DEV Community

Cover image for ECOMMERCE Website Using MERN Part-6.1 ( Authentication { Setup } )
Bikramjeet Sarmah
Bikramjeet Sarmah

Posted on • Updated on

ECOMMERCE Website Using MERN Part-6.1 ( Authentication { Setup } )

In this blog we will be setting up the user by making userModel, userController as well as userRoutes. This blog is gonna be a long one but preety simple as it will be almost same as our products

Step-1 Installing the necessary dependencies

Open up the terminal and install the following dependencies

  1. BcryptJs - For encrypting & decrypting our passwords
  2. Json Web Token - For Authentication
  3. Validator - For validating some fields like name etc
  4. Nodemailer - For sending mails
  5. Cookie Parser
  6. Body Parser

by writing npm i bcryptjs jsonwebtoken validator nodemailer cookie-parser body-parser.

Step-2 After installing we just make the userModel by making a file named userModel.js inside of models folder.

The code for the User Model is below. If you don't understand some lines do let me know in the comments :)

const mongoose = require("mongoose");
const validator = require("validator");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "Please Enter Your Name"],
    maxLength: [30, "Name cannot exceed 30 characters"],
    minLength: [4, "Name should have more than 4 characters"],
  },
  email: {
    type: String,
    required: [true, "Please Enter Your Email"],
    unique: true,
    validate: [validator.isEmail, "Please Enter a valid Email"],
  },
  password: {
    type: String,
    required: [true, "Please Enter Your Password"],
    minLength: [8, "Password should be greater than 8 characters"],
    select: false,
  },
  avatar: {
    public_id: {
      type: String,
      required: true,
    },
    url: {
      type: String,
      required: true,
    },
  },
  role: {
    type: String,
    default: "user",
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },

  resetPasswordToken: String,
  resetPasswordExpire: Date,
});

module.exports = mongoose.model("User", userSchema);
Enter fullscreen mode Exit fullscreen mode

Step-3 Lets make our registerUser function in a new file named userController.js inside of our controllers folder

const ErrorHandler = require("../utils/errorHandler");
const catchAsyncErrors = require("../middleware/catchAsyncErrors");
const User = require("../models/userModel");

// Register User
exports.registerUser = catchAsyncErrors(async (req, res, next) => {
  const { name, email, password } = req.body;

  const user = await User.create({
    name,
    email,
    password,
    avatar: {
      public_id: "This is a sample id",
      url: "profile pic url",
    },
  });

  res.status(201).json({
    success: true,
    user,
  });
});
Enter fullscreen mode Exit fullscreen mode

Here we are importing our model as well as our ErrorHandlers.
And inside the function we destructured our req.body and extract the name, email & password and create the user with create({}) where we are sending those values including avatar which we will be doing using cloudinary while doing the front-end.

Step-4 Now lets make userRoutes.js inside of routes folder and write the following code.

const express = require("express");
const router = express.Router();
const { registerUser } = require("../controllers/userController");

router.route("/register").post(registerUser);

module.exports = router;

Enter fullscreen mode Exit fullscreen mode

Its explanation is preety simple, we just imported express and called the Router() and then made the route /register with the registerUser function from userController

Step-5 Now to use this router we write the following code inside of our app.js file
1. const userRoutes = require("./routes/userRoutes)
2. app.use("/api/v1", userRoutes)

Our app.js shall look like this
App.js

So our basic Setup is done.
In the Next Blog we will be encrypting the user's password

Discussion (2)

Collapse
mcwolfmm profile image
mcwolfmm

Here begins the interesting part :)

I don't like the fact that once you create a user you return the password in the reply. In general, this does not open a big hole in security, but it is still good not to do it.

Therefore, my advice is to remove the password field from the answer.
I have another remark, but I will wait to see how you develop the topic.

Collapse
bikramjeetsarmah profile image
Bikramjeet Sarmah Author

ya ya i will be removing that in the next blog which will probably come by tomorrow. Securing and managing password with auto login will also be included there.