node.js 如何使用快递/节点确认电子邮件地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39092822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:31:18  来源:igfitidea点击:

how to do confirm email address with express/node?

node.jsexpress

提问by sinusGob

Im trying to build confirm 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

我试图为用户建立确认电子邮件地址,以验证他们的电子邮件是真实的。我应该使用什么包来确认用户的电子邮件地址。到目前为止我使用猫鼬和快递

Code Example

代码示例

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();
});

In the app.post codes, how do i confirm the email address of the user?

在 app.post 代码中,我如何确认用户的电子邮件地址?

回答by Soviut

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:

您要查找的内容称为“帐户验证”或“电子邮件验证”。有很多 Node 模块可以执行此操作,但其原理如下:

  • Your User model should have an activeattribute that is falseby default
  • When the user submits a valid signup form, create a new User (who's activewill be falseinitially)
  • 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 activeproperty to true
  • Delete the hash from the database, it is no longer needed
  • 你的 User 模型应该有一个默认的active属性false
  • 当用户提交一个有效的注册表单,创建一个新用户(谁的active将是false最初)
  • 使用加密库创建一个长随机字符串(通常为 128 个字符),并将其存储在您的数据库中并引用用户 ID
  • 向提供的电子邮件地址发送电子邮件,并将哈希作为指向服务器上路由的链接的一部分
  • 当用户点击链接并点击您的路线时,检查 URL 中传递的哈希值
  • 如果数据库中存在哈希,则获取相关用户并将其active属性设置为true
  • 从数据库中删除哈希,不再需要它

Your user is now verified.

您的用户现已通过验证。

回答by BlackMamba

var express=require('express');
var nodemailer = require("nodemailer");
var app=express();
/*
    Here we are configuring our SMTP Server details.
    STMP is mail server which is responsible for sending and recieving email.
*/
var smtpTransport = nodemailer.createTransport("SMTP",{
    service: "Gmail",
    auth: {
        user: "Your Gmail ID",
        pass: "Gmail Password"
    }
});
var rand,mailOptions,host,link;
/*------------------SMTP Over-----------------------------*/

/*------------------Routing Started ------------------------*/

app.get('/',function(req,res){
    res.sendfile('index.html');
});
app.get('/send',function(req,res){
        rand=Math.floor((Math.random() * 100) + 54);
    host=req.get('host');
    link="http://"+req.get('host')+"/verify?id="+rand;
    mailOptions={
        to : req.query.to,
        subject : "Please confirm your Email account",
        html : "Hello,<br> Please Click on the link to verify your email.<br><a href="+link+">Click here to verify</a>" 
    }
    console.log(mailOptions);
    smtpTransport.sendMail(mailOptions, function(error, response){
     if(error){
            console.log(error);
        res.end("error");
     }else{
            console.log("Message sent: " + response.message);
        res.end("sent");
         }
});
});

app.get('/verify',function(req,res){
console.log(req.protocol+":/"+req.get('host'));
if((req.protocol+"://"+req.get('host'))==("http://"+host))
{
    console.log("Domain is matched. Information is from Authentic email");
    if(req.query.id==rand)
    {
        console.log("email is verified");
        res.end("<h1>Email "+mailOptions.to+" is been Successfully verified");
    }
    else
    {
        console.log("email is not verified");
        res.end("<h1>Bad Request</h1>");
    }
}
else
{
    res.end("<h1>Request is from unknown source");
}
});

/*--------------------Routing Over----------------------------*/

app.listen(3000,function(){
    console.log("Express Started on Port 3000");
});

Follow the code example, you can use nodemailerto send the link, and then verify it. Here is a link: https://codeforgeek.com/2014/07/node-email-verification-script/

按照代码示例,您可以使用nodemailer发送链接,然后验证它。这是一个链接:https: //codeforgeek.com/2014/07/node-email-verification-script/

回答by Piyush Upadhyay

if you are just testing on your local machine, one simple way of understanding how to do it can be :

如果您只是在本地机器上进行测试,了解如何进行测试的一种简单方法是:

Assuming you already know sending mails through nodemailer..

假设您已经知道通过 nodemailer 发送邮件..

Once user signs up, after storing sign-up data in your database, on your server side take user email from sign-up data received and a random generated number and build a custom url with the address of page where user will be directed after he/she clicks on the link given in mail.

一旦用户注册,在您的数据库中存储注册数据后,在您的服务器端从收到的注册数据和随机生成的数字中获取用户电子邮件,并使用用户将在他之后被定向的页面地址构建一个自定义 URL /she 单击邮件中提供的链接。

var customUrl = "http://"+ your host + "/" + your verification web-page + "?email=" + userEmail + "&id=" + randomNumber;

An example can be:

一个例子可以是:

var userEmail = [email protected]
var host = localhost:8080
var directWebPage = verifyUserEmail.html
var randomNumber = // generate with math.random() // lets say 111

Putting in above format of customUrl it looks something like this

放入customUrl的上述格式,它看起来像这样

customUrl:http://localhost:8080/[email protected]&id=111

Save this customUrl somewhere (probably in your database) Now, send an email to user with email body containing this cutomUrl link.

将此 customUrl 保存在某处(可能在您的数据库中) 现在,向用户发送一封电子邮件,电子邮件正文包含此 cutomUrl 链接。

<a href="customUrl">Click to verify your email</a>

When user clicks on the link he/she will be directed to verifyUserEmail.htmlpage and when that happens you can extract the page urlcontaining emailand idinformation

当用户点击链接时,他/她将被定向到verifyUserEmail.html页面,当发生这种情况时,您可以提取包含电子邮件ID信息的页面url

For example in angular I go like this-

例如在角度我去这样 -

var urlVerifyData = $location.url(); or $location.absUrl();

Now extract emailform urlVerifyDatastring using javascript string methods

现在使用 javascript 字符串方法提取电子邮件表单urlVerifyData字符串

Request your server with this emailand urlVerifyData

使用此电子邮件urlVerifyData请求您的服务器

Now query your database for this email and verify previously stored customUrlwith user's urlVerifyData

现在,查询数据库的这封电子邮件,并确认之前存储customUrl与用户的urlVerifyData

If they match, hola ! You got yourself a genuine user !!!

如果他们匹配,你好!你让自己成为一个真正的用户!!!

回答by Patrice Thimothee

I would like to present a slightly different approach from the ones proposed.

我想提出一种与提议的方法略有不同的方法。

This method does not put the hash into the database (therefore less interaction with it)

此方法不会将哈希放入数据库中(因此与它的交互较少)

You don't need to register the hash in the database. Here's an overview after receiving a registration request:

您不需要在数据库中注册哈希。以下是收到注册请求后的概述:

  1. You encode the user id + registration time
  2. You send the token to the user
  3. When the user triggers his registration request, you decode the token.
  4. Because The decoded token contains the user id + the time, you can mark the user as registered by increasing their role (registered, subscriber, admin, etc.) for instance
  1. 您对用户 ID + 注册时间进行编码
  2. 您将令牌发送给用户
  3. 当用户触发他的注册请求时,您对令牌进行解码。
  4. 因为解码后的令牌包含用户 ID + 时间,所以您可以通过增加他们的角色(注册、订阅者、管理员等)来将用户标记为已注册

Translated into code, you would have something like this:

翻译成代码,你会得到这样的东西:

1- Encode the token

1-编码令牌

function encodeRegistrationToken()
{
    // jsonweb automatically adds a key that determines the time, but you can use any module
    const jwt = require('jsonwebtoken');

    // The information we need to find our user in the database (not sensible info)
    let info = {id: yourUserId};

    // The hash we will be sending to the user
    const token = jwt.sign(info, "yoursecretkey");

    return token;
}

// ... 
let token = encodeRegistrationToken();

2- Send token to the user via any appropriate way

2-通过任何适当的方式向用户发送令牌

// Your implementation of sending the token
sendTokenToUser(token);

3- Decode the token

3-解码令牌

function decodeRegistrationToken(token)
{   
    const jwt = require('jsonwebtoken');
    let decoded = jwt.verify(token, "yoursecretkey");

    let userId = decoded.id;

    // Check that the user didn't take too long
    let dateNow = new Date();
    let tokenTime = decoded.iat * 1000;

    // Two hours
    let hours = 2;
    let tokenLife = hours * 60 * 1000;

    // User took too long to enter the code
    if (tokenTime + tokenLife < dateNow.getTime())
    {
        return {            
            expired: true
        };
    }

    // User registered in time
    return {
        userID
    };

}

4 - Update your database

4 - 更新您的数据库

  • Upgrade the user role to subscriber
  • 将用户角色升级为订阅者

or

或者

  • Set their "register" key to true
  • 将他们的“注册”键设置为 true

Quick note: You can further encode the user id when encoding your token if you want (it's easily accessible).

快速说明:如果需要,您可以在编码令牌时进一步编码用户 ID(它很容易访问)。

回答by AYUSHI AGARWAL

    function generateLink() {
        var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        var token = '';
        for (var i = 16; i > 0; --i) {
            var rand = Math.round(Math.random() * (chars.length - 1))
            token += chars[rand];
        }
        var link = "http://localhost" + "/verify?id=" + token;
        return link;
    }

    // npm install @sendGrid/mail --save

    //library for generating link using SendGrid
    const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey("SENDGRID_API_KEY"); //create an account on sendgrid and get an API key

    // generated link is send to the user's email for email verification
    let sendVerifyEmailLink = (req, res) => {
        var link = generateLink();
        const msg = {
            to: '[email protected]',
            from: '[email protected]',
            subject: 'Account Verifictaion',
            text: 'Hello,\n\n' + 'Please verify your account by clicking the link:\/\/\n',
            html: 'Hello,\n\n <br> Please verify your account by clicking the link: \n <br> <strong><a href = ' + link + '>http:\/\/ Click here to verify the given Link </a></strong>.\n .<br>Thanks<br>',
        };
        sgMail.send(msg).then(() => { }, error => {
            console.error(error);

            if (error.response) {
                console.error(error.response.body)
            }
        });
        console.log(msg)
    }