Basic Authentication System using Node.js, Express, and Passport.js

Basic Authentication System using Node.js, Express, and Passport.js

ยท

3 min read

Let's create a step-by-step guide to build a basic Authentication System using Node.js, Express, and Passport.js.

Buy Me A Coffee

Step 1: Set Up Your Project

  1. Create a new project folder:

     mkdir authentication-system
     cd authentication-system
    
  2. Initialize a new Node.js project:

     npm init -y
    
  3. Install necessary dependencies:

     npm install express passport passport-local express-session bcrypt
    

Step 2: Create Your Folder Structure

Create the following folder structure:

authentication-system/
|-- src/
|   |-- routes/
|       |-- index.js
|       |-- users.js
|   |-- models/
|       |-- User.js
|   |-- app.js
|-- server.js

Step 3: Set Up Express Server

In app.js, set up a basic Express server and middleware:

const express = require('express');
const passport = require('passport');
const session = require('express-session');
const LocalStrategy = require('passport-local').Strategy;
const app = express();
const PORT = process.env.PORT || 3000;

// Set up middleware
app.use(express.urlencoded({ extended: true }));
app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

// Set up routes
const indexRoutes = require('./routes/index');
const usersRoutes = require('./routes/users');
app.use('/', indexRoutes);
app.use('/users', usersRoutes);

// Set up passport local strategy
passport.use(new LocalStrategy(
  (username, password, done) => {
    // Replace this with your actual authentication logic
    // For simplicity, we're using a static user object with a hardcoded username and password
    const user = { id: 1, username: 'user', password: '$2b$10$1EnDPgzPK9LuI0Vbyo6whebTaylRgjRcLCAG2b9wTn7BAYsTfUN7K' };

    // Check if the provided username and password are valid
    if (username === user.username && password === user.password) {
      return done(null, user);
    } else {
      return done(null, false, { message: 'Incorrect username or password' });
    }
  }
));

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  // Replace this with your actual user fetching logic
  // For simplicity, we're using a static user object
  const user = { id: 1, username: 'user' };
  done(null, user);
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 4: Create Routes

In routes/index.js, set up the main routes:

const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  res.send('Home Page');
});

module.exports = router;

In routes/users.js, set up routes for user authentication:

const express = require('express');
const passport = require('passport');
const router = express.Router();

router.get('/login', (req, res) => {
  res.send('Login Page');
});

router.post('/login', passport.authenticate('local', {
  successRedirect: '/',
  failureRedirect: '/users/login',
  failureFlash: true,
}));

router.get('/register', (req, res) => {
  res.send('Register Page');
});

router.post('/register', (req, res) => {
  // Replace this with your actual user registration logic
  res.send('Register POST');
});

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

module.exports = router;

Step 5: Set Up User Model

In models/User.js, create a simple User model:

class User {
  constructor(id, username, password) {
    this.id = id;
    this.username = username;
    this.password = password;
  }
}

module.exports = User;

Step 6: Run Your Application

Start the Express server:

node server.js

Visit http://localhost:3000 in your browser, and you should see your Authentication System. Implement the user registration logic in /users/register and handle user sessions as needed in your application.

Buy Me A Coffee

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย