创建文件authoriry.js
module.exports = {/*** 登陆权限验证*/isAuthenticated: function (req, res, next) {if(req.isAuthenticated()) {console.log('权限验证通过')return next();//继续访问}else{console.log('请先登陆')res.redirect('/bookshelf/login')//页面跳转}}
};
创建文件pasport.js
// 数据库连接配置
let config = {client: 'pg', // 其他可以是pg、sqlite3connection: {host: 'localhost',user: 'postgres',password: 'root',database: 'tutorial', // 数据库名称charset: 'utf8'}
}let knex = require('knex'), db; // 数据库连接// 保证数据库连接只初始化一次。if (!db) {console.log('建立连接')db = knex(config);
}let bodyParser = require('body-parser')
let jsonParser = bodyParser.json();
let express = require('express')
let router = express.Router();var app = express();
app.use('/pass', router);
app.listen(4000, function(){console.log('express 正在运行 http://localhost:4000');
});/*** ********************passport中间件*********************/
var session = require('express-session');
var passport = require('passport');
var authority = require('E:/untitled/bin/bookshelf/连接数据库/authority.js')
var cookieParser = require('cookie-parser');
var LocalStrategy = require('passport-local').Strategy;
router.use(cookieParser()); //增加cookie功能
router.use(session({ //增加session功能,配置sessionsecret: 'keyboard cat',proxy: true,resave: true,saveUninitialized: true
}));
router.use(passport.initialize()); //实例化passport
router.use(passport.session()); //增加session功能router.use(jsonParser) //给所有路由添加json解析功能
router.use('/xxx',authority.isAuthenticated) //给url'/pass'下所有增加登陆验证/*** 登陆验证*/
router.route('/login').post(function (req,res,next) {console.log('进入/login方法')passport.authenticate('local', function (err,user,info) {if(err!=null){console.log('报错信息:'+err)}if (user){console.log(user)// res.redirect('/bookshelf') //执行页面跳转}else{res.send('登陆失败')}req.logIn(user, function(err) {// console.log('错误信息:'+err)if (err) { return next(err); }return res.redirect('/users'+user[0].id);//跳转页面});})(req, res, next);
});router.route('/xxx/test').post(function (req,res) {console.log("测试失败")
})/*** 使用passport本地策略* 此处定义POST请求体中需要用于登陆的字段,username和password*/
passport.use('local',new LocalStrategy({usernameField: 'name',passwordField: 'pass'},function (username,password,done) {console.log('登陆账号:'+username+'密码:'+password)db('users').select().where({name:username}).then(function (user) {console.log('开始验证')if(user.length===0){console.log('未找到登陆账号');return done(null,false)}
console.log(password)
console.log(user[0].password)if (user[0].password!=password) {console.log('密码错误'); return done(null, false); }return done(null, user);})}
))/**序列化后可保存user对象**/
passport.serializeUser(function (user, done) {console.log('执行序列化')if (user !== false){console.log(user[0].id)done(null, user[0].id);}});
/**反序列化用于会话之外的使用**/
passport.deserializeUser(function (id, done) {console.log('执行反序列化')console.log(id)done(null, id);
});