Skip to content

Commit e1b64fa

Browse files
committed
Add authorization
1 parent 5424214 commit e1b64fa

3 files changed

Lines changed: 49 additions & 1 deletion

File tree

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414
"dependencies": {
1515
"aws-sdk": "^2.801.0",
1616
"express": "^4.17.1",
17+
"jsonwebtoken": "^8.5.1",
1718
"@types/express": "^4.17.9",
19+
"@types/jsonwebtoken": "^8.5.0",
1820
"@types/node": "^10.15.3",
1921
"prettier": "^2.2.1",
2022
"typescript": "^4.1.2"

src/authorize.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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 };

src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import express from 'express';
2+
import { authorize } from './authorize';
23
import { getImage } from './images';
34

45
const app = express();
56
const PORT = 8123;
67

7-
app.get('/cat/:catName', async (req, res) => {
8+
app.get('/cat/:catName', authorize, async (req, res) => {
89
const catUrl = await getImage(req.params.catName);
910
if (!catUrl) {
1011
return res.status(404);

0 commit comments

Comments
 (0)