Wolkendama-API / Controller / authController.js
authController.js
Raw
const jwt = require("jsonwebtoken");

const User = require("../Model/userModel");
const catchAsync = require("../utils/catchAsync");
const AppError = require("../utils/appError");

exports.protect = catchAsync(async (req, res, next) => {
  // 1) Getting token and check of if it's there
  let token;

  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    token = req.headers.authorization.split(" ")[1];
  } else if (req.cookies.Woladmin) {
    token = req.cookies.Woladmin;
  }

  if (!token) {
    return res.status(400).json({
      status: "error",
      data: `Please login to gain access!`,
    });
  }

  const decoded = jwt.verify(token, process.env.JWT_SECRET);

  // Check if there is an User related to the token
  const currentUser = await User.findById(decoded.user.id);

  if (!currentUser) {
    return next(new AppError("No user found, please try again", 400));
  }

  next();
});