使用node.js失败Passport注册

时间:2017-11-30 12:19:03

标签: node.js passport.js express-session

Iam使用Passport版本0.4.0构建具有Node.js的应用程序以进行注册。但我的post方法无法正常工作,我的用户不会保存到数据库中。这是我的config / passport.js文件:

var passport = require('passport');
var User = require('../models/user');
var LocalStrategy = require('passport-local').Strategy;

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

passport.deserializeUser((id, done) => {
    User.findById(id, (err, user) =>{
        done(err, user);
    });
});

passport.use('local.signup', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
}, function(req, email, password, done) {
    User.findOne({'email': email}, function(err, user) {
        if(err) {
            return done(err);
        }
        if (user) {
            return done(null, false, {message: 'Email is already used.'});
        }
        var newUser = new User();
        newUser.email = email;
        newUser.password = newUser.encryptPassword(password);
        newUser.save(function(err, result) {
            if (err) {
                return done(err);
            }
            return done(null, newUser);
        }); 
    });
}));

在我的route / index.js文件中,我确定了我的帖子和获取方法:

    const express = require('express');
    const bodyParser = require('body-parser');
    const mongoose = require('mongoose');
    const csrf = require('csurf');
    var passport = require('passport'); 

const Products = require('../models/product');
const Users = require('../models/user');

const productRouter = express.Router();

const csrfProtection = csrf();
productRouter.use(csrfProtection);

productRouter.use(bodyParser.json());
//Here my methods for product model
.........
.........
productRouter.get('/user/signup', function(req, res, next) {
    res.render('user/signup', {csrfToken: req.csrfToken()});
});

productRouter.post('/user/signup', passport.authenticate('local.signup', {
    successRedirect: '/user/profile',
    failureRedirect: '/user/signup',
    failureFlash: true
}));

productRouter.get('/user/profile', function(req, res, next) {
    res.render('user/profile');
});


module.exports = productRouter;

我的app.js文件会话,护照和flash(app.js)中需要我:

........
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');

然后连接后,我需要我的配置/护照文件:

const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');

const Products = require('./models/product');
const User = require('./models/user');

const url = 'mongodb://localhost:27017/mystore';
const connect = mongoose.connect(url, {
  useMongoClient: true
});

connect.then((db) => {
  console.log('Connected correctly to server');
}, (err) => { console.log(err); });

require('./config/passport');

我创建了一个signup.hbs模板:

<form class="form" role="form" 
action="/user/signup" method="post">
          <div class="form-group">
            <label for="email">Email</label>
            <input type="email" class="form-control" id="email" placeholder="email@gmail.com" required="">
         </div>
           <div class="form-group">
             <label for="password">Password</label>
             <input type="password" class="form-control" id="password" placeholder="password" required="">
            </div>
              <input type="hidden" name="_csrf" value="{{ csrfToken }}">
            <div class="form-group">
              <button type="submit" class="btn btn-success btn-lg float-right">Register</button>
            </div>
     </form>

我正确连接到localhost:3000 / user / signup,但在提交表单后没有任何事情发生,我的用户集合是空的。

当然我的models / user.js模型:

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


var userSchema = new Schema({
    email: {
        type: String,
        required:true
    },
    password: {
        type: String,
        required: true
    }
});

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

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

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

任何想法,我错了? 非常感谢。

1 个答案:

答案 0 :(得分:0)

Noob在这里但是把手允许你在输入中没有名字属性的表格 - 你是否通过铬检查员验证了那些被发送?