Implementing Authentication in Node.js
Tags: backend, computerscience, performance, coding
Published: 2023-10-20 18:52:30


Authentication is a crucial aspect of web applications, especially when building a blog where users need to create accounts, log in, and manage their content securely. In this tutorial, we'll walk you through implementing authentication in a Node.js blog using the popular authentication library, Passport.js, along with a MongoDB database for storing user information.

## Prerequisites

Before we begin, make sure you have the following prerequisites installed:

1. **Node.js**: You can download and install Node.js from [nodejs.org](https://nodejs.org/).

2. **MongoDB**: Install MongoDB from [mongodb.com](https://www.mongodb.com/try/download/community).

3. **A code editor** of your choice (e.g., Visual Studio Code).

## Setting Up the Project

1. **Initialize Your Project**: Create a new directory for your project and run the following command to initialize a Node.js project with npm:

    ```shell
    npm init -y
    ```
2. **Install Dependencies**: Install the necessary packages:

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

3. **Create** Project Structure:
Create the following project structure:

    ```
    ├── app.js
    ├── models
    │   └── User.js
    ├── routes
    │   ├── auth.js
    │   └── index.js
    ├── views
    │   ├── login.ejs
    │   ├── register.ejs
    │   ├── dashboard.ejs
    │   └── home.ejs
    ├── public
    │   └── styles.css
    └── .env
    ```
4. **Initialize MongoDB Connection**:
In app.js, set up your MongoDB connection using Mongoose:

    ```
    const mongoose = require('mongoose');

    mongoose.connect('mongodb://localhost/nodejs-blog-auth', {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    ```

    Replace 'mongodb://localhost/nodejs-blog-auth' with your MongoDB connection string.

# Implementing Passport.js for Authentication

1. **Configure Passport.js**:
In app.js, configure Passport.js for authentication:

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

// Initialize Passport
app.use(passport.initialize());
app.use(passport.session());
```


2. Create User Model:
Define a User model in models/User.js:

```javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  username: String,
  password: String,
});

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

3. Implement Passport Local Strategy:
Create a Passport Local Strategy for user authentication in config/passport.js:

```javascript
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/User');

module.exports = function (passport) {
  passport.use(
    new LocalStrategy((username, password, done) => {
      User.findOne({ username: username }, (err, user) => {
        if (err) return done(err);
        if (!user) return done(null, false, { message: 'Incorrect username' });
        if (user.password !== password)
          return done(null, false, { message: 'Incorrect password' });

        return done(null, user);
      });
    })
  );

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

  passport.deserializeUser((id, done) => {
    User.findById(id, (err, user) => {
      done(err, user);
    });
  });
};
```

4. Create Authentication Routes:
Create authentication routes for login and registration in routes/auth.js:

```javascript
const express = require('express');
const router = express.Router();
const passport = require('passport');
const User = require('../models/User');

// Register
router.post('/register', (req, res) => {
  // Implement user registration logic here
});

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

module.exports = router;
```

5. Create Views for Authentication:
Create login and registration forms in the views directory (login.ejs and register.ejs).

Set Up Routes:
In routes/index.js, set up your main application routes, including the authentication routes:

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

// Define your routes here

module.exports = router;
```

6. Include Passport Configuration:
Include the Passport configuration in app.js:

```javascript
require('./config/passport')(passport);
```

7. Start the Server:
Start your Express server in app.js:

```javascript
const PORT = process.env.PORT || 3000;

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

Conclusion
In this tutorial, we've laid out the foundation for implementing authentication in a Node.js blog using Passport.js and MongoDB. You can now expand upon this foundation to add user registration, password reset, and user profile functionality. Remember to handle security best practices, such as hashing passwords securely and implementing user input validation.

Feel free to explore more features like user roles, JWT authentication, and authorization to enhance the security and functionality of your Node.js blog.