Skip to content

Commit

Permalink
Merge pull request #114 from dhamolahedonist/feat/15-modify-members
Browse files Browse the repository at this point in the history
fix: fixed the user permission middleware and and the merge conflict
  • Loading branch information
Idimmusix authored Jul 22, 2024
2 parents 118a8d1 + 64f95c6 commit 9c21012
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions src/middleware/checkUserRole.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,30 @@
import { Request, Response, NextFunction } from "express";
import { UserRole } from "../enums/userRoles";
import { Unauthorized } from "./error";
import { User } from "../models";
import AppDataSource from "../data-source";
import jwt from 'jsonwebtoken';


export const checkPermissions = (roles: UserRole[]) => {
return (req: Request, res: Response, next: NextFunction) => {
const user = req.user;
return async (req: Request & { user?: User }, res: Response, next: NextFunction) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
try {
const decodedToken = jwt.decode(token);
if (typeof decodedToken === 'string' || !decodedToken) {
return res.status(401).json({ status: 'error', message: 'Access denied. Invalid token' });
}
const userRepository = AppDataSource.getRepository(User);
const user = await userRepository.findOne({ where: { id: decodedToken.userId } });
console.log(user);
// if (user.role !== 'super_admin' )
if (!user || !roles.includes(user.role)) {
throw new Unauthorized("You do not have permission to perform this action");
return res.status(401).json({ status: 'error', message: 'Access denied. Not an admin' });
}
next();
};
};
} catch (error) {
res.status(401).json({ status: 'error', message: 'Access denied. Invalid token' });
}
}
}

0 comments on commit 9c21012

Please sign in to comment.