user.js的
const mongoose = require('mongoose');
const bcrypt = require('bcrypt-nodejs');
const Schema = mongoose.Schema;
//= ===============================
// User Schema
//= ===============================
const UserSchema = new Schema({
email: {
type: String,
lowercase: true,
unique: true,
required: true
},
password: {
type: String,
required: true
}
});
// Pre-save of user to database, hash password if password is modified or new
UserSchema.pre('save', function (next) {
const user = this,
SALT_FACTOR = 5;
if (!user.isModified('password')) return next();
bcrypt.genSalt(SALT_FACTOR, (err, salt) => {
if (err) return next(err);
bcrypt.hash(user.password, salt, null, (err, hash) => {
if (err) return next(err);
user.password = hash;
next();
});
});
});
// Method to compare password for login
UserSchema.methods.comparePassword = function (candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
if (err) { return cb(err); }
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', UserSchema);
passport.js
const passport = require('passport');
const User = require('../models/user');
const config = require('./main');
const LocalStrategy = require('passport-local');
// username field is now email
const localOptions = {
usernameField: 'email'
};
// set up the local login strategy
const localLogin = new LocalStrategy(localOptions, (email, password, done) => {
User.findOne({ email }, (err, user) => {
if (err) { return done(err); }
if (!user) { return done(null, false, { error: 'Your login details could not be verified. Please try again.' }); }
user.comparePassword(password, (err, isMatch) => {
if (err) { return done(err); }
if (!isMatch) { return done(null, false, { error: 'Your login details could not be verified. Please try again.' }); }
return done(null, user);
});
});
});
passport.use(localLogin);
漂亮的圖片,無用的,但漂亮 - 我認爲'models/user.js'是你寫的東西 - 你可能寫錯了 - 誰可以說,發佈代碼,如果它是你的(不是它的圖片) –
@JaromandaX這些圖片僅僅是爲了表明webstorm沒有認識到這些方法,我的歉意 – Markoe7
我明白,但是如果你想要代碼的幫助,請發佈**你的**代碼可能是錯誤的(再次假設模型/用戶。 js是你的代碼) –