我写userSchema.methods.generateAuthToken()
的功能如下
UserSchema.methods.generateAuthToken = async function()
{
const token = jwt.sign({_id: this._id.toString()}, "ThisIsSecret");
this.tokens = this.tokens.concat({token});
await this.save();
return token;
}
我在我的代码中调用这个函数 while authenticating with google
。以下是谷歌验证码
passport.use(new GoogleStrategy({
clientID: CLIENT_ID,
clientSecret: CLIENT_SECRET,
callbackURL: "http://localhost:8000/auth/google/notepad"
},
async function(accessToken, refreshToken, profile, email, cb) {
try
{
var user = await User.find({googleId: email.id});
if(user.length === 0)
{
const user = new User({googleId: email.id, fullName: email.displayName, email: email.emails[0].value});
await user.save();
}
return cb(undefined, user);
}
catch(err)
{
return cb(err, undefined);
}
}
));
router.get('/auth/google', passport.authenticate('google',{scope: ['profile','email']}));
router.get('/auth/google/notepad',
passport.authenticate('google', { failureRedirect: '/' }),
async function(req, res) {
try
{
const token = await req.user.generateAuthToken();
res.cookie('authToken', token);
}
catch(err)
{
console.log(err);
}
res.redirect('/')
});
router.get('/',(req,res)=>
{
res.send();
})
findOrCreate()
出于某种原因,我不会使用方法。相反,我正在使用find()
猫鼬的方法检查用户是否已经存在。问题是,当用户不存在时,req.user.generateAuthToken
方法会被调用,但是当用户已经存在时,它会说generateAuthToken
方法不存在。它应该每次都运行。