Tutorial
Auth Routes 1

REGISTER USER & Controllers Auth.js

Auth.js

server
├── controllers
│   ├── auth.js
auth.js
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import User from "../models/User.js";
 
/* REGISTER USER */
export const register = async (req, res) => {
  try {
    const {
      firstName,
      lastName,
      email,
      password,
      picturePath,
      friends,
      location,
      occupation,
    } = req.body;
 
    const salt = await bcrypt.genSalt();
    const passwordHash = await bcrypt.hash(password, salt);
 
    const newUser = new User({
      firstName,
      lastName,
      email,
      password: passwordHash,
      picturePath,
      friends,
      location,
      occupation,
      viewedProfile: Math.floor(Math.random() * 10000),
      impressions: Math.floor(Math.random() * 10000),
    });
    const savedUser = await newUser.save();
    res.status(201).json(savedUser);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};
 

We will discuss Auth.js, which is a file inside the controller folder. This file is used to handle user authentication and registration. We will break down the code and explain what each section does in detail. By the end of this blog post, you will have a good understanding of how this file works and how it handles user authentication.

Auth.js contains the logic for user registration and authentication. In this file, we will create an async function that registers a new user, encrypts the password, and saves it to the database. We will then use the response object to send back the user object to the client.

Let's dive into the details of the Auth.js file and its functionalities.

Registering a User

First, we need to create a function to register a new user. We will use the Express.js framework for this. The function will be an async function that takes in two parameters: req (request) and res (response).

auth.js
export const register = async (req, res) => {
    // function body goes here
}

The req parameter provides us with the request body that we get from the front end, and the res parameter is what we are going to be sending back to the front end. We will use the res parameter to send back the user object to the front end.

Try-Catch block:

Inside the register function, there is a try-catch block. The try block will attempt to do the logic, and if it fails, the catch block will execute. Here is how it is structured:

auth.js
    try {
        // function body goes here
    } catch (error) {
        res.status(500).json({ error: error.message });
    }

In case of an error, we will be sending a status code of 500, which means something went wrong on the server.

Structuring request body:

In the next section of the code, we are structuring the request body. We will be receiving these parameters from the front end, and we are storing them in variables inside the register function. Here is how it is done:

auth.js
    const {
      firstName,
      lastName,
      email,
      password,
      picturePath,
      friends,
      location,
      occupation,
    } = req.body;
 
    const viewedProfile = null;
    const impressions = Math.floor(Math.random() * 10000);

The req.body object will contain all the parameters that we are receiving from the front end. In this section, we are destructuring the object and storing the values in individual variables. We are also assigning some default values to the viewedProfile and impressions variables.

Encrypting the password:

In the next section, we are encrypting the password. Here is how it is done:

auth.js
    const salt = await bcrypt.genSalt();
    const passwordHash = await bcrypt.hash(password, salt);
 

We are using the bcrypt library to encrypt the password. We are using the bcrypt.genSalt() function to generate a salt, and then we are using the bcrypt.hash() function to encrypt the password. The bcrypt.hash() function takes in two parameters: the password and the salt. The salt is used to encrypt the password. The salt is a random string that is added to the password before it is encrypted. This makes it harder for hackers to decrypt the password.

Creating a new user:

We are generating a random salt using the bcrypt.genSalt() function, and we are using this salt to encrypt the password using the bcrypt.hash() function. Now, we will create a new user object and save it to the database.

auth.js
    const newUser = new User({
        firstName,
        lastName,
        email,
        password: passwordHash,
        picturePath,
        friends,
        location,
        occupation,
        viewedProfile,
        impressions
    });
 

We are creating a new User object using the User model from the database. We are passing all the values we received from the front end and the hashed password.

Saving the user to the database:

In the next section of the code, we are saving the user object to the database. Here is how it is done:

auth.js
const savedUser = await newUser.save();
 

We are calling the save() function on the newUser object, which will save the user to the database.

Sending the response back to the front end:

In the last section of the code, we are sending the response back to the front end. Here is how it is done:

auth.js
    res.status(201).json(savedUser);
 

Explanation of the code:

auth.js
import bcrypt from "bcrypt"; // importing bcrypt for password hashing
import jwt from "jsonwebtoken"; // importing jwt for token generation
import User from "../models/User.js"; // importing user model
 
/* REGISTER USER */
export const register = async (req, res) => { // async function to handle user registration
  try { // wrapping in try block for error handling
    const {
      firstName, // destructuring user input data from request body
      lastName, // destructuring user input data from request body
      email, // destructuring user input data from request body
      password, // destructuring user input data from request body
      picturePath,// destructuring user input data from request body
      friends,// destructuring user input data from request body
      location, // destructuring user input data from request body
      occupation, // destructuring user input data from request body
    } = req.body; //The req.body object will contain all the parameters that we are receiving from the front end
 
    const salt = await bcrypt.genSalt(); // generating salt for password hashing
    const passwordHash = await bcrypt.hash(password, salt); // hashing the password using bcrypt
 
    const newUser = new User({ // creating new user object with hashed password
      firstName, // assigning firstName property to firstName variable
      lastName, // assigning lastName property to lastName variable
      email, // assigning email property to email variable
      password: passwordHash, // assigning password property to passwordHash variable
      picturePath, // assigning picturePath property to picturePath variable
      friends, // assigning friends property to friends variable
      location, // assigning location property to location variable
      occupation, // assigning occupation property to occupation variable
      viewedProfile: Math.floor(Math.random() * 10000), // assigning random number to viewedProfile property
      impressions: Math.floor(Math.random() * 10000), // assigning random number to impressions property
    });
    const savedUser = await newUser.save(); // saving new user object in the database
    res.status(201).json(savedUser); // returning saved user object with 201 status code
  } catch (err) { // handling error if any of the above steps failed
    res.status(500).json({ error: err.message }); // returning error message with 500 status code
  }
};