|
| 1 | +import { Request, Response, NextFunction } from "express"; |
| 2 | +import { verify } from "jsonwebtoken"; |
| 3 | +import { User } from "../model/User"; |
| 4 | + |
| 5 | +const adminAuthValidation = async ( |
| 6 | + req: Request, |
| 7 | + res: Response, |
| 8 | + next: NextFunction |
| 9 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 10 | +): Promise<Response<any, Record<string, any>> | void> => { |
| 11 | + try { |
| 12 | + const accessToken = req.headers.authorization?.split(" ")[1]; |
| 13 | + if (!accessToken) { |
| 14 | + return res.json({ done: false, err: "No token" }); |
| 15 | + } |
| 16 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 17 | + const payload: any = verify(accessToken, process.env.JWT_SECRET!); |
| 18 | + |
| 19 | + if (!payload) { |
| 20 | + return res.json({ done: false, err: "Bad token" }); |
| 21 | + } |
| 22 | + |
| 23 | + // Check if clubs present in request |
| 24 | + const club = req.body.club; |
| 25 | + if (!club) { |
| 26 | + return res.json({ done: false, err: "Invalid request" }); |
| 27 | + } |
| 28 | + |
| 29 | + const user = await User.findOne({ _id: payload.userId }); |
| 30 | + if (!user) { |
| 31 | + return res.json({ done: false, err: "Invalid token" }); |
| 32 | + } |
| 33 | + const clubAuth = user?.clubs?.find((e) => e.name === club)?.authority; |
| 34 | + if (!clubAuth && clubAuth !== "admin") { |
| 35 | + console.log(JSON.stringify(user.clubs)); |
| 36 | + return res.json({ done: false, err: "Permission denied" }); |
| 37 | + } |
| 38 | + |
| 39 | + next(); |
| 40 | + } catch (err) { |
| 41 | + console.log("my error: " + err); |
| 42 | + return res.json({ done: false, err: "Something went wrong" }); |
| 43 | + } |
| 44 | +}; |
| 45 | + |
| 46 | +export default adminAuthValidation; |
0 commit comments