我正在尝试使用带sqlite的passport.js,但问题是我无法序列化用户,因为id不存在
要保存用户,请执行以下操作:
export const saveUser = async (req: Request, res: Response, next: NextFunction) => {
const users = new UserRepository(db, 'users');
const hash = bcrypt.hash(req.body.password, 10);
const user = new User(
req.body.gender,
req.body.first_name,
req.body.last_name,
req.body.email.toLowerCase(),
await hash,
req.body.dob,
req.body.zip_code,
req.body.house_number,
req.body.addition || null,
);
const emailExists = users.findOne({ email: req.body.email.toLowerCase() });
if (emailExists) {
return res.redirect('/users/register');
} else {
users.create(user);
req.logIn(user, (err) => {
if (err) return next(err);
res.redirect('/');
});
}
};
查询如下:
public create(item: T): boolean {
const query = `
INSERT INTO ${this.table} (${Object.keys(item).join(',')})
VALUES (${Object.keys(item).map((_) => '?').join(',')})`;
const stmt = this.db.prepare(query);
const result = stmt.run(Object.values(item));
return !!result.changes;
}
这是我的护照配置:
passport.serializeUser((user: any, done) => {
console.log(user);
done(undefined, user.id);
});
passport.deserializeUser((id: number, done) => {
const user = users.findById(id);
if (!user) return done(undefined, false);
return done(undefined, user);
});
passport.use(new Strategy({ passReqToCallback: true }, (_, email, password, done) => {
const user = users.findOne({ email: email.toLowerCase() });
if (!user) return done(undefined, false);
bcrypt.compare(password, user.password, (err, isValid) => {
if (err) return done(err);
if (!isValid) return done(undefined, false);
return done(undefined, user);
});
}));
由于对象中没有返回ID,我无法序列化用户,有人可以帮助我使护照认证生效吗?