How to use passport - 10 common examples

To help you get started, we’ve selected a few 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 boutell / justjs / server.js View on Github external
app.use(passport.initialize());
  app.use(passport.session());

  // Borrowed from http://passportjs.org/guide/twitter.html

  // Redirect the user to Twitter for authentication.  When complete, Twitter
  // will redirect the user back to the application at
  // /auth/twitter/callback
  app.get('/auth/twitter', passport.authenticate('twitter'));

  // Twitter will redirect the user to this URL after approval.  Finish the
  // authentication process by attempting to obtain an access token.  If
  // access was granted, the user will be logged in.  Otherwise,
  // authentication has failed.
  app.get('/auth/twitter/callback', 
    passport.authenticate('twitter', { successRedirect: '/',
                                       failureRedirect: '/login' }));

  app.get('/logout', function(req, res)
  {
    req.logOut();
    res.redirect('/');
  });
  console.log("Installed passport.initialize");
}
github ZeroCho / nodejs-book / ch10 / 10.2 / nodebird-api / routes / auth.js View on Github external
if (loginError) {
        console.error(loginError);
        return next(loginError);
      }
      return res.redirect('/');
    });
  })(req, res, next); // 미들웨어 내의 미들웨어에는 (req, res, next)를 붙입니다.
});

router.get('/logout', isLoggedIn, (req, res) => {
  req.logout();
  req.session.destroy();
  res.redirect('/');
});

router.get('/kakao', passport.authenticate('kakao'));

router.get('/kakao/callback', passport.authenticate('kakao', {
  failureRedirect: '/',
}), (req, res) => {
  res.redirect('/');
});

module.exports = router;
github kogg / hovercards / server / v2.js View on Github external
var TwitterStrategy = require('passport-twitter').Strategy;
var errors          = require('feathers-errors');
var feathers        = require('feathers');
var passport        = require('passport');
// var promisify       = require('es6-promisify');
var session         = require('express-session');
var RedisStore      = require('connect-redis')(session);

var config       = require('../integrations/config');
var integrations = require('../integrations');
var redis        = require('./redis');

var CHROMIUM_IDS = process.env.CHROMIUM_IDS.split(';');

// HACK This only applied to twitter
passport.use(new TwitterStrategy({
	consumerKey:    process.env.TWITTER_CONSUMER_KEY,
	consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
	callbackURL:    '/v2/twitter/callback'
}, function(token, tokenSecret, profile, callback) {
	redis.set('auth:twitter:' + token, tokenSecret, _.partial(callback, _, token));
}));

module.exports = feathers.Router()
	.use(session({
		store:             new RedisStore({ client: redis }),
		secret:            (process.env.SECURE_KEY || '').split(','),
		saveUninitialized: false,
		resave:            false
	}))
	.use(passport.initialize())
	.use(passport.session())
github r03ert0 / microdraw / app / auth / local.js View on Github external
module.exports = (app)=>{

  passport.use(new LocalStrategy(
    (username,password,done)=>{
      console.log('querying db')
      app.db.queryUser({
        username 
      })
        .then(user=>{

          /* never use md5 to store passwords*/
          // done(null, user ? 
          //   user.password === md5(password) ?
          //     user :
          //     false :
          //   false)

          /* bcrypt -> more secure */
          bcrypt.compare(password,user.passhash)
github physiii / open-automation / server / website.js View on Github external
// Support JSON encoded bodies.
	app.use(bodyParser.json());

	// Support encoded bodies.
	app.use(bodyParser.urlencoded({extended: true}));

	// Support gzip and deflate.
	app.use(compression());

	app.use(passport.initialize());
	app.use(passport.session());
	passport.serializeUser((user, done) => {
		done(null, user);
	});

	passport.use(new LocalStrategy((username, password, done) => {
		const account = AccountsManager.getAccountByUsername(username);

		if (!account) {
			console.log(TAG, 'Login ' + username + ': account not found.');
			return done(null, false);
		}

		account.isCorrectPassword(password).then((is_correct) => {
			if (!is_correct) {
				console.log(TAG, 'Login ' + username + ': incorrect password.');
				return done(null, false);
			}

			// Password is correct.
			return done(null, account);
		}).catch(() => {
github bradtraversy / nodeauthapp / app.js View on Github external
// Port Number
const port = 3000;

// CORS Middleware
app.use(cors());

// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));

// Body Parser Middleware
app.use(bodyParser.json());

// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());

require('./config/passport')(passport);

app.use('/users', users);

// Index Route
app.get('/', (req, res) => {
  res.send('Invalid Endpoint');
});

// Start Server
app.listen(port, () => {
  console.log('Server started on port '+port);
});
github avoidwork / tenso / lib / utility.js View on Github external
obj.always(luscaNoSniff).blacklist(luscaNoSniff);
	}

	// Can fork to `middleware.keymaster()`
	obj.always(middleware.zuul).blacklist(middleware.zuul);

	passportInit = passport.initialize();
	obj.always(passportInit).blacklist(passportInit);

	if (stateless === false) {
		passportSession = passport.session();
		obj.always(passportSession).blacklist(passportSession);
	}

	passport.serializeUser((user, done) => done(null, user));
	passport.deserializeUser((arg, done) => done(null, arg));

	if (config.auth.basic.enabled) {
		let x = {};

		const validate = (arg, cb) => {
			if (x[arg] !== void 0) {
				cb(null, x[arg]);
			} else {
				cb(new Error(STATUS_CODES[401]), null);
			}
		};

		each(config.auth.basic.list || [], i => {
			let args = i.split(":");

			if (args.length > 0) {
github bonham000 / react-quiz-app / src / server / index.js View on Github external
app.use(express.static('dist/client'));

app.use(cookieParser(secretString));
app.use(session({
  secret: secretString,
  resave: true,
  secure: false,
  saveUninitialized: true
}));

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

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

// connect authentication and api routes
app.use(passportRoutes);
app.use(apiRoutes);

app.use(fallback(path.join(__dirname, '../../dist/client/index.html')));

app.listen(PORT, (err) => {
  if (err) throw err;
  console.log(`The Express Server is Listening at port ${PORT} in ${NODE_ENV} mode`);
});

export default app;
github AzureAD / passport-azure-ad / lib / bearerstrategy.js View on Github external
// (2) common endpoint is not supported
  //---------------------------------------------------------------------------

  // for B2C, 
  if (options.isB2C) {
    if (!options.policyName || !CONSTANTS.POLICY_REGEX.test(options.policyName))
      throw new Error('In BearerStrategy constructor: invalid policy for B2C');
  }

  // if logging level specified, switch to it.
  if (options.loggingLevel) { log.levels('console', options.loggingLevel); }

  log.info(`In BearerStrategy constructor: created strategy with options ${JSON.stringify(options)}`);
}

util.inherits(Strategy, passport.Strategy);

Strategy.prototype.jwtVerify = function jwtVerifyFunc(req, token, metadata, optionsToValidate, done) {
  const self = this;

  const decoded = jws.decode(token);
  let PEMkey = null;

  if (decoded == null) {
    return done(null, false, 'In Strategy.prototype.jwtVerify: Invalid JWT token.');
  }

  log.info('In Strategy.prototype.jwtVerify: token decoded:  ', decoded);

  // When we generate the PEMkey, there are two different types of token signatures
  // we have to validate here. One provides x5t and the other a kid. We need to call 
  // the right one.
github yunchancho / oauth2-restapi-server / routes / auth / externals / google.js View on Github external
state: 'success',
                data: req.user.access_token
            });
        } else {
            res.render('extenral_account_oauth', { 
                state: 'failure', 
                data: {
                    message: "Google+ authentication failed :("
                }
            });
        }
    });

    // connect to current session
    router.get('/auth/connect/google',
            passport.authorize('google', {
                scope : 'email'
            })
    );

    // disconnect from current session
    router.get('/auth/disconnect/google',
            function (req, res) {
                console.log('disconnect google');
                if (!req.user) {
                    res.send(401, { reason: 'not-authenticated' });
                } else {
                    var user = req.user;
                    user.google = undefined;
                    console.log('google info: ' + req.user.google);
                    user.save(function (err) {
                        if (err) {