How to use the koa-csrf function in koa-csrf

To help you get started, we’ve selected a few koa-csrf examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github freedomexio / rocketx-condenser / server / server.js View on Github external
// set number of processes equal to number of cores
// (unless passed in as an env var)
const numProcesses = process.env.NUM_PROCESSES || os.cpus().length;

app.use(requestTime());

app.keys = [config.get('session_key')];

const crypto_key = config.get('server_session_secret');
session(app, {
    maxAge: 1000 * 3600 * 24 * 60,
    crypto_key,
    key: config.get('session_cookie_key')
});
csrf(app);

app.use(mount(grant));
app.use(flash({ key: 'flash' }));

function convertEntriesToArrays(obj) {
    return Object.keys(obj).reduce((result, key) => {
            result[key] = obj[key].split(/\s+/);
    return result;
}, {});
}

const service_worker_js_content = fs
    .readFileSync(path.join(__dirname, './service-worker.js'))
    .toString();

// some redirects
github freedomexio / rocketx-condenser / src / server / server.js View on Github external
// (unless passed in as an env var)
const numProcesses = process.env.NUM_PROCESSES || os.cpus().length;

const statsLoggerClient = new StatsLoggerClient(process.env.STATSD_IP);

app.use(requestTime(statsLoggerClient));

app.keys = [config.get('session_key')];

const crypto_key = config.get('server_session_secret');
session(app, {
    maxAge: 1000 * 3600 * 24 * 60,
    crypto_key,
    key: config.get('session_cookie_key'),
});
csrf(app);

koaLocale(app);

function convertEntriesToArrays(obj) {
    return Object.keys(obj).reduce((result, key) => {
        result[key] = obj[key].split(/\s+/);
        return result;
    }, {});
}

// Fetch cached currency data for homepage
const steemMarket = new SteemMarket();
app.use(function*(next) {
    this.steemMarketData = yield steemMarket.get();
    yield next;
});
github Someguy123 / understeem / server / server.js View on Github external
import flash from 'koa-flash';
import minimist from 'minimist';
import Grant from 'grant-koa';
import config from '../config';

const grant = new Grant(config.grant);
// import uploadImage from 'server/upload-image' //medium-editor

const app = new Koa();
app.name = 'Steemit app';
const env = process.env.NODE_ENV || 'development';
const cacheOpts = {maxAge: 86400000, gzip: true};

app.keys = [config.session_key];
app.use(session({maxAge: 1000 * 3600 * 24 * 7}, app));
csrf(app);
app.use(mount(grant));
app.use(flash({key: 'flash'}));

// redirect to home page if known account
// remember ch, cn, r url params in the session and remove them from url
app.use(function *(next) {
    if (this.method === 'GET' && this.url === '/' && this.session.a) {
        this.status = 301;
        this.redirect(`/@${this.session.a}/feed`);
        return;
    }
    if (this.method === 'GET' && /\?[^\w]*(ch=|cn=|r=)/.test(this.url)) {
        let redir = this.url.replace(/((ch|cn|r)=[^&]+)/gi, r => {
            const p = r.split('=');
            if (p.length === 2) this.session[p[0]] = p[1];
            return '';
github embbnux / kails / app / index.js View on Github external
const method = req.body._method;
    delete req.body._method;
    return method;
  }
}));
app.use(convert(json()));
app.use(convert(logger()));

//views with pug
app.use(views(__dirname + '/views', { extension: 'pug' }));

// catch error
app.use(middlewares.catchError);

// csrf
app.use(new CSRF({
  invalidSessionSecretMessage: 'Invalid session secret',
  invalidSessionSecretStatusCode: 403,
  invalidTokenMessage: 'Invalid CSRF token',
  invalidTokenStatusCode: 403,
  excludedMethods: [ 'GET', 'HEAD', 'OPTIONS' ],
  disableQuery: false
}));

// add helpers for views
app.use(middlewares.addHelper);
app.use(flashMessage);

app.use(router.routes(), router.allowedMethods());

if (process.argv[2] && process.argv[2][0] == 'c') {
  const repl = require('repl');
github ecmadao / hacknical / app / bin / app.js View on Github external
httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
  renew: true, /** (boolean) renew session when session is nearly expired */
}
app.use(session(CONFIG, app))

// cache
app.use(redisMiddleware())
// mq
app.use(mqMiddleware())
// locale
app.use(localeMiddleware())
// catch error
app.use(errorMiddleware())
// csrf
app.use(new Csrf())
// helper func
app.use(async (ctx, next) => {
  ctx.state = Object.assign({}, ctx.state, {
    assetsPath: assetsMiddleware,
    csrf: ctx.csrf,
    env: process.env.NODE_ENV,
    footer: {
      about: ctx.__('dashboard.about'),
      feedback: ctx.__('dashboard.feedback'),
      code: ctx.__('dashboard.code'),
    }
  })
  await next()
})

// 配置nunjucks模板文件所在的路径,否则模板继承时无法使用相对路径
github ShieldBattery / ShieldBattery / server / app.js View on Github external
if (err instanceof TypeError || err instanceof SyntaxError || err instanceof ReferenceError) {
    // These types are very unlikely to be handle-able properly, exit
    throw err
  }
  // Other promise rejections are likely less severe, leave the process up but log it
})

app
  .use(logMiddleware())
  .use(koaError()) // TODO(tec27): Customize error view
  .use(koaCompress())
  .use(views(path.join(__dirname, 'views'), { extension: 'jade' }))
  .use(koaBody())
  .use(sessionMiddleware)
  .use(onlyWebClients(csrfCookie()))
  .use(onlyWebClients(new Csrf()))
  .use(secureHeaders())
  .use(secureJson())
  .use(userIpsMiddleware())
  .use(userSessionsMiddleware())
  .use(emailSessionMiddleware())

const mainServer = http.createServer(app.callback())

import setupWebsockets from './websockets'
const { nydus, userSockets } = setupWebsockets(mainServer, app, sessionMiddleware)

import createRoutes from './routes'
// Wrapping this in IIFE so we can use top-level `await` (until node implements it natively)
;(async () => {
  if (isDev) {
    const koaWebpack = require('koa-webpack')
github ecmadao / Learn-Koa2 / app / app.js View on Github external
// json parse
app.use(convert(json()));
// logger
app.use(convert(logger()));
// catch error
app.use(catchError)
// session
app.use(convert(session(app)));
// or you can use MongoStore as session,
// but you must connect mongo server first
// app.use(convert(session({
//   store: new MongoStore()
// })));

// csrf
app.use(new csrf());
// helper func
app.use(async (ctx, next) => {
  ctx.state = {
    csrf: ctx.csrf,
    assetsPath
  };
  await next();
});
// 配置nunjucks模板文件所在的路径,否则模板继承时无法使用相对路径
nunjucks.configure(path.join(__dirname, './templates'), { autoescape: true });
// flash
app.use(convert(flash()));
// frontend static file
app.use(convert(require('koa-static')(path.join(__dirname, '../public'))));
//views with nunjucks
app.use(views(path.join(__dirname, './templates'), {
github hung-phan / koa-react-isomorphic / app / server / infrastructure / middlewares / index.js View on Github external
export const securityLayer = (app: Object) => {
  app.keys = [process.env.SECRET_KEY];

  const csrf = new CSRF();

  app
    .use(session({ maxAge: 86400000 }, app)) // https://github.com/koajs/session
    .use((ctx, next) => {
      // don't check csrf for request coming from the server
      if (ctx.get("x-app-secret") === process.env.SECRET_KEY) {
        return next();
      }

      return csrf(ctx, next);
    }) // https://github.com/koajs/csrf
    .use(helmet()); // https://github.com/venables/koa-helmet
};
github ecmadao / hacknical / app / bin / app.js View on Github external
renew: true, /** (boolean) renew session when session is nearly expired */
};
app.use(session(CONFIG, app));

// cache
app.use(redisMiddleware({
  url: redis
}));
// mq
app.use(mqMiddleware());
// locale
app.use(checkLocale());
// catch error
app.use(catchError());
// csrf
app.use(new Csrf());
// helper func
app.use(async (ctx, next) => {
  ctx.state = Object.assign({}, ctx.state, {
    assetsPath,
    csrf: ctx.csrf,
    env: process.env.NODE_ENV,
    footer: {
      about: ctx.__('dashboard.about'),
      feedback: ctx.__('dashboard.feedback'),
      code: ctx.__('dashboard.code'),
    },
  });
  await next();
});

// 配置nunjucks模板文件所在的路径,否则模板继承时无法使用相对路径
github bugulink / bugu-web / src / routes.js View on Github external
ctx.cookies.set('XSRF-TOKEN', ctx.csrf, {
      httpOnly: false
    });
    await next();
  }

  async function linkCombine(ctx, next) {
    if (ctx.path === '/combine/callback') {
      await link.combine(ctx);
    } else {
      await next();
    }
  }

  app.use(linkCombine);
  app.use(new CSRF());
  app.use(injectParams);
  app.use(router.routes());
  app.use(router.allowedMethods());
}

koa-csrf

CSRF tokens for Koa

MIT
Latest version published 2 years ago

Package Health Score

56 / 100
Full package analysis

Popular koa-csrf functions