passport.js身份验证和错误处理

时间:2017-07-10 15:52:11

标签: node.js express passport.js

我有一个API,可以通过移动应用对用户进行身份验证。我遇到了一个问题,如果用户使用错误的密码或无效的用户名登录到应用程序,那么节点应用程序会因为抛出身份验证错误而崩溃,是否有办法在不使用护照时处理身份验证错误崩溃的api?

var mysql = require('mysql');
var bcrypt = require('bcrypt-nodejs');
var dbconfig = require('./database');
var connection = mysql.createConnection(dbconfig.connection);

connection.query('USE ' + dbconfig.database);
module.exports = function(passport) {


    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        connection.query("SELECT * FROM saf_users WHERE id = ? ",[id], function(err, rows){
            done(err, rows[0]);
        });
    });

    passport.use(
        'local-login',
        new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField : 'username',
            passwordField : 'password',
            passReqToCallback : true // allows us to pass back the entire request to the callback
        },
        function(req, username, password, done) { // callback with email and password from our form
            connection.query("SELECT * FROM saf_users WHERE username = ?",[username], function(err, rows){
let bcryptedPwd = rows[0].password;
  let newPwd = bcryptedPwd.replace(bcryptedPwd.charAt(2), "a");
                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
                return res.status(401).json({ message: 'Unauthorized user!' });

        }       


                if (!bcrypt.compareSync(password, newPwd))
                    //return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
                return res.status(401).json({ message: 'Unauthorized user!' });

                // all is well, return successful user
                return done(null, rows[0]);
            });
        })
    );
};

1 个答案:

答案 0 :(得分:0)

done()

你应该做以下的

using(var ctx = new MyDbContext())
{
    return ctx.TableA
         .Join(ctx.TableB, a=>a.B_Id, b=>b.Id, (a,b)=>
              new QueryResult{TableA=a, TableB=b});
}

基本上CSS回调中的第一个参数会出错。因此,您可以向用户返回消息,而不是破坏您的应用。正如@robertklep所说,res没有定义。但这是处理错误的最佳方法。您可以查看this Example Here