Skip to content
This repository has been archived by the owner on May 6, 2022. It is now read-only.

Commit

Permalink
Fixed EnsureAuth
Browse files Browse the repository at this point in the history
  • Loading branch information
Tolfx committed Nov 27, 2021
1 parent 6531f54 commit 14abb5f
Showing 1 changed file with 37 additions and 14 deletions.
51 changes: 37 additions & 14 deletions src/Middlewares/EnsureAuth.ts
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();
});
}
}

0 comments on commit 14abb5f

Please sign in to comment.