DEV Community

Cover image for Authentication in NodeJS With Express and Mongo use Mongoose and  #1
FaresHamel
FaresHamel

Posted on

Authentication in NodeJS With Express and Mongo use Mongoose and #1

  1. Packages Required

You will be needing these following 'npm' packages.

  1. express
    Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications

  2. express-validator
    To Validate the body data on the server in the express framework, we will be using this library. It's a server-side data validation library. So, even if a malicious user bypasses the client-side verification, the server-side data validation will catch it and throw an error.

  3. body-parser
    It is nodejs middleware for parsing the body data.

  4. bcryptjs
    This library will be used to hash the password and then store it to database.This way even app administrators can't access the account of a user.

  5. mongoose
    Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks.

    1. Initiate Project

We will start by creating a node project. So, Create a new folder with the name 'node-auth' and follow the steps below. All the project files should be inside the 'node-auth' folder.

router.js

router.post('/singUp', [
check('username', 'Please Enter a Valid Username').not().isEmpty(),
check('firstname', 'Please Enter a Valid firstname').not().isEmpty(),
check('lastname', 'Please Enter a Valid lastname').not().isEmpty(),
check('city', 'Please Enter a Valid City').not().isEmpty(),
check('ville', 'Please Enter a Valid Ville').not().isEmpty(),
check('numberphone', 'Please Enter a Valid numberPhone').not().isEmpty().isNumeric(),
check('email', 'please Enter a valid Email Address').isEmail(),
check('password', 'please your password is short try again').isLength({ min: 8 }),
], authClient.singUpClient);

const Client = require('../models/clientCls');
const mongose = require('mongoose');
const { validationResult } = require('express-validator');
const bcrypt = require("bcryptjs");
const { error } = require('console');
//Sing up controller with valitaor
module.exports.singUpClient = async(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
const salt = await bcrypt.genSalt(10);

const user = new Client({

    _id: new mongose.Types.ObjectId(),

    username: req.body.username,

    firstname: req.body.firstname,

    lastname: req.body.lastname,

    email: req.body.email,

    password: req.body.password,

    numberPhon: req.body.numberphone,

    city: req.body.city,

    ville: req.body.ville,

    dateInscription: new Date(),

    passwrodEncrypt: await bcrypt.hash(req.body.password, salt)
});

try {
    const emailuser = user.email;

    const resultResearch = await Client.findOne({ email: emailuser });

    if (resultResearch) {

        return res.json({ insertion: false });;
    }


    await user.save().then(result => {

        return res.json({ newname: result.id });

    }).catch(error => {

        return res.send({ newname: error });
    });

} catch (erro) {

    res.json({ message: error });
}
Enter fullscreen mode Exit fullscreen mode

};

Discussion (0)