0

I need to check if the email address used to register on my site actually exists or not. If it exists then it's not generated by some temporary email generator. How can I do it using npm deep-email-validator package?

In my html page I have given names to different input, which I have fetched to index.js using body-parser.

register.html

<!-- Credit of UI Design : https://mdbootstrap.com/docs/standard/extended/login/ -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Montserrat&family=Ubuntu:wght@700&display=swap"
      rel="stylesheet"
    />

    <!-- Font Awesome -->
    <script
      src="https://kit.fontawesome.com/76fae8cbf2.js"
      crossorigin="anonymous"
    ></script>

    <!-- Bootstrap -->
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
      crossorigin="anonymous"
    />
    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
      crossorigin="anonymous"
    ></script>

    <!-- CSS -->
    <link rel="stylesheet" href="css/styles.css" />

    <title>Sign In</title>
  </head>
  <body>
    <div class="container h-custom">
      <div class="row">
        <div class="col-lg-6 div1">
          <img src="images/signin.jpg" />
        </div>
        <div class="col-lg-6 div2">
          <div class="OAuth">
            <form action="/register" method="post">
              <h1>Sign up with</h1>
              <a href="#"
                ><i class="fa-brands fa-google fa-2xl button icon"></i
              ></a>
              <a href="#"
                ><i class="fa-brands fa-facebook-f fa-2xl button icon"></i
              ></a>
              <a href="#"
                ><i class="fa-brands fa-twitter fa-2xl button icon"></i
              ></a>
              <a href="#"
                ><i class="fa-brands fa-linkedin-in fa-2xl button icon"></i
              ></a>
              <p class="divider">Or</p>
              <div class="form">
                <div class="inputdetails">
                  <input
                    type="email"
                    placeholder="Email"
                    class="form-control inputtext"
                    name="email"
                  />
                  <br />
                  <input
                    type="text"
                    placeholder="Password"
                    class="form-control inputtext"
                    name="password"
                  />
                  <br />
                  <input
                    type="text"
                    placeholder="Verify your password"
                    class="form-control inputtext"
                    name="passwordverify"
                  />
                </div>
                <button type="submit" class="btn btn-primary login">
                  REGISTER
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    <div class="copyright">
      <p class="copyright-text">&copy;2022 Made with ❤️ by theAlphaCoder06</p>
      <div class="logo">
        <a href="#"><i class="fa-brands fa-google fa-lg icon"></i></a>
        <a href="#"><i class="fa-brands fa-facebook-f fa-lg icon"></i></a>
        <a href="#"><i class="fa-brands fa-twitter fa-lg icon"></i></a>
        <a href="#"><i class="fa-brands fa-linkedin-in fa-lg icon"></i></a>
      </div>
    </div>
  </body>
</html>

index.js

In the app.post('/register`), what I will have to do to check if the email being used to login in to my page exists and is not temporary.

const express = require('express');
const mongoose = require('mongoose');
const bodyparser = require('body-parser');
const app = express();
const port = 3000;

app.use(express.static('public'));
app.use(bodyparser.urlencoded({extended:false}))
app.use(bodyparser.json());

mongoose.connect("mongodb://127.0.0.1:27017/user");

const usersSchema = new mongoose.Schema({
    email: String,
    password: String
});

const User = mongoose.model('User', usersSchema);


app.get("/", (req, res)=>{
    res.sendFile( __dirname + "/signup.html");
});

app.get("/register", (req, res)=>{
    res.sendFile( __dirname + "/register.html");
})

app.get("/home", (req, res)=>{
    res.sendFile( __dirname + "/index.html");
});


app.post('/', (req, res)=>{
    const password = req.body.password;
    User.findOne({email: req.body.email}, (err, foundUser)=>{
        if(err)
            console.log(err);
        else{
            if(foundUser){
                if(foundUser.password === password){
                    res.redirect("/home");
                }
                else{
                    res.send("Please enter correct password");
                }
            }
            else{
                res.redirect("/register");
            }
        }
    })
})
app.post("/register", (req, res)=>{
    const newUser = new User({
        email: req.body.email,
        password: req.body.password,
        passwordverify: req.body.passwordverify
    })
    User.findOne({email: req.body.email}, (err, foundUser)=>{
        if(err)
            console.log(err);
        else{
            if(foundUser){
                res.send("Already a user! Please login to your account")
            }
            else{
                if(req.body.password === req.body.passwordverify){
                    newUser.save();
                    res.redirect('/home')
                }
                else{
                    res.send("Password did not match");
                }
            }
        }
    })
})

app.listen(port, (req, res)=>{
    console.log(`Server is listening on ${port}`)
})

1 Answer 1

0

According to deep-email-validator package, you can validate email before looking into the database. In you /register controller you can to do something like this.

import { validate } from 'deep-email-validator'

app.post('/register', async (req, res) => {
  /* You can validate email before finding it on the database here and return response */
  const emailValid = await validate(req.body.email)
  if (!emailValid.valid) return res.send('Email is not valid. Please try again!')

  const newUser = new User({
    email: req.body.email,
    password: req.body.password,
    passwordverify: req.body.passwordverify
  })
  User.findOne({ email: req.body.email }, (err, foundUser) => {
    if (err) console.log(err)
    else {
      if (foundUser) {
        res.send('Already a user! Please login to your account')
      } else {
        if (req.body.password === req.body.passwordverify) {
          newUser.save()
          res.redirect('/home')
        } else {
          res.send('Password did not match')
        }
      }
    }
  })
})

and you can refactor your code using async/await syntax as well like this

app.post('/register', async (req, res) => {
  /* You can validate email before finding it on the database here and return response */
  try {
    const emailValid = await validate(req.body.email)
    if (!emailValid.valid) return res.send('Email is not valid. Please try again!')

    const user = await User.findOne({ email: req.body.email })
    if (user) return res.send('Already a user! Please login to your account')

    if (req.body.password !== req.body.passwordverify) return res.send('Password did not match')

    await User.create({
      email: req.body.email,
      password: req.body.password,
      passwordverify: req.body.passwordverify
    })

    res.redirect('/home')
  } catch (err) {
    /* Catch all error here */
    console.log('Error occured!', err)
  }
})
Sign up to request clarification or add additional context in comments.

9 Comments

Sir, can you please explain what actually async functions are, what does await do. Moreover, throw some light on try and catch functions.
you can learn here about async await in javascript
Error occured! TypeError: validate is not a function at X:\OAuth\index.js:53:30 The above code is having this error!
try importing like this import validate from 'deep-email-validator'
Still it's giving the same error!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.