auth.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import User from "./models/User.js";
  2. import {HttpError, catchError} from "./HttpError.js";
  3. import jwt from "jsonwebtoken";
  4. const userAuth = async (req, res, next)=>{
  5. try{
  6. const userData = jwt.verify(req.signedCookies.userToken, process.env.JWT_SECRET);
  7. const user = await User.findOne({_id: userData.id});
  8. if(!user || user.uuid !== userData.token){
  9. throw new HttpError(401, "Unauthorized");
  10. }
  11. res.locals.user = user;
  12. next();
  13. }catch(e){
  14. if(e.message === "Cannot read properties of undefined (reading 'split')"){
  15. const error = new HttpError(400, "Must provide authorization token");
  16. catchError(error, req, res, next);
  17. return;
  18. }
  19. if(e.message === "jwt malformed"){
  20. const error = new HttpError(400, "Invalid JWT");
  21. catchError(error, req, res, next);
  22. return;
  23. }
  24. if(e.message === "jwt must be provided"){
  25. const error = new HttpError(400, "No auth");
  26. catchError(error, req, res, next);
  27. return;
  28. }
  29. catchError(e, req, res, next);
  30. }
  31. }
  32. export {userAuth}