【问题标题】:NODE.JS Passport not working with mongooseNODE.JS Passport 不适用于猫鼬
【发布时间】:2017-08-11 18:07:27
【问题描述】:

我正在学习 Node.js 及其所有功能,我正在使用 scotch 的教程 (https://scotch.io/tutorials/easy-node-authentication-setup-and-local),我构建了他提出的内容,它非常好,但后来我想为用户获取更多信息,比如名称和一个名为 SIAPE 的特殊编号,如我的用户模型代码所示:user.js

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');

var userSchema = mongoose.Schema({

    local           : {
        name        : String,
        email       : String,
        password    : String,
        siape       : String
    }
});

userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8),null);
};

userSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.local.password);
};

module.exports = mongoose.model('User', userSchema);

然后设置我的 passport.js 以使用 mongoose 将这些内容更新到我的 mangodb 数据库,但它不起作用,我不知道为什么。

// config/passport.js

// load all the things we need
var LocalStrategy   = require('passport-local').Strategy;

// load up the user model
var User            = require('../app/models/users');

// expose this function to our app using module.exports
module.exports = function(passport) {

    // =========================================================================
    // passport session setup ==================================================
    // =========================================================================
    // required for persistent login sessions
    // passport needs ability to serialize and unserialize users out of session

    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    // =========================================================================
    // LOCAL SIGNUP ============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'

    passport.use('local-signup', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : 'siape',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, siape,password, email,name, done) {



        // asynchronous
        // User.findOne wont fire unless data is sent back
        process.nextTick(function() {
            console.log('USERNAME:' + name );
            console.log('EMAIL:' + email );
            console.log('PASSWORD:' + password );
            console.log('SIAPE:' + siape );
            console.log('DONE:' + done);
            console.log('REQ:' + req);

        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({ 'local.siape' :  siape }, function(err, user) {
            // if there are any errors, return the error
            if (err)
                return done(err);

            // check to see if theres already a user with that email
            if (user) {
                return done(null, false, req.flash('signupMessage', 'Email já existe'));
            } else {

                // if there is no user with that Email
                // create the user
                var newUser            = new User();

                // set the user's local credentials
                newUser.local.name     = name;
                newUser.local.email    = email;
                //newUser.local.password = newUser.generateHash(password);  
                newUser.local.password = password;
                newUser.local.siape    = siape;

                // save the user
                newUser.save(function(err) {
                    if (err)
                        throw err;
                       return done(null, newUser);
                });
            }

        });    

        });

    }));

    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

        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({ 'local.email' :  email }, function(err, user) {
            // if there are any errors, return the error before anything else
            if (err)
                return done(err);

            // if no user is found, return the message
            if (!user)
                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 (!user.validPassword(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, user);
        });

    }));
};

不知道是否有帮助,但我也会更新 html 表单:

<!-- views/signup.ejs -->
<!doctype html>
<html>
<head>
    <title>Cadastro de professor</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>
</head>
<body>
<div class="container">

<div class="col-sm-6 col-sm-offset-3">

    <h1><span class="fa fa-sign-in"></span> Cadastro De Professor</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>Nome</label>
            <input type="text" class="form-control" name="username">
        </div>
        <div class="form-group">
            <label>Email</label>
            <input type="text" class="form-control" name="email">
        </div>
        <div class="form-group">
            <label>Senha</label>
            <input type="password" class="form-control" name="password">
        </div>
        <div class="form-group">
            <label>SIAPE</label>
            <input type="text" class="form-control" name="siape">
        </div>
        <button type="submit" class="btn btn-warning btn-lg">Cadastrar Professor</button>
    </form>

    <hr>

    <p>Professor ja cadastrado?? <a href="/login">Entre</a></p>
    <p>Ou <a href="/">volte</a>.</p>

</div>

</div>
</body>
</html>

发生了很多我不太明白的事情,例如,我放了一个console.log来打印所有以html形式发送的信息,这就是打印的内容:

USERNAME:undefined
EMAIL:function verified(err, user, info) {
    if (err) { return self.error(err); }
    if (!user) { return self.fail(info); }
    self.success(user, info);
  }
PASSWORD:senha
SIAPE:SIAPE
DONE:undefined
REQ:[object Object]

对于最后一部分,我的终端服务器中打印的错误:

/home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/lib/utils.js:413
        throw err;
              ^
TypeError: undefined is not a function
    at Promise.<anonymous> (/home/aluno/28882/naest/AdmnistrationModule/config/passport.js:83:31)
    at Promise.<anonymous> (/home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/node_modules/mpromise/lib/promise.js:177:8)
    at Promise.emit (events.js:98:17)
    at Promise.emit (/home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/node_modules/mpromise/lib/promise.js:84:38)
    at Promise.fulfill (/home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/node_modules/mpromise/lib/promise.js:97:20)
    at handleSave (/home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/lib/model.js:133:13)
    at /home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/lib/utils.js:408:16
    at /home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/core.js:128:9
    at /home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1197:7
    at /home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1905:9
    at Server.Base._callHandler (/home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:453:41)
    at /home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:488:18
    at MongoReply.parseBody (/home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
    at null.<anonymous> (/home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:446:20)
    at emit (events.js:95:17)
    at null.<anonymous> (/home/aluno/28882/naest/AdmnistrationModule/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:207:13)
aluno@lab2208-pc32:~/28882/naest/AdmnistrationModule$ clear

【问题讨论】:

    标签: javascript node.js mongodb passport.js mongoose-schema


    【解决方案1】:

    刚刚解决了我的问题,问题是本地注册只接受2个参数作为默认值,用户名和密码用于身份验证,其他变量将使用“req.body”前缀捕获。这个链接对我帮助很大

    Does passportjs LocalStrategy allow more parameters than the default username and password?

    【讨论】:

      猜你喜欢
      • 2021-06-18
      • 2013-06-24
      • 2021-12-18
      • 2017-11-07
      • 1970-01-01
      • 2017-12-19
      • 2021-11-08
      • 2019-09-16
      • 2021-01-22
      相关资源
      最近更新 更多