Advertisement
NaroxEG

middleware

May 23rd, 2024
689
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const jwt = require('jsonwebtoken');
  2. require('dotenv').config()
  3. const SECRET = process.env.SECRET;
  4.  
  5. function verifyToken(req, res, next) {
  6.     const token = req.cookies.jwt;
  7.     if (!token) return res.redirect("/api/v1/user/login");
  8.     try {
  9.         const decoded = jwt.verify(token, SECRET);
  10.         req.userId = decoded.userId;
  11.         next();
  12.     } catch (error) {
  13.         return res.redirect("/api/v1/user/login");
  14.     }
  15. };
  16.  
  17. function verifyAdminToken(req, res, next) {
  18.     const token = req.cookies.jwt;
  19.     if (!token) return res.redirect("/api/v1/user/login");
  20.     try {
  21.         const decoded = jwt.verify(token, SECRET);
  22.         req.userId = decoded.userId;
  23.         if (decoded.isAdmin) {
  24.             next();
  25.         } else {
  26.             return res.status(403).json({ message: 'Unauthorized: Access restricted to admins' });
  27.         }
  28.     } catch (error) {
  29.         return res.redirect("/api/v1/user/login");
  30.     }
  31. };
  32.  
  33.  
  34. module.exports = { verifyToken, verifyAdminToken };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement