Node.js Level2 (Auth using JWT)

1مُقدمة المُستوى الثانى
2Login & signup pages design

getbootstrap.com

3 Github README.mdfile

Download files

4 Send data to database using async& await

Download files

5Hashing Passwords
1npm i bcrypt
2in schema file :
 
const bcrypt = require('bcrypt');

userSchema.pre("save", async function (next) {
 const salt = await bcrypt.genSalt();
 this.password = await bcrypt.hash(this.password, salt);
 next();
});

المصدر

Download files

6Check email & password (before login)

Download files

7Store jwt in cookies
2Store jwt in cookies
 
var jwt = require("jsonwebtoken");

if (correct email & password) {
  var token = jwt.sign({ id: loginUser._id }, "shhhhh");
  res.cookie("jwt", token, { httpOnly: true, maxAge: 86400000 });
  res.redirect("/home")
}

res.cookie()

Download files

8Function to protect routes
1npm install cookie-parserto get cookies fron browser
2Function to check if there is a jwt in cookies :
 
const requireAuth = (req, res, next) => {
const token = req.cookies.jwt;

 if (token) {
    jwt.verify(token, "shhhhh", (err) => {
  if (err) { res.redirect("/login"); } else {next();}
   });
   } else {
    res.redirect("/login");
}};

Download files

9Function to check if there is JWT (Login user)
 
const checkIfUser = (req, res, next) => {
  const token = req.cookies.jwt;
  if (token) {
    jwt.verify(token, "shhhhh", async (err, decoded) => {
      if (err) {
        res.locals.user = null;
        next();
      } else {
        const currentUser = await AuthUser.findById(decoded.id);
        res.locals.user = currentUser;
        next();
      }
    });
  } else {
    res.locals.user = null;
    next();
  }
};

Download files

10Task & sign out

Delete cookies to sign out:

 
router.get("/signout", (req, res) => {
  res.cookie("jwt", "", { maxAge: 1 });
  res.redirect("/");
});

Download files

Validate Email & Password - Show Errors

11Email already exist ?
 
const isCurrentEmail = await AuthUser.findOne({email: req.body.email})
if (isCurrentEmail) {
  return  console.log("Email already exist")
}

Download files

12Validating Email & Password with Express-Validator
2Check Email & Password
 
const { check, validationResult } = require("express-validator");

router.post(/signup",
[
   check("email", "Please provide a valid email").isEmail(),
   check("password", "Password must be at least 8 characters with 1 upper case letter and 1 number").matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})/),
],

(req, res) => {
const objError = validationResult(req);
console.log(objError.errors);

if (objError.errors.length > 0) {
 return console.log("invalid email OR invalid password")
}}
)

Download files

13Send data to front-end
1in app.js app.use(express.json())
2Using node res.json({ KEY: VALUE });
3From front-end :
 
const form = document.querySelector("form");

form.addEventListener("submit", async (e) => {
e.preventDefault();

const res = await fetch("/signup", {
  method: "POST",
  body: JSON.stringify({ email: emailId.value, password: passwordId.value }),
  headers: { "Content-Type": "application/json" },
});

const data = await res.json();
console.log(data)

});

JavaScript fetch

location.assign(URL)

Download files

14Task solution

Download files

15Task

Download files

16Task solution

Download files

17Task Solution

Download files

Deploying Node.js App for free

18.envfile & Github actions

Environment variables in Node are used to store sensitive data.

2in app.jsrequire('dotenv').config()

Download files

19Deploying Node.js App for free

Download files

😡
انت مشغل الـ AdBlock !!

ياريت تقفله لوسمحت 😊 😊

تنبيه هام ✋

إذا كانت الإعلانات مزعجة بالنسبة لك، فيُمكنك التبرع ب50$ وسيتم إيقاف الإعلانات لمدة شهر لجميع زوار الموقع 🧡 ويُمكنك التواصل معنا عن طريق صفحة الفيس بوك