我正在使用scotch.io教程为我正在处理的应用程序设置PassportJS本地登录。在设置我的注册/登录页面,MongoDB,PassportJS之后,我尝试进行测试“帐户”,并且......没有任何反应。没有重定向,没有flash消息,没有。似乎没有任何东西被拿起来发布到数据库。我在下面列出了相关的脚本。我试图尽可能忠实于教程布局(来源:https://scotch.io/tutorials/easy-node-authentication-setup-and-local)。
index.js(服务器的入口点)
// load dependencies
var express = require('express');
var app = express();
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var LocalStrategy = require('passport-local').Strategy;
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
// setup views
var ejs = require('ejs');
var engine = require('ejs-locals');
//database configuration
mongoose.connect(configDB.url);
require('./config/passport')(passport);
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
//view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/public', express.static(path.join(__dirname, 'public')));
// required for passport
app.use(session({
secret: 'ilovescotchscotchyscotchscotch',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // for flash messages stored in-session
// routes
require('./routes')(app, passport);
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
passport.js(护照设置)
var LocalStrategy = require('passport-local').Strategy;
var User = require('../user');
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done) {
process.nextTick(function() {
User.findOne({ 'local.email': email }, function(err, user) {
if (err)
return done(err);
if (user) {
return done(null, false, req.flash('signupMessage', 'That e-mail address is already taken.'));
} else {
var newUser = new User;
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done) {
User.findOne({ 'local.email': email }, function(err, user) {
if (err)
return done(err);
if (!user)
return done(null, false, req.flash('loginMessage', 'User not found.'));
if(!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Invalid password, please try again.'));
return done(null, user);
});
}));
};
/config/database.js
module.exports = {
'url': 'mongodb://localhost:27017/users/'
}
routes.js
module.exports = function(app, passport) {
app.get('/', function (req, res) {
res.render('pages/index');
});
app.get('/login', function (req, res) {
res.render('pages/login', { message: req.flash('loginMessage') });
});
app.get('/signup', function (req, res) {
res.render('pages/signup', { message: req.flash('signupMessage') });
});
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true
}));
app.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile',
failureRedirect: '/login',
failureFlash: true
}));
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profile.ejs', {
user: req.user
});
});
app.get('/addroom', function (req, res) {
res.render('pages/addroom.ejs', {
message: req.flash('addroomMessage')
});
});
app.get('/propconfig', function (req, res) {
res.render('pages/propconfig.ejs', {
message: req.flash('propconfigMessage')
});
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
};
// route middleware to ensure a user is logged in
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
user.js(用户架构)
// load dependencies
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
// define user schema
var userSchema = mongoose.Schema({
local: {
email: String,
password: String
}
});
// METHODS
// generating a hash
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// creating model for user to expose to app
module.exports = mongoose.model('User', userSchema);
最后是signup.ejs(注册用户界面的模板)
<!doctype html>
<html>
<head>
<title>Node Authentication</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
<style>
body { padding-top:80px; }
</style>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="col-sm-6 col-sm-offset-3">
<h1><span class="fa fa-sign-in"></span> Signup</h1>
<!-- show any messages that come back with authentication -->
<% if (message.length > 0) { %>
<div class="alert alert-danger"><%= message %></div>
<% } %>
<!-- LOGIN FORM -->
<form action="/signup" method="post">
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" id="email">
<div id="emailError"></div>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" id="password">
<div id="passwordError"></div>
</div>
<button type="submit" class="btn btn-warning btn-lg">Signup</button>
</form>
<hr>
<p>Already have an account? <a href="/login">Login</a></p>
<p>Or go <a href="/">home</a>.</p>
</div>
</div>
<script type="text/javascript" src="../public/javascripts/validate.js"></script>
</body>
</html>
更新:我注释掉了我正在使用的电子邮件验证脚本,现在发生了POST操作(之前为什么不是,我不知道),但它仍然没有达到数据库。
更新#2:我尝试在调试模式下运行服务器。控制台返回了这些信息:
GET /signup 304 34.791 ms - -
express:router dispatching POST /signup +28s
express:router query : /signup +0ms
express:router expressInit : /signup +0ms
express:router logger : /signup +0ms
express:router cookieParser : /signup +1ms
express:router jsonParser : /signup +0ms
express:router urlencodedParser : /signup +3ms
express:router session : /signup +157ms
express:router initialize : /signup +2ms
express:router authenticate : /signup +0ms
express:router <anonymous> : /signup +1ms
POST /signup - - ms - -
express:router dispatching POST /signup +2m
express:router query : /signup +0ms
express:router expressInit : /signup +0ms
express:router logger : /signup +1ms
express:router cookieParser : /signup +1ms
express:router jsonParser : /signup +2ms
express:router urlencodedParser : /signup +0ms
express:router session : /signup +4ms
express:router initialize : /signup +1ms
express:router authenticate : /signup +2ms
express:router <anonymous> : /signup +1ms
POST /signup - - ms - -
同时,浏览器在"Waiting for localhost..."
停留约2或3分钟(没有崩溃或超时),最后返回“本地主页不工作
localhost没有发送任何数据。 ERR_EMPTY_RESPONSE“
更新#3:这是另一个调试日志,检查所有模块(不仅仅是Express):
express:router dispatching POST /signup +39s
express:router query : /signup +4ms
express:router expressInit : /signup +1ms
express:router logger : /signup +2ms
express:router cookieParser : /signup +5ms
express:router jsonParser : /signup +3ms
body-parser:json content-type "application/x-www-form-urlencoded" +0ms
body-parser:json skip parsing +4ms
express:router urlencodedParser : /signup +1ms
body-parser:urlencoded content-type "application/x-www-form-urlencoded" +0ms
body-parser:urlencoded content-encoding "identity" +3ms
body-parser:urlencoded read body +0ms
body-parser:urlencoded parse body +60ms
body-parser:urlencoded parse extended urlencoding +5ms
express:router session : /signup +8ms
express-session fetching 6M-W_9dEFDmsPBvNp2d0UmeBE9gDuXMn +14ms
express-session no session found +3ms
express:router initialize : /signup +9ms
express:router authenticate : /signup +0ms
express:router <anonymous> : /signup +2ms
req.body: {"email":"matt@matt.matt","password":"pass1234"}
mquery findOne +20ms users { 'local.email': 'matt@matt.matt' } { fields: {} }
express-session saving EkaL4tXbUCZ9QXHDGt2XWxlgMjVGejAC +95ms
express-session split response +1ms
express-session set-cookie connect.sid=s%3AEkaL4tXbUCZ9QXHDGt2XWxlgMjVGejAC.cvTE1KsUvIzbnNqHP0ns9td75MUkR4mKRDvwuHk%2B4jE; Path=/; HttpOnly +4ms
morgan log request +17ms
POST /signup 302 237.147 ms - 58
express:router dispatching GET /signup +9ms
express:router query : /signup +2ms
express:router expressInit : /signup +0ms
express:router logger : /signup +1ms
express:router cookieParser : /signup +2ms
express:router jsonParser : /signup +0ms
body-parser:json skip empty body +0ms
express:router urlencodedParser : /signup +13ms
body-parser:urlencoded skip empty body +0ms
express:router session : /signup +1ms
express-session fetching EkaL4tXbUCZ9QXHDGt2XWxlgMjVGejAC +1ms
express-session session found +3ms
express:router initialize : /signup +1ms
express:router authenticate : /signup +1ms
express:router <anonymous> : /signup +1ms
express:view lookup "pages/signup.ejs" +6ms
express:view stat "/media/matt/PORTABLE/myapp/views/pages/signup.ejs" +1ms
express:view render "/media/matt/PORTABLE/myapp/views/pages/signup.ejs" +1ms
express-session saving EkaL4tXbUCZ9QXHDGt2XWxlgMjVGejAC +18ms
express-session split response +0ms
morgan log request +10ms
GET /signup 200 50.407 ms - 1736
答案 0 :(得分:2)
首先改变你这样的本地策略
passport.use(new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, function () {
//LocalStrategy verify callback
}
));
然后改变您的路线/注册
app.post('/signup', function (req, res, next) {
passport.authenticate('local', {failureRedirect: '/login'},
function (req, email, password, done) {
process.nextTick(function () {
User.findOne({'local.email': email}, function (err, user) {
if (err)
return done(err);
if (user) {
return done(null, false, req.flash('signupMessage', 'That e-mail address is already taken.'));
} else {
var newUser = new User;
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
newUser.save(function (err) {
if (err){
throw err;}
//res.redirect("/path")
return done(null, newUser);
});
}
});
});
})(req, res, next);
});
您可以像这样
重定向到res.redirect(“/ path”)中的其他页面您在路线中定义的那条路线,即
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true
}));
它无法正常工作,因为您无法直接在路由中定义passport.authenticate,并且您的数据库连接正常,它从数据库中获取结果没有数据库连接问题。
答案 1 :(得分:2)
感谢您的代码。我认为这有助于我更快地解决这个问题。我能够重现你的问题。以下是我为解决您的问题所采取的措施的差异
在routes.js中,我修改了护照以使用passport.js中定义的local-signup
而不是现有的函数:
diff --git a/routes.js b/routes.js
index a6166b7..e2a742f 100644
--- a/routes.js
+++ b/routes.js
@@ -13,30 +13,12 @@ module.exports = function(app, passport) {
res.render('pages/signup', { message: req.flash('signupMessage') });
});
- app.post('/signup', function (req, res, next) {
- passport.authenticate('local', {failureRedirect: '/login'},
- function (req, email, password, done) {
- process.nextTick(function () {
- User.findOne({'local.email': email}, function (err, user) {
- if (err)
- return done(err);
- if (user) {
- return done(null, false, req.flash('signupMessage', 'That e-mail address is already taken.'));
- } else {
- var newUser = new User;
- newUser.local.email = email;
- newUser.local.password = newUser.generateHash(password);
- newUser.save(function (err) {
- if (err){
- throw err;}
- //res.redirect("/path")
- return done(null, newUser);
- });
- }
- });
- });
- });
-});
+ // process the signup form
+ app.post('/signup', passport.authenticate('local-signup', {
+ successRedirect : '/profile', // redirect to the secure profile section
+ failureRedirect : '/signup', // redirect back to the signup page if there is an error
+ failureFlash : true // allow flash messages
+ }));
app.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile',
发表了一些评论,并确保if err
已关闭
diff --git a/config/passport.js b/config/passport.js
index dde7628..398796e 100644
--- a/config/passport.js
+++ b/config/passport.js
@@ -23,7 +23,6 @@ module.exports = function(passport) {
process.nextTick(function() {
User.findOne({ 'local.email': email }, function(err, user) {
if (err)
- console.log(err);
return done(err);
if (user) {
return done(null, false, req.flash('signupMessage', 'That e-mail address is already taken.'));
@@ -31,9 +30,9 @@ module.exports = function(passport) {
var newUser = new User;
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
- newUser.$__save(function(err) {
+
+ newUser.save(function(err) {
if (err)
- console.log(err);
throw err;
console.log(User);
console.log(newUser);
我已向您的分支机构提交了pull请求。