app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose')
//models
require('./models/Article.model') //require model here
require('./models/About.model')
require('./models/Category.model')
require('./models/Tool.model')
var index = require('./routes/index');
var about = require('./routes/about');
var articles = require('./routes/articles');
var categories = require('./routes/categories');
var tools = require('./routes/tools');
//models
//passport-authentication
var session = require('express-session');
var flash = require('express-flash');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var authenticate=require('./routes/authenticate')(passport)
//end passport-authentication
var app = express()
var db='mongodb://localhost/myblog'
mongoose.connect(db)
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(session({secret:'http://localhost:3000/',cookie: { maxAge: 60000 }}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')));
//authenticate
app.use(passport.initialize());
app.use(passport.session());
app.use(flash())
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/', index);
app.use('/auth', authenticate);
app.use('/about', about);
app.use('/articles', articles);
app.use('/categories', categories);
app.use('/tools', tools);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
passport.use('local', new LocalStrategy(
function (email, password, done) {
debugger
var user = {
id: '1',
email: 'this@email.com',
password: '123456'
}; // 可以配置通过数据库方式读取登陆账号
console.log("authenticating.......")
console.log(email);
console.log(password)
if (email !== user.email) {
return done(null, false, { message: 'Incorrect email.' });
}
if (password !== user.password) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
}
));
passport.serializeUser(function (user, done) {//保存user对象
done(null, user);//可以通过数据库方式操作
});
passport.deserializeUser(function (user, done) {//删除user对象
done(null, user);//可以通过数据库方式操作
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
这是我的authenticate.js
var express = require('express');
var router = express.Router();
module.exports = function(passport){
//sends successful login state back to angular
router.get('/success', function(req, res){
res.send({state: 'success', user: req.user ? req.user : null});
});
//sends failure login state back to angular
router.get('/failure', function(req, res){
res.send({state: 'failure', user: null, message: "Invalid username or password"});
});
//log in
router.post('/login', passport.authenticate('local', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
//log out
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
}
即使我输入正确的电子邮件和密码登录,我总是在下面 Chrome控制台。您可以在下面看到我打印出正确的电子邮件和密码。
opening pop up
myBlogApp.js:63 {"email":"this@email.com","password":"123456"}
myBlogApp.js:69 Object {data: Object, status: 200, config: Object, statusText: "OK"}config: Objectdata: Objectmessage: "Invalid username or password"state: "failure"user: null__proto__: Objectheaders: (name)status: 200statusText: "OK"__proto__: Object
我不知道为什么它会跳过策略,因为我在策略中设置了一些console.log但它似乎根本没有运行。
答案 0 :(得分:1)
默认情况下,passport-local
会检查username
和password
字段的请求;如果其中一个不可用,则不会调用验证回调。
您正在使用email
和password
,因此您应该覆盖默认值(具体为usernameField
),如下所示:
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(username, password, done) {
// ...
}
));
记录here。