如何解决类型错误:user.authenticate 不是函数
const mongoose = require("mongoose")
const uuidv1 = require("uuidv1")
const crypto = require('crypto');
const userSchema = new mongoose.Schema({
name: {
type: String,trim: true,},email: {
type: String,hashed_password: {
type: String,salt: String,created: {
type: Date,default: Date.Now
},updated: {
type: Date
}
})
userSchema.virtual('password')
.set(function(password) {
//create temporary variable called _password
this._password = password;
//generate a timestamp
this.salt =uuidv1();
// encrypt password()
this.hashed_password =this.encryptPassword(password);
})
.get(function() {
return this._password;
});
userSchema.methods = {
authenticate: function(plainText) {
return this.encryptPassword(plainText) === this.hashed_password
},encryptPassword: function(password){
if(!password) return "";
try{
return crypto.createHmac('sha1',this.salt)
.update(password)
.digest('hex');
}catch (err){
return "";
}
}
};
module.exports = mongoose.model("user",userSchema);
const jwt = require('jsonwebtoken');
const user = require('../models/user');
require('dotenv').config();
exports.signup = async(req,res ) => {
const userExists = await User.findOne({email: req.body.email})
if(userExists) return res.status(403).json({
error: "Email is already taken"
})
const user = await new User(req.body)
await user.save()
res.status(200).json({user});
};
exports.signin =(req,res) => {
//find the user based on email
const {email,password} = req.body
user.findOne({email},() => {
if(!user){
return res.status(401).json({
error: "User does not exist. Please signin."
})
}
//created the model for aunthentication and use here
if(!user.authenticate(password)){
return res.status(401).json({
error: "Email and password do not match"
})
}
//generate a token with user id and secret
const token = jwt.sign({_id: user._id},process.env.JWT_SECRET)
//persist the token as 't' in cookie to frontend client
res.cookie('t',token,{expire:new Date() + 9999})
//return response with user and token to frontend client
const{_id,name,email} = user
return res.json({token,user: {_id,email,name}})
})
}
TypeError: user.authenticate 不是函数
请帮忙
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。