All files / src/auth adminAuth.js

80% Statements 12/15
83.33% Branches 5/6
100% Functions 1/1
78.57% Lines 11/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23        79x 79x 79x 79x 78x 78x 78x 75x 3x 3x             1x    
import extractAuthFromRequestHeaders from "../utilities/extractAuthFromRequestHeaders.js";
import { verifyJWT } from "../utilities/jwtUtilities.js";
 
export default async function adminAuth(req, res, next) {
    const unAuthorizedMsg = { message: "You need some credentials first to access this api" };
    const failedToAuthorizeMsg = { message: "Invalid credentials!, Failed to authorize you" };
    const { accessToken } = extractAuthFromRequestHeaders(req)
    if (accessToken) {
        try {
            const token = verifyJWT(accessToken)
            if (token.role === "admin") {
                req.adminId = token.adminId; next();
            } else if (token.role === "user") {
                res.status(401).json({ message: "You are not admin" });
            }
            else Eres.status(401).json(failedToAuthorizeMsg);
        } catch (error) {
            console.log(error)
            res.status(401).json(failedToAuthorizeMsg);
        }
    } else return res.status(401).json(unAuthorizedMsg)
};