This repository has been archived by the owner on May 6, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
37 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,29 +1,52 @@ | ||
import { Request, Response, NextFunction } from "express" | ||
import jwt from "jsonwebtoken"; | ||
import { JWT_Access_Token } from "../Config"; | ||
import Logger from "../Lib/Logger"; | ||
import { APIError } from "../Lib/Response"; | ||
|
||
export default function EnsureAuth() | ||
{ | ||
return (req: Request, res: Response, next: NextFunction) => | ||
{ | ||
const authHeader = req.headers['authorization']; | ||
const token = authHeader; | ||
if (token == null) | ||
return APIError(`Missing token in headers.`, 401)(res); | ||
if(!authHeader) | ||
return APIError({ | ||
text: "Missing 'authorization' in header" | ||
})(res); | ||
|
||
jwt.verify(token, JWT_Access_Token, (err, payload) => | ||
{ | ||
if (err) | ||
return APIError(`Unauthorized user.`, 403)(res); | ||
|
||
if(!payload?.data?.id) | ||
return APIError(`Wrong payload.`, 403)(res); | ||
const b64auth = (authHeader).split(' '); | ||
|
||
if(!b64auth[0].toLocaleLowerCase().match(/basic|bearer/g)) | ||
return APIError({ | ||
text: "Missing 'basic' or 'bearer' in authorization" | ||
})(res); | ||
|
||
if(!b64auth[1]) | ||
return APIError({ | ||
text: "Missing 'buffer' in authorization" | ||
})(res); | ||
|
||
//@ts-ignore | ||
req.customer = payload.data; | ||
if(b64auth[0].toLocaleLowerCase() === "bearer") | ||
{ | ||
const token = (Buffer.isBuffer(b64auth[1]) ? Buffer.from(b64auth[1], 'base64') : b64auth[1]).toString(); | ||
jwt.verify(token, JWT_Access_Token, (err, payload) => | ||
{ | ||
console.log(err); | ||
if (err) | ||
return APIError(`Unauthorized user.`, 403)(res); | ||
|
||
if(!payload?.data?.id) | ||
return APIError(`Wrong payload.`, 403)(res); | ||
|
||
//@ts-ignore | ||
req.customer = payload.data; | ||
|
||
Logger.api(`Authorizing`, payload.data); | ||
|
||
return next(); | ||
}); | ||
} | ||
|
||
|
||
return next(); | ||
}); | ||
} | ||
} |