Skip to content

Commit bd0fe25

Browse files
committed
Updates to common package
1 parent 36b32eb commit bd0fe25

5 files changed

Lines changed: 184 additions & 6 deletions

File tree

examples_new/microservices/common/package-lock.json

Lines changed: 138 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples_new/microservices/common/package.json

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,11 @@
1616
"author": "",
1717
"license": "ISC",
1818
"dependencies": {
19-
"express": "^4.18.2"
19+
"express": "^4.18.2",
20+
"jsonwebtoken": "^9.0.2"
2021
},
2122
"devDependencies": {
22-
"@types/express": "^4.17.21"
23+
"@types/express": "^4.17.21",
24+
"@types/jsonwebtoken": "^9.0.5"
2325
}
2426
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export enum Events {
2+
USER_CREATED = 'USER_CREATED',
3+
ITEM_CREATED = 'ITEM_CREATED',
4+
ORDER_CREATED = 'ORDER_CREATED',
5+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { NextFunction, Request, Response } from 'express';
2+
import jwt, { JwtPayload } from 'jsonwebtoken';
3+
4+
interface UserPayload extends JwtPayload {
5+
userId: string;
6+
}
7+
8+
export interface CurrentUserRequest extends Request {
9+
currentUser?: string;
10+
}
11+
//middleware to check if there is a cookie
12+
// if there is a cookie, we decode jwt and attach the current user id
13+
export const currentUser = (req: CurrentUserRequest, res: Response, next: NextFunction) => {
14+
const { token } = req.cookies;
15+
16+
if (!token) return next();
17+
18+
19+
try {
20+
const payload = jwt.verify(token, process.env.JWT_KEY!) as UserPayload;
21+
req.currentUser = payload.userId;
22+
return next()
23+
} catch (err) {
24+
throw new Error('🎃Internal Error');
25+
}
26+
};
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { CurrentUserRequest } from './currentUser';
2+
import { NotAuthorizedError } from '../errors/not-authorized-error';
3+
import { NextFunction, Response } from 'express';
4+
// take in req, res and next as arguments - include their types from express package
5+
export const requireAuth = (req: CurrentUserRequest, res: Response, next: NextFunction) => {
6+
// check if req.currentUser exists
7+
// if it does, move onto to the next middleware
8+
if (req.currentUser) return next();
9+
// if not throw a not authorized error
10+
throw new NotAuthorizedError();
11+
};

0 commit comments

Comments
 (0)