|
| 1 | +const { DynamoDB } = require('aws-sdk'); |
| 2 | + |
| 3 | +import { Request, Response, NextFunction } from 'express'; |
| 4 | + |
| 5 | +import jwt from 'jsonwebtoken'; |
| 6 | + |
| 7 | +const ddb = new DynamoDB(); |
| 8 | + |
| 9 | +const getUserPerms = async (user: any): Promise<string[]> => { |
| 10 | + const result = await ddb.scan({TableName:'users' }) .promise(); |
| 11 | + return result.Items?result.Items.map((e: any) => e.userPermissions.S as string) : []; |
| 12 | +}; |
| 13 | + |
| 14 | +const authenticateUser = async(token: any): Promise<string> => { |
| 15 | + const parsed = jwt.decode(token); |
| 16 | + if (!parsed) |
| 17 | + throw new Error('Unauthorized'); |
| 18 | + |
| 19 | + return parsed.sub; |
| 20 | +}; |
| 21 | + |
| 22 | +// Validate that there's a permission 'catName:1' in the permissions for the user. |
| 23 | +const testPerm = async (perm: any, catName: any): Promise<any> =>{ |
| 24 | + return [...perm.matchAll(`/(${catName}):(\d)/g`)].map((e) => e[2]).filter((p) => p > 0).length > 0; |
| 25 | +}; |
| 26 | + |
| 27 | +const authorize = async (req: Request, res: Response, next: NextFunction) => { |
| 28 | + var authHeader = req.headers['authentication']; |
| 29 | + if (!authHeader) { |
| 30 | + return res.status(404); |
| 31 | + } |
| 32 | + |
| 33 | + var token = authenticateUser(authHeader as string); |
| 34 | + if (!token) { return res.status(404); } |
| 35 | + |
| 36 | + var perms = await getUserPerms(req.params.user); |
| 37 | + for (var i = 0; i < perms.length; i++) { |
| 38 | + if (testPerm(perms[i], req.params.catName)) |
| 39 | + return next(); |
| 40 | + } |
| 41 | + |
| 42 | + return res.status(404); |
| 43 | +}; |
| 44 | + |
| 45 | +export { authorize }; |
0 commit comments