• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript helmet.xssFilter函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中helmet.xssFilter函数的典型用法代码示例。如果您正苦于以下问题:TypeScript xssFilter函数的具体用法?TypeScript xssFilter怎么用?TypeScript xssFilter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了xssFilter函数的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: init

export function init(appConfig: Config): express.Express {
  // Notas de configuración de express http://expressjs.com/es/guide/using-middleware.html#middleware.application
  const app = express();
  app.set("port", appConfig.port);

  // Habilitar Cors
  app.use(cors({
    origin: true,
    optionsSuccessStatus: 200,
    credentials: true
  }));

  // Si estamos en level debug, debaguear los request
  if (appConfig.logLevel == "debug") {
    app.use(morgan("dev"));
  }

  // Configuramos el server para que tome los json correctamente
  app.use(bodyParser.urlencoded({ extended: true, limit: "20mb" }));
  app.use(bodyParser.json({ limit: "5mb" }));

  // Configurar express para comprimir contenidos de text en http
  app.use(compression());

  // Configuramos passport, autentificación por tokens y db
  app.use(passport.initialize());
  app.use(passport.session());

  // Permite hacer validaciones de parámetros req.assert
  app.use(expressValidator());

  // helmet le da seguridad al sistema para prevenir hacks
  app.use(helmet.xssFilter());  // Previene inyección de javascript
  app.use(helmet.noSniff());
  app.use(helmet.ieNoOpen());
  app.disable("x-powered-by");

  // Esta es la ruta de contenidos estáticos, no deberían haber muchos pero algo de documentación
  // vendría bien como contenido estático.
  app.use(
    express.static(path.join(__dirname, "../public"), { maxAge: 31557600000 })
  );

  // Iniciamos nuestros módulos
  passportHandler.init();

  // Iniciamos las rutas del directorio
  // mas sobre rutas http://expressjs.com/es/guide/routing.html
  indexModule.init(app);
  mascotasModule.init(app);
  comentariosModule.init(app);
  postModule.init(app);
  foroModule.init(app);
  perfilModule.init(app);
  provinciasModule.init(app);
  seguridadModule.init(app);
  imageModule.init(app);

  // Para el manejo de errores, para que los loguee en la consola
  app.use(errorHandler.logErrors);

  // Responder con JSON cuando hay un error 404, sino responde con un html
  // Esto tiene que ir al final porque sino nos sobreescribe las otras rutas
  app.use(errorHandler.handle404);

  return app;
}
开发者ID:maticorv,项目名称:mascotas2018_foro,代码行数:67,代码来源:express.factory.ts


示例2: constructor

    constructor(options) {

        super();

        // In case of no options
        !options && (options = {});

        // Load default configuration
        this.config = require('../defaultServerConfig.js');

        // Set initial status
        this.status = -1;

        // Overwrite defaults
        for (let option in options)
            this.config[option] = options[option];

        // Create the express app
        this.server = express();

        // Use compression on all requests
        // @todo toggle compression with optional parameter
        //this.server.use(compression({threshold:0}));

        // Create router
        this.router = express.Router();

        // Set upload limit
        this.server.use(bodyParser.raw({
            limit: this.config.uploadLimit
        }));

        // Block libwww-perl
        this.server.use(
            (req, res, next) =>
                /libwww-perl/.test(req.get('user-agent')) ? res.status(403).end() : next());

        // Parse json api requests
        this.server.use(bodyParser.urlencoded({ extended: true }));
        this.server.use(bodyParser.json());


        // Add headers
        this.server.use((req, res, next) => {

            if (this.config.serverHeader)
                res.setHeader(
                    'Server',
                    'ZenX/' + packageInfo.version);

            res.setHeader('Connection', 'Keep-Alive');
            res.setHeader('Keep-Alive', 'timeout=15, max=100');

            return next();

        });

        // Standard middleware
        this.server.use(helmet.xssFilter());
        this.server.use(cookieParser());
        this.server.use(multipart());
        this.server.use(methodOverride());

        // Disable x-powered-by header
        this.server.disable('x-powered-by');

        // A route to be used later
        this.server.use(this.router);

        // If a static content path was provided
        if (this.config.static) {

            // Always add cache control header
            this.server.use(function(req, res, next) {

                res.setHeader("Cache-Control", "max-age=31104000, public");
                res.setHeader('Expires',
                    new Date(Date.now() + 345600000).toUTCString());

                return next();

            });

            // Serve static content
            this.server.use(
                express.static(
                    path.resolve(this.config.static)));

        }

        // Not found
        this.server.get('*', function(req, res) {

            res.writeHead(404, 'Not found');

            res.end('404: Not found');

        });

        var config = this.config;
//.........这里部分代码省略.........
开发者ID:raelgor,项目名称:zen-arena,代码行数:101,代码来源:Server.ts


示例3: Middleware

/*=====  End of MODULES  ======*/

/**
 * Orchestrates the middleware tools for the Express Application
 * @param  {Object} app Express Application
 */
export default function Middleware(app: express.Express) {
  const env = process.env.NODE_ENV;

  /*=============================================>>>>>
  = IMPORT DATABASE TABLES ORM =
  ===============================================>>>>>*/

  const Models = new db();
  const Users = Models.Users;

  /*= End of IMPORT DATABASE TABLES ORM =*/
  /*=============================================<<<<<*/

  const sess = {
    name:         'nodeStarter.sid',
    genid: (req: express.Request) => {
      // use UUIDs for session IDs
      return uuid.v4();
    },
    resave:            true,
    rolling:           true,
    saveUninitialized: false,
    secret:            process.env.SECRET,
    store:             sessionStore
  };

  if (env === 'development' || env === 'staging') {
    app.use(errorhandler({log: (err: Error, str: string, req: express.Request) => {
      log.debug('===== SHOWING ERROR =====');
      log.debug(str);
      log.debug(req.method);
      log.debug(req.url);
      log.debug('===== END ERROR DISPLAY =====');
    }}));
  } else {
    // trust first proxy
    app.set('trust proxy', 1);
    // sess.cookie.secure = true; // serve secure cookies
    /* Turn on View Caching */
    app.set('view cache', true);
  }

  /*=============================================>>>>>
  = SECURITY MIDDLEWARE =
  ===============================================>>>>>*/

  /* Prevent XSS Attacks */
  app.use(helmet.xssFilter());
  /* Prevents click jacking */
  app.use(helmet.frameguard('deny'));
  /* Enforces users to use HTTPS (requires HTTPS/TLS/SSL) */
  // app.use(helmet.hsts({ maxAge: process.env.APP_HTTPS_TIMEOUT }));
  /* Hides x-powered-by header */
  app.use(helmet.hidePoweredBy());
  /* Prevent MIME type sniffing */
  app.use(helmet.noSniff());
  /* Disable Caching */
  app.use(helmet.noCache());
  /* Prevent Parameter Pollution */
  app.use(hpp());

  /*= End of SECURITY MIDDLEWARE =*/
  /*=============================================<<<<<*/

  /*=============================================>>>>>
  = SERVER MIDDLEWARE =
  ===============================================>>>>>*/

  /* Enables CORS Headers */
  app.use(cors());
  /* Establishes an Express Session */
  app.use(session(sess));
  /* Imports Passport Middleware */
  app.use(passport.initialize());
  /* Manages the same Cookie Session */
  app.use(passport.session());
  /* Parses the request body */
  app.use(bodyParser.urlencoded({ extended: false }));
  /* Returns request body as JSON */
  app.use(bodyParser.json());
  /* GZIP everything */
  app.use(compression());
  /* Establishes CORS headers */
  app.options(process.env.CORS, cors());

  /*= End of SERVER MIDDLEWARE =*/
  /*=============================================<<<<<*/

  passport.serializeUser((user: any, done: Function) => {
    done(null, user.token);
  });

  passport.deserializeUser((token: any, done: Function) => {
    Users.findOne({
//.........这里部分代码省略.........
开发者ID:organization-for-testing,项目名称:gig-546f34e3f4dad50200e03ce8-practical-frozen-table,代码行数:101,代码来源:middleware.ts


示例4: baseMiddleware

/**
 * Denali ships with several base middleware included, each of which can be enabled/disabled
 * individually through config options.
 */
export default function baseMiddleware(router: Router, application: Application): void {

  let config = application.config;

  /**
   * Returns true if the given property either does not exist on the config object, or it does exist
   * and it's `enabled` property is not `false`. All the middleware here are opt out, so to disable
   * you must define set that middleware's root config property to `{ enabled: false }`
   */
  function isEnabled(prop: string): boolean {
    return !config[prop] || (config[prop] && config[prop].enabled !== false);
  }

  if (isEnabled('timing')) {
    router.use(timing());
  }

  if (isEnabled('logging')) {
    let defaultLoggingFormat = application.environment === 'production' ? 'combined' : 'dev';
    let defaultLoggingOptions = {
      // tslint:disable-next-line:completed-docs
      skip(): boolean {
        return application.environment === 'test';
      }
    };
    let format = (config.logging && config.logging.format) || defaultLoggingFormat;
    let options = defaults(config.logging || {}, defaultLoggingOptions);
    router.use(morgan(format, options));

    // Patch morgan to read from our non-express response
    morgan.token('res', (req: IncomingMessage, res: ServerResponse, field: string) => {
      let header = res.getHeader(field);
      return Array.isArray(header) ? header.join(', ') : header;
    });
  }

  if (isEnabled('compression')) {
    router.use(compression());
  }

  if (isEnabled('cookies')) {
    router.use(cookies(config.cookies));
  }

  if (isEnabled('cors')) {
    router.use(cors(config.cors));
  }

  if (isEnabled('xssFilter')) {
    router.use(helmet.xssFilter());
  }

  if (isEnabled('frameguard')) {
    router.use(helmet.frameguard());
  }

  if (isEnabled('hidePoweredBy')) {
    router.use(helmet.hidePoweredBy());
  }

  if (isEnabled('ieNoOpen')) {
    router.use(helmet.ieNoOpen());
  }

  if (isEnabled('noSniff')) {
    router.use(helmet.noSniff());
  }

  if (isEnabled('bodyParser')) {
    router.use(json({ type: config.bodyParser && config.bodyParser.type }));
  }

}
开发者ID:acburdine,项目名称:denali,代码行数:77,代码来源:middleware.ts


示例5: next

app.use(cookieParser(COOKIE_SECRET))

// compress all 'compressible' requests
// https://github.com/expressjs/compression
app.use(compression())
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

app.disable('x-powered-by');

app.use(morgan('combined'));

app.use(helmet.frameguard());
app.use(helmet.xssFilter());
app.use(helmet.noSniff());
app.use(helmet.ieNoOpen());
app.use(csp);

if (process.env.NODE_ENV !== 'production') {
  app.use(function(req, res, next){
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS PUT DELETE')
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
    next()
  })
  app.use('/js', express.static(root + '/nginx/static/js'));
  app.use('/css', express.static(root + '/nginx/static/css'));
  
  app.use('/api/test', authenticate,
开发者ID:memolog,项目名称:mean-edge,代码行数:31,代码来源:server.ts


示例6: require

var express:any       = require('express');
var helmet:any        = require('helmet');
var path:any          = require('path');
var favicon:any       = require('serve-favicon');
var logger:any        = require('morgan');
var cookieParser:any  = require('cookie-parser');
var bodyParser:any    = require('body-parser');
var routes            = require('./routes/index');

var app:any           = express();

app.use(helmet());
app.use(helmet.noCache());
app.use(helmet.frameguard());
app.use(helmet.xssFilter({ setOnOldIE: true }));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
开发者ID:soojinkim22,项目名称:sooocode,代码行数:30,代码来源:app.ts



注:本文中的helmet.xssFilter函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript oauth-helper.OAuthHelper类代码示例发布时间:2022-05-25
下一篇:
TypeScript helmet.noCache函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap