如何使用 express/node 确认电子邮件地址?
问题描述:
我正在尝试为用户建立电子邮件地址验证,以验证他们的电子邮件是真实的.我应该使用什么包来确认用户的电子邮件地址?到目前为止我使用猫鼬和快递
I'm trying to build verification of email address for users, to verify their email is real. What package should I use to confirm the email address of the user? So far Im using mongoose and express
代码示例
var UserSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true }
password: String
});
var User = mongoose.model('User', UserSchema);
app.post('/signup', function(req, res, next) {
// Create a new User
var user = new User();
user.email = req.body.email;
user.password = req.body.password;
user.save();
});
在 app.post 代码中,我如何确认用户的电子邮件地址?
In the app.post codes, how do i confirm the email address of the user?
答
您要查找的内容称为帐户验证"或电子邮件验证".有很多 Node 模块可以执行此操作,但原理是这样的:
What you're looking for is called "account verification" or "email verification". There are plenty of Node modules that can perform this, but the principle goes like this:
- 您的用户模型应该有一个
active
属性,默认情况下为false
- 当用户提交有效的注册表单时,创建一个新用户(
active
最初为false
) - 使用加密库创建一个长随机字符串(通常为 128 个字符),并将其存储在您的数据库中,并引用用户 ID
- 向提供的电子邮件地址发送一封电子邮件,并将哈希作为指向您服务器上的路由的链接的一部分
- 当用户点击链接并点击您的路线时,检查 URL 中传递的哈希值
- 如果hash存在于数据库中,获取相关用户并将他们的
active
属性设置为true
- 从数据库中删除哈希,不再需要它
- Your User model should have an
active
attribute that isfalse
by default - When the user submits a valid signup form, create a new User (who's
active
will befalse
initially) - Create a long random string (128 characters is usually good) with a crypto library and store it in your database with a reference to the User ID
- Send an email to the supplied email address with the hash as part of a link pointing back to a route on your server
- When a user clicks the link and hits your route, check for the hash passed in the URL
- If the hash exists in the database, get the related user and set their
active
property totrue
- Delete the hash from the database, it is no longer needed
您的用户现已通过验证.
Your user is now verified.