How To Create a user login system using Node.js MongoDB

 Creating a user login system using Node.js typically involves using a web framework (e.g., Express.js) for routing and handling HTTP requests, a database (e.g., MongoDB, MySQL) to store user data, and packages like `passport` for authentication. Below is a simplified example of how you can create a user login system using Node.js and Express.js with local authentication (username and password) and MongoDB as the database. Before you begin, ensure you have Node.js and MongoDB installed.

Set Up Your Project:

   Create a new directory for your project, navigate to it in your terminal, and run the following commands to set up your project and install the necessary packages:

   ```bash

   mkdir user-authentication

   cd user-authentication

   npm init -y

   npm install express express-session passport passport-local mongoose bcrypt

   ```

Create a File Structure:

   Organize your project files and create the following directory structure:

   ```plaintext

   - user-authentication

     - node_modules

     - models

       - User.js

     - routes

       - index.js

       - users.js

     - views

       - login.ejs

       - signup.ejs

       - dashboard.ejs

     - app.js

   ```

Set Up the Database (MongoDB):

   Set up a MongoDB database, and create a `users` collection. You can use a cloud-based MongoDB service like MongoDB Atlas or install MongoDB locally.

Create Models:

   In the `models` directory, create a `User.js` file to define the User schema and model:

   ```javascript

   // models/User.js

   const mongoose = require('mongoose');

   const userSchema = new mongoose.Schema({

     username: String,

     password: String,

   });

   module.exports = mongoose.model('User', userSchema);

   ```

Create Routes:

   Create route handlers for user authentication in the `routes` directory. Here's an example:


   ```javascript

   // routes/users.js

   const express = require('express');

   const router = express.Router();

   const passport = require('passport');

   const User = require('../models/User');


   // Render the login page

   router.get('/login', (req, res) => {

     res.render('login');

   });

   // Authenticate the user

   router.post(

     '/login',

     passport.authenticate('local', {

       successRedirect: '/dashboard',

       failureRedirect: '/users/login',

       failureFlash: true,

     })

   );

   // Render the registration page

   router.get('/signup', (req, res) => {

     res.render('signup');

   });

   // Handle user registration

   router.post('/signup', (req, res) => {

     const { username, password } = req.body;

     const newUser = new User({ username, password });

     newUser.save((err) => {

       if (err) {

         console.error(err);

         res.redirect('/users/signup');

       } else {

         res.redirect('/users/login');

       }

     });

   });

   // Log out the user

   router.get('/logout', (req, res) => {

     req.logout();

     res.redirect('/');

   });

   module.exports = router;

   ```

   You should also create routes for the dashboard and other pages as needed.

Set Up Passport for Authentication:

   Configure Passport.js for local authentication in your `app.js` file:

   ```javascript

   // app.js

   const express = require('express');

   const session = require('express-session');

   const passport = require('passport');

   const LocalStrategy = require('passport-local').Strategy;

   const User = require('./models/User');

   const mongoose = require('mongoose');

   const bcrypt = require('bcrypt');

   // Initialize Express

   const app = express();

   // ...

   // Passport Configuration

   passport.use(

     new LocalStrategy((username, password, done) => {

       User.findOne({ username }, (err, user) => {

         if (err) return done(err);

         if (!user) return done(null, false, { message: 'Incorrect username.' });

         bcrypt.compare(password, user.password, (err, res) => {

           if (res) {

             return done(null, user);

           } else {

             return done(null, false, { message: 'Incorrect password.' });

           }

         });

       });

     })

   );

   passport.serializeUser((user, done) => {

     done(null, user.id);

   });

   passport.deserializeUser((id, done) => {

     User.findById(id, (err, user) => {

       done(err, user);

     });

   });

   // ...

   // Initialize Passport and session middleware

   app.use(passport.initialize());

   app.use(passport.session());

   // ...

   // Define routes

   const indexRouter = require('./routes/index');

   const usersRouter = require('./routes/users');

   app.use('/', indexRouter);

   app.use('/users', usersRouter);

   // ...

   // Start the server

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

   app.listen(port, () => {

     console.log(`Server is running on port ${port}`);

   });

   ```

Create Views:

   Create EJS template files for login, signup, and dashboard pages in the `views` directory. Customize these views according to your project's requirements.

Start the Server:

   Run your Node.js application by executing `node app.js` from your project's root directory. Your user authentication system should now be set up and running. Users can sign up, log in, and access the dashboard. Remember that this is a basic example, and you should consider adding security features, error handling, and other enhancements for a production-ready application. Additionally, you may want to explore additional libraries like `express-validator` for form validation and `connect-flash` for displaying flash messages to users.

Comments