How to make login with Nodejs and MongoDB

0 votes

I created a system for signups and hashes. I'm having trouble figuring out how to transfer the values from the react file into the js code below, then compare the email and hashed password to validate.

const express = require('express')
const router = express.Router()
const signUpTemplateCopy = require('../models/SignUpModels')
const bcrypt = require('bcrypt')

router.post('/signup',async(request, response)=>{

    const saltPassword = await bcrypt.genSalt(12)
    const securePassword = await bcrypt.hash(request.body.password, saltPassword)


    const signedUpUser = new signUpTemplateCopy({
        firstName:request.body.firstName,
        lastName:request.body.lastName,
        password:securePassword,
        email:request.body.email,
        userType:request.body.userType
    })
    signedUpUser.save()
    .then(data =>{
        response.json(data)
    })
    .catch(error=>{
        response.json(error)
    })
})
router.post('/login',async(request, response)=>{

    const validPassword = await bcrypt.compare(password, hashedPassword);
    
    signedUpUser.save()
    .then(data =>{
        response.json(data)
    })
    .catch(error=>{
        response.json(error)
    })
})


// router.get('/signin')
module.exports = router

this is the react code(i am new so i don't have alot of knowledge on the matter

      axios
        .post("http://localhost:4000/app/login", {
          email: this.state.email,
          password: this.state.password,
        })
        .then((res) => {
          console.log(res.data.access);
          var token = res.data.access;
          sessionStorage.setItem("tree", token);
          this.props.history.push("/Dashboard");

any leads will also help. thank you.

Jun 15, 2022 in Node-js by Vaani
• 7,070 points
10,236 views

1 answer to this question.

0 votes

MongoDB Login and Registration with Node js Express
Create a login and registration system using node js, express, and a MongoDB database by following the instructions below:

Install the Node JS Express App and Modules first.
Connect Node Express Js App to MongoDB in Step 2
Step 3: Make a Model
Step 4: In app.js, import modules and create routes.
Step 5: Create Login and Registration Views in 
Step 6: Start the Development Server

Step 1 – Install Node JS Express App and Modules

Execute the following command on terminal to create new directory for node js login and registration system with mongodb:

express --view=ejs myApp

Then execute the following command to enter your myApp app directories, So open your cmd and run the following command:

cd myApp

Your node express js app structure looks like:

Install some required node module; so open again your cmd and run the following commands:

 npm install    
 npm install express-flash --save
 npm install express-session --save
 npm install mongoose
 npm install passport passport-local --save
 npm install passport-local-mongoose --save
 npm install body-parser --save

express-flash

Flash is an extension of connect-flash with the ability to define a flash message and render it without redirecting the request.

express-session

Express.js uses a cookie to store a session id.

body-parser

Body-parser allows express to read the body and then parse that into a JSON object that we can understand.

Passport:

Passport is authentication middleware for Node. js. Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.

Mongoose:

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.

Step 2 – Connect Node js Express with MongoDB

Create a new file name database.js; so visit your app root directory and create new file name database.js. Then add the following code into to connect node js express app with mongoDB database:

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/node-mongodb', {useNewUrlParser: true});

var conn = mongoose.connection;

conn.on('connected', function() {

    console.log('database is connected successfully');

});

conn.on('disconnected',function(){

    console.log('database is disconnected successfully');

})

conn.on('error', console.error.bind(console, 'connection error:'));

module.exports = conn;

Step 3 – Create Model

Create model; so visit your app directory and create directory name Models. And inside this directory; create a userModel.js file and then add the following code into it:

const mongoose = require("../database");


// create an schema

var userSchema = new mongoose.Schema({

            name: String,

            password: String,

            email:String

        });


var userModel=mongoose.model('users',userSchema);


module.exports = mongoose.model("Users", userModel);

 

Step 4 – Import Modules and Create routes in app.js

Import modules and create login and registration routes in app.js file; So visit your app root directory and open app.js file in any text editor; then add the following code into it:

var express = require("express");

var mongoose = require("mongoose");

var passport = require("passport");

var bodyParser = require("body-parser");

var LocalStrategy = require("passport-local");

var passportLocalMongoose = require("passport-local-mongoose");

var User = require("./models/userModel");

var app = express();

app.set("view engine", "ejs");

app.use(bodyParser.urlencoded({ extended: true }));

app.use(require("express-session")({

secret: "node js mongodb",

resave: false,

saveUninitialized: false

}));

app.use(passport.initialize());

app.use(passport.session());

passport.use(new LocalStrategy(User.authenticate()));

passport.serializeUser(User.serializeUser());

passport.deserializeUser(User.deserializeUser());

//=====================

// ROUTES

//=====================

// Showing home page

app.get("/", function (req, res) {

res.render('register', {

title: 'Registration Page',

name: '',

email: '',

password: ''    

})

});

// Showing secret page

app.get("/home", isLoggedIn, function (req, res) {

res.render("home");

});

// Showing register form

app.get("/register", function (req, res) {

res.render('register', {

title: 'Registration Page',

name: '',

email: '',

password: ''    

})

});

// Handling user signup

app.post("/register", function (req, res) {

var email = req.body.email

var password = req.body.password

User.register(new User({ email: email }),

password, function (err, user) {

if (err) {

console.log(err);

return res.render("register");

}

passport.authenticate("local")(

req, res, function () {

req.flash('success', 'You have logged in')

res.render("home");

});

});

});

//Showing login form

app.get("/login", function (req, res) {

res.render('login', {

title: 'Login',

email: '',

password: ''     

})

});

//Handling user login

app.post("/login", passport.authenticate("local", {

successRedirect: "/home",

failureRedirect: "/login"

}), function (req, res) {

});

//Handling user logout

app.get("/logout", function (req, res) {

req.logout();

res.redirect("/");

});

function isLoggedIn(req, res, next) {

if (req.isAuthenticated()) return next();

res.redirect("/login");

}

var port = process.env.PORT || 3000;

app.listen(port, function () {

console.log("Server Has Started!");

});

 

Step 5: Create Login and Registration Views

Create login and registration views; so visit the views directory and create the following views file into it:

  • login.ejs
  • register.ejs
  • home.ejs

Now, open your login.ejs file and update the following code into your file:

<!DOCTYPE html>

<html>

<head>

<title><%= title %></title>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

</head>

<body>

<% if (messages.error) { %>

<p style="color:red"><%- messages.error %></p>

<% } %>

<% if (messages.success) { %>

<p style="color:green"><%- messages.success %></p>

<% } %>

<form action="/login" method="post" name="form1">

<div class="form-group">

<label for="exampleInputEmail1">Email</label>

<input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" value="">

</div>

<div class="form-group">

<label for="exampleInputEmail1">Password</label>

<input type="password" name="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="*********" value="">

</div>

<input type="submit" class="btn btn-primary" value="Add">

<a href="auth/register" class="btn btn-success ml-2">Register Here</a>

</form>

</body>

</html>

Now, open your register.ejs file and update the following code into your file:

<!DOCTYPE html>

<html>

<head>

<title><%= title %></title>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

</head>

<body>

<% if (messages.error) { %>

<p style="color:red"><%- messages.error %></p>

<% } %>

<% if (messages.success) { %>

<p style="color:green"><%- messages.success %></p>

<% } %>

<form action="/register" method="post" name="form1">

<div class="form-group">

<label for="exampleInputEmail1">Name</label>

<input type="name" name="name" class="form-control" id="name" aria-describedby="nameHelp" placeholder="Enter name" value="">

</div>  

<div class="form-group">

<label for="exampleInputEmail1">Email</label>

<input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" value="">

</div>

<div class="form-group">

<label for="exampleInputEmail1">Password</label>

<input type="password" name="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="*********" value="">

</div>

<input type="submit" class="btn btn-primary" value="Add">

<a href="auth/login" class="btn btn-success ml-2">Login</a>

</form>

</body>

</html>

This login.ejs file contains login form.

Recommended:-Node js Delete Data by id into MongoDB Tutorial

Next, open your home.ejs file and update the following code into your file:

<!DOCTYPE html>

<html>

<head>

<title><%= title %></title>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

</head>

<body>

<div class="container">

<% if (messages.error) { %>

<p style="color:red"><%- messages.error %></p>

<% } %>

<% if (messages.success) { %>

<p style="color:green"><%- messages.success %></p>

<% } %>

<div class="card">

<div class="card-header">

Dashboard <b><%= name %></b>

</div>

<div class="card-body">

<h5 class="card-title">Welcome</h5>

<p class="card-text">You have successfully login</p>

<a href="logout" class="btn btn-primary">Logout</a>

</div>

</div>

</div>

</body>

</html>

Step 6: Run Development Server

You can use the following command to run development server:

//run the below command
npm start
after run this command open your browser and hit 
http://127.0.0.1:3000/

Conclusion

Node js + MongoDB user login and registration form example. In this tutorial, you have learn how to create user registration and login authentication application using node js + express js + MongoDB database.

To know more about Node JS, It's recommended to join Node JS Certification today.

answered Jun 16, 2022 by Neha
• 9,020 points

Related Questions In Node-js

0 votes
0 answers

How can i make my REST API Faster with nodejs and express?

Summarize the problem My problem: I have built ...READ MORE

Aug 19, 2022 in Node-js by Neha
• 9,020 points
814 views
0 votes
1 answer

How to create an Excel File with Nodejs?

Hello @kartik, Just create a file with Tabs ...READ MORE

answered Sep 7, 2020 in Node-js by Niroj
• 82,840 points
2,498 views
+1 vote
1 answer

How to make external HTTP requests with Node.js ?

Hello @kartik, Use this: var http = require('http'); var options ...READ MORE

answered Oct 12, 2020 in Node-js by Niroj
• 82,840 points
1,865 views
0 votes
1 answer

How to use MongoDB with promises in Node.js?

Hello @kartik, Try this: var MongoClient = require('mongodb').MongoClient var url ...READ MORE

answered Oct 12, 2020 in Node-js by Niroj
• 82,840 points
1,366 views
0 votes
1 answer

Truffle tests not running after truffle init

This was a bug. They've fixed it. ...READ MORE

answered Sep 11, 2018 in Blockchain by Christine
• 15,790 points
1,953 views
0 votes
1 answer

Hyperledger Sawtooth vs Quorum in concurrency and speed Ask

Summary: Both should provide similar reliability of ...READ MORE

answered Sep 26, 2018 in IoT (Internet of Things) by Upasana
• 8,620 points
1,479 views
0 votes
1 answer
0 votes
1 answer

How to host MEAN stack application with Angular and nodejs on windows IIS

It's fine that you're using Angular. Be ...READ MORE

answered May 27, 2022 in Node-js by Neha
• 9,020 points
1,382 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP