我已经在 expresJS 中设置了一个用户填写表单的设置,然后它会转到经过以下步骤的注册路径:
- 验证数据(清理电子邮件和用户名)
- 注册(如果数据有效,将用户保存到数据库中)
- 登录(使用 passportJS)
该路线的代码:
router.post('/register',
userController.validateRegister,
userController.register,
authController.login
);
问题是,我不想直接注册用户。 我想给他们发一封电子邮件,然后当他们点击链接时,它实际上注册了他们。
我猜这样做的方法是不在我的注册路径(注册)中使用第 2 步,而是向用户发送一封包含完成注册链接的电子邮件,然后当用户点击我注册的链接时让他们登录。
所以我想,如果我去掉register方法我可以跳到login方法,解决用户不注册登录的问题(没有 将其保存到数据库)
但是当我提交表单时,出现错误:
登录失败!
来自登录方法:
exports.login = passport.authenticate('local', {
failureRedirect: '/login',
failureFlash: 'Failed Login!',
successRedirect: '/',
successFlash: 'You are now logged in!'
});
所以,对于如何更改我当前的设置(我在现场注册它们)到他们必须单击我将发送给他们的电子邮件的设置,我有点迷茫。
这是我在注册路由中使用的方法:
exports.validateRegister = (req, res, next) => {
req.sanitizeBody('name');
req.checkBody('name', 'You must supply a name!').notEmpty();
req.checkBody('email', 'That Email is not valid!').isEmail();
req.sanitizeBody('email').normalizeEmail({
gmail_remove_dots: false,
remove_extension: false,
gmail_remove_subaddress: false
});
req.checkBody('password', 'Password Cannot be Blank!').notEmpty();
req.checkBody('password-confirm', 'Confirmed Password cannot be blank!').notEmpty();
req.checkBody('password-confirm', 'Oops! Your passwords do not match').equals(req.body.password);
const errors = req.validationErrors();
if (errors) {
req.flash('error', errors.map(err => err.msg));
res.render('register', { title: 'Register', body: req.body, flashes: req.flash() });
return; // stop the fn from running
}
next(); // there were no errors!
};
exports.register = async (req, res, next) => {
const user = new User({
email: req.body.email,
name: req.body.name,
location: {
address: req.body.location.address,
vicinity: req.body.location.vicinity,
coordinates: [
req.body.location.coordinates[0],
req.body.location.coordinates[1],
]
}
});
const register = promisify(User.register, User);
await register(user, req.body.password);
next(); // pass to authController.login
};
exports.login = passport.authenticate('local', {
failureRedirect: '/login',
failureFlash: 'Failed Login!',
successRedirect: '/',
successFlash: 'You are now logged in!'
});
Passport 是这样配置的:
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
最佳答案
为什么要登录一个没有注册的用户?
您可以在您的用户模型设置中添加一个 bool 属性,如 isVerified
默认为 false
。
仅允许将 isVerified
属性设置为 true
的用户进行登录。
当用户单击包含在注册电子邮件中的链接时,您将 isVerified
设置为 true
并且用户可以自由登录。
这样,您就可以在注册期间运行注册方法。
用户提交注册表后,没有理由立即登录。
您可以呈现一个信息页面,通知用户 帐户验证
电子邮件已发送到他的电子邮件帐户。
关于javascript - 使用 expressJS 通过电子邮件确认注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57101552/