【发布时间】:2016-10-16 09:36:06
【问题描述】:
我正在使用 Nodejs 和 MySQL 开发应用程序..
对于登录身份验证,我使用的是 passportJS。 此应用程序中有两个登录名,一个用于管理员,另一个用于客户。所以单独的表是有用户和注册。
passport.serializeUser(function(user, done) {
done(null, {
id : user.id,
isAdmin : user.isAdmin // or some other property/check
});
});
// used to deserialize the user
passport.deserializeUser(function(user, done) {
var table = user.isAdmin ? 'register' : 'users';
connection.query('select * from ?? where id = ?', [ table, user.id ], function(err, rows) {
if (err) {
return done(err);
} else if (! Array.isArray(rows) || ! rows.length) {
return done();
} else {
return done(null, rows[0]);
}
});
});
在反序列化用户中,如果我使用客户 ID 登录...它检查用户表是否有相同的 ID...所以我得到错误的数据
问题更新: 管理员本地登录
passport.use('local-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
connection.query("select * from users WHERE email = '" + email + "'",function(err,rows){
if (err)
return done(err);
if (!rows.length) {
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 (!( rows[0].password == 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, rows[0]);
});
}));
客户登录
passport.use('customer-login', new LocalStrategy({
usernameField : 'mobile',
passwordField : 'otp',
passReqToCallback : true
},
function(req, mobile, otp, done) {
connection.query("select * from register WHERE mobile = '" + mobile + "'",function(err,rows){
if (err)
return done(err);
if (!rows.length) {
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 (!( rows[0].otp == otp))
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
console.log(rows);
return done(null, rows[0]);
});
}));
对于管理员,我使用电子邮件作为登录用户名
客户使用手机号登录
【问题讨论】:
标签: mysql node.js passport.js