SIGNUP

const { validationResult } = require("express-validator/check")
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken")

exports.signup = (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        const error = new Error("validation failed")
        error.statusCode = 422;
        error.data = errors.array()
        throw error;
    }
    const email = req.body.email;
    const name = req.body.name;
    const password = req.body.password;
    bcrypt.hash(password, 12)
        .then(hashedPassword => {
            const user = new User({
                email: email,
                password: hashedPassword,
                name: name
            })
            return user.save()
        })
        .then(result => {
            res.status(201).json({
                message: "User created",
                userId: result._id
            })
        })
        .catch(err => {
            if (!err.statusCode) {
                err.statusCode = 500;
            }
            next(err);
        })
}

VALIDATING USER SIGNUP

const { body } = require("express-validator/check");

router.put('/signup', [
    body("email")
        .isEmail()
        .trim()
        .withMessage("Please enter a valid email")
        .custom((value, { req }) => {
            return User.findOne({ email: value })
                .then(userDoc => {
                    if (userDoc) {
                        return Promise.reject(
                            'E-Mail exists already, please pick a different one.'
                        );
                    }
                })
        })
        .normalizeEmail(),
    body("password")
        .trim()
        .isLength({ min: 5 })
        .withMessage("Please enter a longer password"),
    body("name")
        .trim()
        .not()
        .isEmpty()
        .withMessage("Please enter a name")
], authController.signup);

// ENCORE PLUS SIMPLE POUR LA VALIDATION : 
// verifier si l'email est deja utilisé !
npm i --save mongoose-unique-validator

const uniqueValidator = require("mongoose-unique-validator");
userSchema.plugin(uniqueValidator)

ENCRYPT PASSWORD

npm i --save bcryptjs
... 
// create the user
//bcrypt hash returns a promise !
        return bcrypt.hash(password, 12)
        .then((hashedPassword) => {
            const user = new User({
                email: email,
                password: hashedPassword,
                cart: {
                    items: []
                }
            })
            return user.save()
        })
        .then(() => {
            console.log("user created!")
            res.redirect("/")
        })

SIGN IN

exports.login = (req, res, next) => {
    const email = req.body.email;
    const password = req.body.password;
    let loadedUser;
    User.findOne({ email: email })
        .then(user => {
            if (!user) {
                const error = new Error("Invalid email or password")
                error.statusCode = 401;
                throw error;
            }
            loadedUser = user;
            return bcrypt.compare(password, user.password)
        })
        .then(isEqual => {
            if (!isEqual) {
                const error = new Error("Invalid email or password")
                error.statusCode = 401;
                throw error;
            }
            const token = jwt.sign({
                email: loadedUser.email,
                userId: loadedUser._id.toString()
            }, 'weareallsatoshi', { expiresIn: '1h' })
            res.status(200).json({
                token: token,
                userId: loadedUser._id.toString()
            })
        })
        .catch(err => {
            if (!err.statusCode) {
                err.statusCode = 500;
            }
            next(err);
        })
}

ROUTE PROTECTION

Facon de faire plutot simple :

exports.getAddProduct = (req, res, next) => {
  if (!req.session.isLoggedIn) {
    // not loggedin
    return res.redirect("/login")
  }

Ca fonctionne, enfin bon si on a 50 routes ca va être pénible.. Nous allons donc creer un nouveau dossier a la racine du projet avec un fichier qu'on appellera 'is-auth.js'

module.exports = (req, res, next) => {
    if (!req.session.isLoggedIn) {
        return res.redirect("/login")
    }
    next();
}

On va ensuite l'utiliser dans notre dossier routes

const isAuth = require("./../middleware/is-auth");

// /admin/add-product => GET
// ici on chain notre middleware, bien faire attention à l'ordre !
router.get('/add-product', isAuth, adminController.getAddProduct);

Pour éviter ce genre d'attaque nous allons utiliser un CSRF token