How to use the koa-passport.session function in koa-passport

To help you get started, we’ve selected a few koa-passport 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 7kmCo / koa-example / app.js View on Github external
const passport = require('koa-passport');

app = new Koa();
koaqs(app);

// sessions
const session = require('koa-session');
app.keys = ['your-session-secret'];

app
  .use(logger())
  .use(session({}, app))
  .use(bodyParser())
  .use(koaValidator())
  .use(passport.initialize())
  .use(passport.session())
  .use(router.routes())
  .use(router.allowedMethods());

  app.listen(PORT, () => {
    console.log(`Server listening on port: ${PORT}`);
  });
github keattang / eks-auth-proxy / src / index.js View on Github external
// NOTE: Do not parse the body of the incoming request (using body parser or the like)
    // or the proxy will not be able to forward it on.
    app.use(session({}, app));
    app.use(helmet());

    // Set up EJS for rendering HTML
    koaEjs(app, {
        root: path.join(__dirname, '../templates'),
        viewExt: 'ejs',
        layout: false,
    });

    // Set up passport for authentication
    app.use(passport.initialize());
    app.use(passport.session());

    // Redirect users to the login page if they are not authenticated
    app.use(checkAuthenticatedMiddleware);

    // Redirect users to the login page if their AWS creds have expired
    app.use(checkAwsCredentialsMiddleware);

    // Refresh the EKS auth token if it has expired
    app.use(refreshEksTokenMiddleware);

    // Handle routes (e.g. for login)
    app.use(router.routes());
    app.use(router.allowedMethods());

    // Proxy all requests on any path not defined in the router to proxyHost
    app.use(proxyMiddleware);
github snollygolly / koa-starter / index.js View on Github external
// misc handlebars helpers
require("./helpers/handlebars");

// trust proxy
app.proxy = true;

// sessions
app.keys = [config.site.secret];
app.use(session(app));

// body parser
app.use(bodyParser());

// authentication
app.use(passport.initialize());
app.use(passport.session());

// statically serve assets
app.use(mount("/assets", serve("./assets")));

// load up the handlebars middlewear
app.use(hbs.middleware({
	viewPath: `${__dirname}/views`,
	layoutsPath: `${__dirname}/views/layouts`,
	partialsPath: `${__dirname}/views/partials`,
	defaultLayout: "main"
}));


// Error handling middleware
app.use(async(ctx, next) => {
	try {
github allan2coder / react-ssr / app.js View on Github external
app.use(json({ pretty: false })); // send request json
  app.use(serve("", __dirname + "/public")); // use static dir

  // session
  const CONFIG = {
    key: "ssr-react",
    maxAge: 86400000,
    overwrite: true,
    httpOnly: true,
    signed: true
  };
  app.use(session(CONFIG, app)); // authentication

  require("./server/auth/passport.js"); // passport
  app.use(passport.initialize());
  app.use(passport.session());

  app.use(routers); // 路由

  return app;
};
github snollygolly / bloodhound / app.js View on Github external
viewPath: __dirname + '/views',
  layoutsPath: __dirname + '/views/layouts',
  partialsPath: __dirname + '/views/partials',
  defaultLayout: 'main'
}));

// Passport binding.
var config = require('./config.json');
app.keys = config.app.data.session_keys;

app.use(session({
  cookie: {maxAge: 1000 * 60 * 60 * 24},
  store : redisStorage()
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(router(app));

// Adds response-time to headers.
var requestTime = function(headerName){
  return function *(next){
    var start = new Date();
    yield next;
    var end = new Date();
    var ms = end - start;
    this.set(headerName, ms + "ms");
  }
}
app.use(requestTime('Reponse-time'));

//logging
var log = require("./helpers/common.js").log;
github ditojs / dito / packages / server / src / app / Application.js View on Github external
...options
        } = isObject(app.session) ? app.session : {}
        if (modelClass) {
          // Create a ContextStore that resolved the specified model class,
          // uses it to persist and retrieve the session, and automatically
          // binds all db operations to `ctx.transaction`, if it is set.
          // eslint-disable-next-line new-cap
          options.ContextStore = SessionStore(modelClass)
        }
        this.use(session(options, this))
      }
      // 5. passport
      if (app.passport) {
        this.use(passport.initialize())
        if (app.session) {
          this.use(passport.session())
        }
        this.use(emitUserEvents())
      }
      // 6. finally handle the found route, or set status / allow accordingly.
      this.use(handleRoute())
      this.hasControllerMiddleware = true
    }
  }
github adrianObel / koa2-api-boilerplate / bin / server.js View on Github external
const app = new Koa()
app.keys = [config.session]

mongoose.Promise = global.Promise
mongoose.connect(config.database)

app.use(convert(logger()))
app.use(bodyParser())
app.use(session())
app.use(errorMiddleware())

app.use(convert(mount('/docs', serve(`${process.cwd()}/docs`))))

require('../config/passport')
app.use(passport.initialize())
app.use(passport.session())

const modules = require('../src/modules')
modules(app)

app.listen(config.port, () => {
  console.log(`Server started on ${config.port}`)
})

export default app
github cofacts / rumors-api / src / index.js View on Github external
jsonLimit: '10mb',
    textLimit: '10mb',
  })
);

app.keys = (process.env.COOKIE_SECRETS || '').split(',');

app.use(
  session({
    store: new CookieStore({ password: app.keys[0] }),
    signed: true,
    maxAge: process.env.COOKIE_MAXAGE,
  })
);
app.use(passport.initialize());
app.use(passport.session());

router.use('/login', loginRouter.routes(), loginRouter.allowedMethods());
router.use('/callback', authRouter.routes(), authRouter.allowedMethods());

router.options('/logout', checkHeaders());
router.post('/logout', checkHeaders(), ctx => {
  ctx.logout();
  ctx.body = { success: true };
});

router.options('/graphql', checkHeaders());
router.post('/graphql', checkHeaders());

const indexFn = pug.compileFile(path.join(__dirname, 'jade/index.jade'));
const schemaStr = printSchema(schema);
router.get('/', ctx => {
github TryStarboard / Starboard / source / server / util / auth.js View on Github external
});

passport.deserializeUser(wrap(function *(id, done) {
  try {
    const [user] = yield db('users').select('id').where({ id }).limit(1);
    if (!user) {
      throw new Error('user does not exist');
    }
    done(null, user);
  } catch (err) {
    done(err);
  }
}));

export const authInit = passport.initialize();
export const authSession = passport.session();
export const authenticateRequest = passport.authenticate('local');
export const authenticateSignupRequest = passport.authenticate('local-signup');
github sirodoht / aspen / back / app.js View on Github external
const app = module.exports = new Koa();

app.use(logger());

app.use(views(path.join(__dirname, '../front/views'), {
  extension: 'pug',
}));

app.use(bodyParser());

app.keys = [config.sessionSecret];
app.use(session(config.session, app));

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function (user, done) {
  done(null, user.id);
});

passport.deserializeUser(async function (id, done) {
  try {
    const user = await models.User.findOne({
      where: {
        id: {
          [Op.eq]: id,
        },
      },
    });
    done(null, user);
  } catch(err) {