how to do confirm email address with express/node?

前端 未结 8 940
隐瞒了意图╮
隐瞒了意图╮ 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:10

    I spent a lot of time figuring out the perfect way to send confirmation mail. Here is the method I used.

    Libraries

    const jwt = require('jsonwebtoken');
    const nodemailer = require("nodemailer");
    

    Step 1 Encode the user id in a jwt token with an expiration date

    var date = new Date();
    var mail = {
                "id": user.id,
                "created": date.toString()
                }
    
    const token_mail_verification = jwt.sign(mail, config.jwt_secret_mail, { expiresIn: '1d' });
    
    var url = config.baseUrl + "verify?id=" + token_mail_verification;
    

    Step 2 Send the token to the user email address using nodemailer library

     let transporter = nodemailer.createTransport({
            name: "www.domain.com",
            host: "smtp.domain.com",
            port: 323,
            secure: false, // use SSL
            auth: {
                user: "user@domain.com", // username for your mail server
                pass: "Password", // password
            },
    
        });
    
        // send mail with defined transport object
        let info = await transporter.sendMail({
            from: '"NAME" <user@domain.com>', // sender address
            to: user.email, // list of receivers seperated by comma
            subject: "Account Verification", // Subject line
            text: "Click on the link below to veriy your account " + url, // plain text body
        }, (error, info) => {
    
            if (error) {
                console.log(error)
                return;
            }
            console.log('Message sent successfully!');
            console.log(info);
            transporter.close();
        });
    

    Step 3 Accept the verification link

    app.get('/verify', function(req, res) {
        token = req.query.id;
        if (token) {
            try {
                jwt.verify(token, config.jwt_secret_mail, (e, decoded) => {
                    if (e) {
                        console.log(e)
                        return res.sendStatus(403)
                    } else {
                        id = decoded.id;
    
                    
    //Update your database here with whatever the verification flag you are using 
    
    
    
                    }
    
                });
            } catch (err) {
    
                console.log(err)
                return res.sendStatus(403)
            }
        } else {
            return res.sendStatus(403)
    
        }
    
    })
    

    Step 4 Have a coffee and THANK ME for saving your so much time

    PS: This nodemailer SMTP method will even work with your hosting. So no need to go for third party. You can also find ways to use gmail with nodemailer.

    0 讨论(0)
  • 2020-12-12 10:16

    Step 1:

    User Model

    var userSchema = new mongoose.Schema({
        email: { type: String, unique: true },
        isVerified: { type: Boolean, default: false },
        password: String,
      });
    

    Token Model

    const tokenSchema = new mongoose.Schema({
        _userId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
        token: { type: String, required: true },
        expireAt: { type: Date, default: Date.now, index: { expires: 86400000 } }
    });
    

    Step 2: Login

    exports.login = function(req, res, next) {
        User.findOne({ email: req.body.email }, function(err, user) {
            // error occur
            if(err){
                return res.status(500).send({msg: err.message});
            }
            // user is not found in database i.e. user is not registered yet.
            else if (!user){
                return res.status(401).send({ msg:'The email address ' + req.body.email + ' is not associated with any account. please check and try again!'});
            }
            // comapre user's password if user is find in above step
            else if(!Bcrypt.compareSync(req.body.password, user.password)){
                return res.status(401).send({msg:'Wrong Password!'});
            }
            // check user is verified or not
            else if (!user.isVerified){
                return res.status(401).send({msg:'Your Email has not been verified. Please click on resend'});
            } 
            // user successfully logged in
            else{
                return res.status(200).send('User successfully logged in.');
            }
        });
    
    });
    

    Step 3: Sign Up

    exports.signup = function(req, res, next) {
      User.findOne({ email: req.body.email }, function (err, user) {
        // error occur
        if(err){
            return res.status(500).send({msg: err.message});
        }
        // if email is exist into database i.e. email is associated with another user.
        else if (user) {
            return res.status(400).send({msg:'This email address is already associated with another account.'});
        }
        // if user is not exist into database then save the user into database for register account
        else{
            // password hashing for save into databse
            req.body.password = Bcrypt.hashSync(req.body.password, 10);
            // create and save user
            user = new User({ name: req.body.name, email: req.body.email, password: req.body.password });
            user.save(function (err) {
                if (err) { 
                  return res.status(500).send({msg:err.message});
                }
                
                // generate token and save
                var token = new Token({ _userId: user._id, token: crypto.randomBytes(16).toString('hex') });
                token.save(function (err) {
                  if(err){
                    return res.status(500).send({msg:err.message});
                  }
    
                    // Send email (use credintials of SendGrid)
                    var transporter = nodemailer.createTransport({ service: 'Sendgrid', auth: { user: process.env.SENDGRID_USERNAME, pass: process.env.SENDGRID_PASSWORD } });
                    var mailOptions = { from: 'no-reply@example.com', to: user.email, subject: 'Account Verification Link', text: 'Hello '+ req.body.name +',\n\n' + 'Please verify your account by clicking the link: \nhttp:\/\/' + req.headers.host + '\/confirmation\/' + user.email + '\/' + token.token + '\n\nThank You!\n' };
                    transporter.sendMail(mailOptions, function (err) {
                        if (err) { 
                            return res.status(500).send({msg:'Technical Issue!, Please click on resend for verify your Email.'});
                         }
                        return res.status(200).send('A verification email has been sent to ' + user.email + '. It will be expire after one day. If you not get verification Email click on resend token.');
                    });
                });
            });
        }
        
      });
    
    });
    

    Step 4: Verify Account

    // It is GET method, you have to write like that
    //    app.get('/confirmation/:email/:token',confirmEmail)
    
    exports.confirmEmail = function (req, res, next) {
        Token.findOne({ token: req.params.token }, function (err, token) {
            // token is not found into database i.e. token may have expired 
            if (!token){
                return res.status(400).send({msg:'Your verification link may have expired. Please click on resend for verify your Email.'});
            }
            // if token is found then check valid user 
            else{
                User.findOne({ _id: token._userId, email: req.params.email }, function (err, user) {
                    // not valid user
                    if (!user){
                        return res.status(401).send({msg:'We were unable to find a user for this verification. Please SignUp!'});
                    } 
                    // user is already verified
                    else if (user.isVerified){
                        return res.status(200).send('User has been already verified. Please Login');
                    }
                    // verify user
                    else{
                        // change isVerified to true
                        user.isVerified = true;
                        user.save(function (err) {
                            // error occur
                            if(err){
                                return res.status(500).send({msg: err.message});
                            }
                            // account successfully verified
                            else{
                              return res.status(200).send('Your account has been successfully verified');
                            }
                        });
                    }
                });
            }
            
        });
    });
    

    Step 5: Resend Link

    exports.resendLink = function (req, res, next) {
    
        User.findOne({ email: req.body.email }, function (err, user) {
            // user is not found into database
            if (!user){
                return res.status(400).send({msg:'We were unable to find a user with that email. Make sure your Email is correct!'});
            }
            // user has been already verified
            else if (user.isVerified){
                return res.status(200).send('This account has been already verified. Please log in.');
        
            } 
            // send verification link
            else{
                // generate token and save
                var token = new Token({ _userId: user._id, token: crypto.randomBytes(16).toString('hex') });
                token.save(function (err) {
                    if (err) {
                      return res.status(500).send({msg:err.message});
                    }
        
                    // Send email (use credintials of SendGrid)
                        var transporter = nodemailer.createTransport({ service: 'Sendgrid', auth: { user: process.env.SENDGRID_USERNAME, pass: process.env.SENDGRID_PASSWORD } });
                        var mailOptions = { from: 'no-reply@example.com', to: user.email, subject: 'Account Verification Link', text: 'Hello '+ user.name +',\n\n' + 'Please verify your account by clicking the link: \nhttp:\/\/' + req.headers.host + '\/confirmation\/' + user.email + '\/' + token.token + '\n\nThank You!\n' };
                        transporter.sendMail(mailOptions, function (err) {
                           if (err) { 
                            return res.status(500).send({msg:'Technical Issue!, Please click on resend for verify your Email.'});
                         }
                        return res.status(200).send('A verification email has been sent to ' + user.email + '. It will be expire after one day. If you not get verification Email click on resend token.');
                    });
                });
            }
        });
    });
    

    You can take help from this link:https://medium.com/@slgupta022/email-verification-using-sendgrid-in-node-js-express-js-mongodb-c5803f643e09

    0 讨论(0)
提交回复
热议问题