Я занимаюсь разработкой приложения для машинописного текста с помощью API, работающего с нодами, экспрессами и мангустами.
У меня есть контроллер авторизации с функцией хранения, прикрепленной к POST: /api/auth
.Пользователь передает свой адрес электронной почты и пароль, чтобы сравнить его с хешированной версией.
Однако функция ComparePassword в use.model.ts
работает, потому что this.password
не определено.
auth.controller.ts
import { Request, Response, NextFunction } from 'express';
import User from './../users/user.model';
import jwt from 'jsonwebtoken';
import Config from './../../config/config';
class AuthController {
private config: any;
constructor() {
this.config = new Config();
}
public async store(req: Request, res: Response): Promise<any> {
const input = req.body;
console.log(input);
try {
let user = await User.findOne({ 'email': input.email });
if (!user) {
throw {};
}
console.log(user);
user.schema.methods.comparePassword(input.password, (err: any, isMatch: any) => {
if (err || !isMatch) {
return res.status(401).json({
success: false,
status: 401,
data: { err, isMatch },
message: 'Authentication Failed, wrong password',
});
}
if (!err && isMatch) {
const token = jwt.sign({ sub: user._id }, this.config.jwt.secretOrKey);
return res.status(200).json({
success: true,
status: 200,
data: { user, token },
message: 'Authentication Successful',
})
}
})
} catch (err) {
return res.status(404).json({
success: false,
status: 404,
data: err,
message: 'Failed to Authenticate'
})
}
}
}
export default AuthController;
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) {
//let user = <UserInterface>this;
console.log(candidatePassword);
console.log(this.password);
bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
const User = model<UserInterface>('Users', UserSchema);
export default User;
У меня есть похожий пароль сравненияфункция работает в другом проекте, который не использует машинопись.Поэтому я не уверен, почему «this» не определено и не установлено для пользовательского объекта mongoose.