【发布时间】:2018-08-27 05:08:46
【问题描述】:
我在我的应用程序中使用带有 Passport 的 JWT 进行身份验证,但我不知道如何更改密码。
这是我的登录功能:
function login(req, res, next) {
const userObj = {
email: req.body.email,
userType: req.body.userType
};
UserSchema.findOneAsync(userObj, '+password')
.then((user) => {
if (!user) {
const err = new APIError('User not found with the given email id', httpStatus.NOT_FOUND);
return next(err);
} else {
user.comparePassword(req.body.password, (passwordError, isMatch) => {
if (passwordError || !isMatch) {
const err = new APIError('Incorrect password', httpStatus.UNAUTHORIZED);
return next(err);
}
user.loginStatus = true;
user.gpsLoc = [19.02172902354515, 72.85368273308545];
const token = jwt.sign(user, config.jwtSecret);
UserSchema.findOneAndUpdateAsync({ _id: user._id }, { $set: user }, { new: true })
.then((updatedUser) => {
const returnObj = {
success: true,
message: 'user successfully logged in',
data: {
jwtAccessToken: `JWT ${token}`,
user: updatedUser
}
};
res.json(returnObj);
})
.error((err123) => {
const err = new APIError(`error in updating user details while login ${err123}`, httpStatus.INTERNAL_SERVER_ERROR);
next(err);
});
});
}
})
.error((e) => {
const err = new APIError(`erro while finding user ${e}`, httpStatus.INTERNAL_SERVER_ERROR);
next(err);
});
}
我的用户数据库是这样的。
import Promise from 'bluebird';
import mongoose from 'mongoose';
import httpStatus from 'http-status';
import APIError from '../helpers/APIError';
import bcrypt from 'bcrypt';
const UserSchema = new mongoose.Schema({
fname: { type: String, default: null },
lname: { type: String, default: null },
email: { type: String, required: true, unique: true },
password: { type: String, required: true, select: false },
});
UserSchema.pre('save', function userSchemaPre(next) {
const user = this;
if (this.isModified('password') || this.isNew) {
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, (hashErr, hash) => {
if (hashErr) {
return next(hashErr);
}
user.password = hash;
next();
});
});
} else {
return next();
}
});
UserSchema.methods.comparePassword = function comparePassword(pw, cb) {
const that = this;
bcrypt.compare(pw, that.password, (err, isMatch) => {
if (err) {
return cb(err);
}
cb(null, isMatch);
});
};
我已经做了另一个重置密码的功能,并且匹配检查的旧密码像登录功能一样有效,现在我想在数据库中更新新护照。我该怎么做?
非常感谢
【问题讨论】:
标签: node.js mongodb passwords passport.js passport-local