2017-08-11 89 views
0

我正在學習Node.js及其所有功能,我正在使用蘇格蘭的教程(https://scotch.io/tutorials/easy-node-authentication-setup-and-local),我建立了他提出​​的建議,它非常好,但後來我想獲得更多信息用戶,像名和一個叫SIAPE因爲我的用戶模型代碼的特殊數字顯示:user.js的NODE.JS Passport不能與貓鼬

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更新這些事我與貓鼬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) 
[email protected]ab2208-pc32:~/28882/naest/AdmnistrationModule$ clear 

回答