-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
60 lines (47 loc) · 1.58 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { configDotenv } from "dotenv";
import { Response } from "express";
import jwt from "jsonwebtoken";
import { RequestModel } from "./src/models/request.model";
configDotenv()
export function checkIfDefined(data: any){
if(!data) throw new Error("NOT_FOUND")
else{
delete data.deletedAt
return data;
}
}
export async function authenticateToken(req : RequestModel, res: Response, next: Function) {
const unprotected = [
"/api/admin/login",
"/api/admin/refresh",
]
if(req.path.startsWith("/api/movie") || req.path.startsWith("/api/projection") || req.path.startsWith("/api/hall")){
unprotected.push(req.path);
}
if(unprotected.includes(req.path)){ next(); return }
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (token == null) {
return sendErrorResponse(res, 401, 'NO_TOKEN')
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET as string, (err: any, decoded: any) => {
if (err) {
return sendErrorResponse(res, 403, 'INVALID_TOKEN')
}
req.username = decoded.username
next()
})
}
export function sendErrorResponse(res: Response,code = 400, msg= "Bad request"){
res.status(code).json({
message: msg,
timestamp: new Date()
})
}
export function checkIfModelHasData(model: any,...requiredArguments: string[]){
requiredArguments.forEach(attribute => {
if(!model[attribute]){
throw new Error(`Error ! Missing ${attribute} field`)
}
})
}