我正在使用以下技术堆栈,nodejs,mongodb,mongoose和express with typescript来构建API。
在我的身份验证控制器中,我有一个store方法,当用户尝试登录时会触发该方法。他们传递了一封电子邮件和密码。
我正在尝试将电子邮件密码与存储在mongo文档中的哈希电子邮件进行比较。但是,函数comparePassword
不存在。如何在我的user.model.ts
user.interface.ts
import { Document } from 'mongoose';
export interface UserInterface extends Document{
_id: string;
email: string;
password: string;
}
user.model.ts
import { Schema, Model, Document, model } from 'mongoose';
import bcrypt from 'bcryptjs';
import { UserInterface } from './user.interface';
const UserSchema = new Schema({
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
}, {
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
});
UserSchema.pre('save', function (next) {
let user = <UserInterface>this;
let SALT_WORK_FACTOR = 10;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function (candidatePassword: any, cb: any) {
bcrypt.compare(candidatePassword, this.password, function (err:any, isMatch: any) {
if (err) return cb(err);
cb(null, isMatch);
});
};
const User = model<UserInterface>('Users', UserSchema);
export default User;
auth.controller.ts
import { Request, Response, NextFunction } from 'express';
import User from './..//users/user.model';
class AuthController {
constructor() {
}
public async store(req: Request, res: Response, next: NextFunction): Promise<any> {
const input = req.body;
try {
let user = await User.findOne({'email': input.email});
if(!user) {
throw {};
}
user.comparePassword // comparePassword does not exist
} catch (err) {
return res.status(404).json({
success: false,
status:404,
dats: err,
message: "Failed to autenticate user"
});
}
}
}
export default AuthController;