Javascript 护照JS+;NodeJS:在成功或失败后不重定向404页
我正在尝试实现PassportJS local、facebook、twitter和google身份验证+保存到在线mongodb mongodb数据库。注册或登录工作正常,并保存到数据库。一旦成功,它应该重定向到/profile页面,如果失败,它应该返回到/login页面或/register页面。两者都不起作用,他们都给我404错误页面 它应该重定向到的文件(/profile)是可访问的&工作正常。它只是无法重定向成功,甚至在失败时也无法重定向 任何帮助都会很好 Passport.js Route.js Login.htmlJavascript 护照JS+;NodeJS:在成功或失败后不重定向404页,javascript,node.js,mongodb,passport.js,Javascript,Node.js,Mongodb,Passport.js,我正在尝试实现PassportJS local、facebook、twitter和google身份验证+保存到在线mongodb mongodb数据库。注册或登录工作正常,并保存到数据库。一旦成功,它应该重定向到/profile页面,如果失败,它应该返回到/login页面或/register页面。两者都不起作用,他们都给我404错误页面 它应该重定向到的文件(/profile)是可访问的&工作正常。它只是无法重定向成功,甚至在失败时也无法重定向 任何帮助都会很好 Passport.js Rout
登录
或
电子邮件地址
密码
记得我吗
让我登录
| |
Register.html
签约
或
名称
电子邮件
密码
重新输入密码
给我报名
|
单击“注册”表示您同意我们的条款,并且您已经阅读了我们的Cookie使用
编辑
来自节点的morgan logger的一些屏幕截图:
尝试在
router.post中更改您的successRedirect:“login”
(“/login”…
从/
=>/login
开始,我也尝试过这个,但效果相同。Stil将我重定向到404页面使用google strategy图像登录显示了许多404。为什么?从我的404页面,我可以返回主页。但出于某种原因,它有时再也无法识别任何东西,就像被从我的服务器踢出,再也找不到任何页面。如果有意义的话。(它停留在404页面上)尝试更改路由器.post中的成功重定向:“login”
(“/login”…
从/
=>/login
开始,我也尝试过这个,但效果相同。Stil将我重定向到404页面使用google strategy图像登录显示了许多404。为什么?从我的404页面,我可以返回主页。但出于某种原因,它有时再也无法识别任何东西,就像被踢出我的服务器,再也找不到任何页面。如果这有意义的话。(它停留在404页面上)
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var TwitterStrategy = require('passport-twitter').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
// load up the user model
var User = require('../data/schema/user');
// load the auth variables
var configAuth = require('./auth');
module.exports = function(passport) {
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function (user, done) {
User.findById(id, function (err, user) {
done(null, user);
});
});
// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password'
//passReqToCallback : true // allows us to pass back the entire request to the callback
},
function (req, email, password, done)
{
// callback with email and password from our form
process.nextTick(function(){
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function (err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
// if the user is found but the password is wrong
if (!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, user);
});
});
}));
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('signUp', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null);
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
// =========================================================================
// FACEBOOK ================================================================
// =========================================================================
passport.use('facebook',new FacebookStrategy({
// pull in our app id and secret from our authSchema.js file
clientID : configAuth.facebookAuth.clientID,
clientSecret : configAuth.facebookAuth.clientSecret,
callbackURL : configAuth.facebookAuth.callbackURL
},
// facebook will send back the token and profile
function(token, refreshToken, profile, done) {
// asynchronous
process.nextTick(function() {
// find the user in the database based on their facebook id
User.findOne({ 'facebook.id' : profile.id }, function(err, user) {
// if there is an error, stop everything and return that
// ie an error connecting to the database
if (err)
return done(err);
// if the user is found, then log them in
if (user) {
return done(null, user); // user found, return that user
} else {
// if there is no user found with that facebook id, create them
var newUser = new User();
// set all of the facebook information in our user model
newUser.facebook.id = profile.id; // set the users facebook id
newUser.facebook.token = token; // we will save the token that facebook provides to the user
newUser.facebook.name = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned
newUser.facebook.email = profile.emails[0].value; // facebook can return multiple emails so we'll take the first
// save our user to the database
newUser.save(function(err) {
if (err)
throw err;
// if successful, return the new user
return done(null, newUser);
});
}
});
});
}));
// =========================================================================
// TWITTER =================================================================
// =========================================================================
passport.use('twitte',new TwitterStrategy({
consumerKey : configAuth.twitterAuth.consumerKey,
consumerSecret : configAuth.twitterAuth.consumerSecret,
callbackURL : configAuth.twitterAuth.callbackURL
},
function(token, tokenSecret, profile, done) {
// make the code asynchronous
// User.findOne won't fire until we have all our data back from Twitter
process.nextTick(function() {
User.findOne({ 'twitter.id' : profile.id }, function(err, user) {
// if there is an error, stop everything and return that
// ie an error connecting to the database
if (err)
return done(err);
// if the user is found then log them in
if (user) {
return done(null, user); // user found, return that user
} else {
// if there is no user, create them
var newUser = new User();
// set all of the user data that we need
newUser.twitter.id = profile.id;
newUser.twitter.token = token;
newUser.twitter.username = profile.username;
newUser.twitter.displayName = profile.displayName;
// save our user into the database
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
// =========================================================================
// GOOGLE ==================================================================
// =========================================================================
passport.use('google',new GoogleStrategy({
clientID : configAuth.googleAuth.clientID,
clientSecret : configAuth.googleAuth.clientSecret,
callbackURL : configAuth.googleAuth.callbackURL
},
function(token, refreshToken, profile, done) {
// make the code asynchronous
// User.findOne won't fire until we have all our data back from Google
process.nextTick(function() {
// try to find the user based on their google id
User.findOne({ 'google.id' : profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
// if a user is found, log them in
return done(null, user);
} else {
// if the user isnt in our database, create a new user
var newUser = new User();
// set all of the relevant information
newUser.google.id = profile.id;
newUser.google.token = token;
newUser.google.name = profile.displayName;
newUser.google.email = profile.emails[0].value; // pull the first email
// save the user
newUser.save(function(err) {
// if successful, return the new user
if (err) throw err;
return done(null, newUser);
});
}
});
});
}));
};
var express = require('express');
var router = express.Router();
var passport = require('passport');
var Events = require('../data/schema/events.js');
// =====================================
// HOME PAGE (with login links) ========
// =====================================
router.get('/', function(req, res) {
res.render('landing');
});
// =====================================
// EVENTS PAGE =========================
// =====================================
router.get('/events', function(req, res) {
res.render('events');
});
// =====================================
// GROUPS PAGE =========================
// =====================================
router.get('/groups', function(req, res) {
res.render('groups');
});
// =====================================
// PROFILE SECTION =====================
// =====================================
// we will want this protected so you have to be logged in to visit
// we will use route middleware to verify this (the isLoggedIn function)
router.get('/profile',isLoggedIn, function (req , res) {
res.render('profile.jade',{ title: 'Profile', user: req.user});
});
// =====================================
// LOGIN ===============================
// =====================================
// show the login form
router.get('/login', function(req, res) {
res.render('login');
});
// process the login form
router.post('/login', passport.authenticate('login', {
successRedirect : 'profile', // redirect to the secure profile section
failureRedirect : 'login' // redirect back to the signup page if there is an error
}));
//router.post('/login', function(req, res, next) {
// passport.authenticate('local', function(err, user, info) {
// if (err) { return next(err); }
// // if user is not found due to wrong username or password
// if (!user) {
// return res.render('login', {
// //you can send a message to your view
// message: 'Invalid username or password'
// });
// }
// //passport.js has a logIn user method
// req.logIn(user, function(err) {
// if (err) { return next(err); }
//
// return res.redirect('/');
// });
// })(req, res, next);
//});
// =====================================
// FORGOTPW ============================
// =====================================
// show the login form
router.get('/forgotpw', function(req, res) {
res.render('forgotpw');
});
// process the signup form
router.post('/forgotpw', passport.authenticate('signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/forgotpw' // redirect back to the signup page if there is an error
}));
// =====================================
// SIGNUP ==============================
// =====================================
// show the signup form
router.get('/register', function (req, res) {
res.render('register');
});
// process the signup form
router.post('/register', passport.authenticate('signUp', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/register' // redirect back to the signup page if there is an error
}));
// =====================================
// LOGOUT ==============================
// =====================================
router.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
// =====================================
// 404 =================================
// =====================================
router.get('/400',function(req,res){
res.render('404');
});
// =====================================
// 500 =================================
// =====================================
router.get('/500',function(req,res){
res.render('500');
});
// =============================================================================
// AUTHENTICATE (FIRST LOGIN) ==================================================
// =============================================================================
// =====================================
// FACEBOOK ROUTES =====================
// =====================================
// route for facebook authentication and login
router.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));
// handle the callback after facebook has authenticated the user
router.get('/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash: true
}));
// =====================================
// TWITTER ROUTES ======================
// =====================================
// route for twitter authentication and login
router.get('/auth/twitter', passport.authenticate('twitter'));
// handle the callback after twitter has authenticated the user
router.get('/auth/twitter/callback', passport.authenticate('twitter', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash: true
}));
// =====================================
// GOOGLE ROUTES =======================
// =====================================
// send to google to do the authentication
// profile gets us their basic information including their name
// email gets their emails
router.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));
// the callback after google has authenticated the user
router.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash: true
}));
// =====================================
// API EVENTS ROUTES ===================
// =====================================
router.get('/api/events', function (req, res) {
Events.find(function (err, events) {
if (err)
res.send(err);
res.json(events);
});
});
// route middleware to ensure user is logged in
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
module.exports = router;
<div class="container-fluid">
<div class="row-fluid">
<div class="form-body">
<div class="col-md-4 col-md-offset-4">
<h2>Sign in with </h2>
<div class="row">
<div class="col-sm-4"><a href="/auth/facebook" class="button btn-social facebook span-left btn-block"><span><i class="fa fa-facebook"></i></span>Facebook</a></div>
<div class="col-sm-4"><a href="/auth/twitter" class="button btn-social twitter span-left btn-block"><span><i class="fa fa-twitter"></i></span>Twitter</a></div>
<div class="col-sm-4"><a href="/auth/google" class="button btn-social googleplus span-left btn-block"><span><i class="fa fa-google-plus"></i></span>Google+</a></div>
</div>
<div class="section-divider"><span>OR</span></div>
<form class="loginForm" action="login.html" method="POST">
<div class="form-group">
<label>Email address</label>
<input type="email" class="form-control input-lg" placeholder=" Email Address " required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control input-lg" placeholder=" Password" required>
</div>
<div class="checkbox"><label><input type="checkbox"> Remember Me</label></div>
<div class="login-buttons"><button type="submit" class="btn btn-success btn-block btn-lg">Sign me in</button></div>
<div class="m-t-20">
<a class="add-info" href="forgotpw.html">Forgot your Password ?</a> | <a class="add-info" href="register.html"> Sign Up</a> | <a class="add-info" href="landing.html">Home</a>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row-fluid">
<div class="form-body">
<div class="col-md-4 col-md-offset-4" ng-controller="valController">
<h2>Sign Up with</h2>
<div class="row">
<div class="col-sm-4"><a href="#" class="button btn-social facebook span-left btn-block"><span><i class="fa fa-facebook"></i></span>Facebook</a></div>
<div class="col-sm-4"><a href="#" class="button btn-social twitter span-left btn-block"><span><i class="fa fa-twitter"></i></span>Twitter</a></div>
<div class="col-sm-4"><a href="#" class="button btn-social googleplus span-left btn-block"><span><i class="fa fa-google-plus"></i></span>Google+</a></div>
</div>
<div class="section-divider"><span>OR</span></div>
<form name="registerForm" novalidate class="ng-pristine ng-valid-email ng-invalid ng-invalid-required ng-valid-pattern ng-valid-validator">
<div class="form-group">
<label class="control-label">Name</label>
<div class="row">
<div class="col-md-6"><input type="text" name="firstName" class="form-control input-lg" placeholder=" First name"></div>
<div class="col-md-6"><input type="text" name="lastName" class="form-control input-lg" placeholder=" Last name"></div>
</div>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" placeholder="mail@example.com" required class="form-control input-lg">
</div>
<div class="form-group">
<label class="control-label"> Password</label>
<input type="password" name="password" class="form-control input-lg" placeholder=" Password">
</div>
<div class="form-group">
<label class="control-label">Re-enter Password</label>
<input type="password" name="password" class="form-control input-lg" placeholder=" Re-enter password">
</div>
<button type="submit" class="btn btn-block btn-lg">Sign me Up</button>
<div class="m-t-20"><a class="add-info" href="landing.html">Home</a> | <a class="add-info" href="login.html">Back to Sign In</a></div>
</form>
<p>By clicking Sign Up, you agree to our Terms and that you have read our Cookie Use.</p>
</div>
</div>
</div>
</div>