-
Notifications
You must be signed in to change notification settings - Fork 84
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #114 from dhamolahedonist/feat/15-modify-members
fix: fixed the user permission middleware and and the merge conflict
- Loading branch information
Showing
1 changed file
with
21 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' }); | ||
} | ||
} | ||
} |