auth.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  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. console.log(userData);
  8. const user = await User.findOne({_id: userData.id});
  9. if(!user || user.uuid !== userData.token){
  10. throw new HttpError(401, "Unauthorized");
  11. }
  12. res.locals.user = user;
  13. next();
  14. }catch(e){
  15. if(e.message === "Cannot read properties of undefined (reading 'split')"){
  16. const error = new CustomError(400, "Must provide authorization token");
  17. catchError(error, req, res, next);
  18. return;
  19. }
  20. if(e.message === "jwt malformed"){
  21. const error = new CustomError(400, "Invalid JWT");
  22. catchError(error, req, res, next);
  23. return;
  24. }
  25. catchError(e, req, res, next);
  26. }
  27. }
  28. export {userAuth}