Login system with NodeJS, MongoDB and Express

August 27, 2023

Creating a Login System with MongoDB and Node.js (Using ES6 Imports and File Structure)

File Structure:

├── index.js
├── user.js
└── checkLoggedIn.js

Dependencies

  • express: Web framework for Node.js
  • mongoose: Library for MongoDB object data modeling
  • express-session: To manage sessions
  • connect-mongo: MongoDB session store for express-session

Install the depedencies with the following command:

npm install express mongoose express-session connect-mongo bcrypt

Code Setup

index.js - Main Server File

// index.js
import express from "express";
import mongoose from "mongoose";
import session from "express-session";
import MongoStore from "connect-mongo";
import { User } from "./user.js";
import checkLoggedIn from "./checkLoggedIn.js";
import bcrypt from 'bcrypt';

// Initialize the Express app
const app = express();
app.use(express.json());

// Connect to MongoDB
mongoose.connect("mongodb://localhost:27017/loginDemo", { useNewUrlParser: true, useUnifiedTopology: true });

// Initialize session middleware
app.use(
  session({
    secret: "mysecret",
    resave: false,
    saveUninitialized: false,
    store: MongoStore.create({ mongoUrl: "mongodb://localhost:27017/loginDemo" }),
  })
);

// Routes
app.post('/login', async (req, res) => {
  const { username, password } = req.body;

  const user = await User.findOne({ username });

  if (!user) {
    return res.send('Invalid username or password');
  }

  const isMatch = await bcrypt.compare(password, user.password);

  if (isMatch) {
    req.session.userId = user._id;
    return res.send('Logged in successfully');
  } else {
    return res.send('Invalid username or password');
  }
});

app.get("/logout", (req, res) => {
  req.session.destroy((err) => {
    if (err) {
      res.status(500).send("Could not log out.");
    } else {
      res.send("Logout successful");
    }
  });
});

app.get("/protected", checkLoggedIn, (req, res) => {
  res.send("This is a protected route");
});

// Start the server
app.listen(3000, () => {
  console.log("Server running on http://localhost:3000/");
});

user.js - User Schema and Model

// user.js
import mongoose from "mongoose";
import bcrypt from 'bcrypt';

const UserSchema = new mongoose.Schema({
  username: String,
  password: String,
});

UserSchema.pre('save', function (next) {
  const user = this;
  if (this.isModified('password') || this.isNew) {
    bcrypt.hash(user.password, 10, (err, hash) => {
      if (err) {
        return next(err);
      }
      user.password = hash;
      next();
    });
  } else {
    return next();
  }
});

export const User = mongoose.model("User", UserSchema);

checkLoggedIn.js - Middleware to Check Login Status

// checkLoggedIn.js
const checkLoggedIn = (req, res, next) => {
  if (req.session.userId) {
    next();
  } else {
    res.status(401).send("Not authorized. Please log in.");
  }
};

export default checkLoggedIn;

And that's it! You now have a modular and organized login system using MongoDB, Node.js, and Express with ES6 imports and exports. To test this, you can use tools like Postman to send HTTP requests to your server. Make sure MongoDB is running before you start your app.


Profile picture

Written by Olivier Bonnet who lives and works in Montreal writing a blog that nobody reads 🤪...

© Bonneto 2024