How to use the passport.authenticate function in passport

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 feathersjs-ecosystem / authentication / src / services / oauth2.js View on Github external
return new Promise(function(resolve, reject){
      let middleware = passport.authenticate(`${options.provider}-token`, options.permissions, function(error, user) {
        if (error) {
          return reject(error);
        }

        // Login failed.
        if (!user) {
          return reject(new errors.NotAuthenticated(`An error occurred logging in with ${options.provider}`));
        }

        // Get a new JWT and the associated user from the Auth token service and send it back to the client.
        return app.service(options.tokenEndpoint)
                  .create(user)
                  .then(resolve)
                  .catch(reject);
      });
github OfficeDev / Office-Add-in-Nodejs-ServerAuth / routes / connect.js View on Github external
io.on('connection', function onConnection(socket) {
  var jsonCookie = cookie.parse(socket.handshake.headers.cookie);
  var sessionID = cookieParser.signedCookie(jsonCookie.nodecookie, 'keyboard cat');
  socket.join(sessionID);
});

router.use(csrf());

router.get(
  '/google/:sessionID',
  function handleRequest(req, res, next) {
    authenticationOptions.google.state = req.params.sessionID;
    next();
  },
  passport.authenticate('google', authenticationOptions.google)
);

router.get(
  '/azure/:sessionID',
  function handleRequest(req, res, next) {
    // Include the sessionID and csrftToken value in the OAuth state parameter
    authenticationOptions.azure.state = req.params.sessionID + '|' + req.csrfToken();
    res.cookie('CSRF-TOKEN', req.csrfToken());
    next();
  },
  passport.authenticate('azure', authenticationOptions.azure)
);

router.get('/:providerName/callback', function handleRequest(req, res) {
  // At the end of the OAuth flow we need to verify that csrfToken in the cookies
  // matches the one returned by the OAuth flow
github hirako2000 / hackathon-board / app.js View on Github external
res.redirect(req.session.returnTo || '/');
});
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/linkedin', passport.authenticate('linkedin', { state: 'SOME STATE' }));
app.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});

/**
 * Error Handler.
 */
app.use(errorHandler());

/**
 * Start Express server.
 */
app.listen(app.get('port'), function() {
  console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
});

module.exports = app;
github Scharkee / vue-nuxt-passport-bulma-express-boiler / src / server.js View on Github external
});
  });
});

/*
Sample Passportjs routes
*/
app.get(
  "/auth/google",
  passport.authenticate("google", {
    scope: "profile email"
  })
);
app.get(
  "/auth/google/callback",
  passport.authenticate("google", {
    failureRedirect: "/login"
  }),
  (req, res) => {
    res.redirect(req.session.returnTo || "/");
  }
);
app.get("/auth/twitter", passport.authenticate("twitter"));
app.get(
  "/auth/twitter/callback",
  passport.authenticate("twitter", {
    failureRedirect: "/login"
  }),
  (req, res) => {
    res.redirect(req.session.returnTo || "/");
  }
);
github avoidwork / tenso / src / utility.js View on Github external
consumerKey: config.auth.twitter.consumer_key,
			consumerSecret: config.auth.twitter.consumer_secret,
			callbackURL: realm + "/auth/twitter/callback"
		}, function (token, tokenSecret, profile, done) {
			config.auth.twitter.auth(token, tokenSecret, profile, function (err, user) {
				if (err) {
					delete err.stack;
					return done(err);
				}

				done(null, user);
			});
		}));

		obj.server.get("/auth/twitter", middleware.asyncFlag);
		obj.server.get("/auth/twitter", passport.authenticate("twitter"));
		obj.server.get("/auth/twitter/callback", middleware.asyncFlag);
		obj.server.get("/auth/twitter/callback", passport.authenticate("twitter", {
			successRedirect: config.auth.redirect,
			failureRedirect: "/login"
		}));
	}

	return config;
}
github datosgobar / consulta-publica / ext / lib / api / miargentina.js View on Github external
}

      if (user.email !== email) {
        user.set('email', email)
        user.set('profiles.custom.email', email)
      }

      if (user.profiles.custom.deauthorized) {
        user.set('profiles.custom.deauthorized')
      }

      user.isModified() ? user.save(done) : done(null, user)
    })
  }));

app.get('/login', passport.authenticate('oidc'));

app.use('/authorization-code/callback',
  passport.authenticate('oidc', { failureRedirect: '/error' }),
  (req, res) => {
    jwt.setUserOnCookie(req.user, res)
    res.redirect('/');
  }
);
github TreeGateway / tree-gateway / bin / lib / authentication / auth.js View on Github external
Utils.keys(authentication).forEach(function (key) {
            try {
                var authConfig = authentication[key];
                if (Utils.has(providedStrategies, key)) {
                    var strategy = providedStrategies[key];
                    strategy(apiKey, authConfig, _this.gateway);
                }
                else {
                    var p = pathUtil.join(_this.gateway.middlewarePath, 'authentication', 'strategies', key);
                    var strategy = require(p);
                    strategy(apiKey, authConfig);
                }
                _this.gateway.server.use(path, auth.authenticate(apiKey, { session: false }));
                if (_this.gateway.logger.isDebugEnabled) {
                    _this.gateway.logger.debug("Authentication Strategy [%s] configured for path [%s]", key, path);
                }
            }
            catch (e) {
                _this.gateway.logger.error("Error configuring Authentication Strategy [%s] for path [%s]", key, path, e);
            }
        });
    };
github rucken / core-nestjs / libs / rucken / auth-nestjs / src / auth.module.ts View on Github external
public configure(consumer: MiddlewareConsumer) {
    consumer.apply(authenticate('signup', { session: false, passReqToCallback: true })).forRoutes('api/auth/signup');
    consumer.apply(authenticate('signin', { session: false, passReqToCallback: true })).forRoutes('api/auth/signin');
    consumer
      .apply(authenticate('facebook', { session: false, passReqToCallback: true }))
      .forRoutes('api/auth/facebook/token');
    consumer
      .apply(authenticate('google', { session: false, passReqToCallback: true }))
      .forRoutes('api/auth/google-plus/token');
  }
}