how to do confirm email address with express/node?

前端 未结 8 988
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 09:28

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 mongoo

8条回答
  •  佛祖请我去吃肉
    2020-12-12 10:08

    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

    Translated into code, you would have something like this:

    1- Encode the token

    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

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

    3- Decode the token

    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

    • Upgrade the user role to subscriber

    or

    • Set their "register" key to true

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

提交回复
热议问题