Created
November 5, 2022 18:32
-
-
Save zawie/b574e439577203baf6810c966df6cf06 to your computer and use it in GitHub Desktop.
Middleware that uses the authentication handler
This file contains hidden or 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
import { NextFunction, Request, Response, RequestHandler } from 'express'; | |
import HttpException from '../model/HttpException' | |
import { isAuthorized } from '../utils/auth-utils' | |
import { aliasExists } from '../accessor/database.mongo' | |
export function authorizationMiddleware(): RequestHandler { | |
return async ( | |
request: Request, | |
response: Response, | |
next: NextFunction) => { | |
// Check if user is even signed in. | |
if (!request.cookies.jwt) { | |
next(new HttpException(401, "Authentication required")) | |
} | |
// Get necessary alias from user param. | |
const user = request.params.user | |
// Check if user even exists. | |
if (!aliasExists(user)) { | |
next(new HttpException(404, `User "${user}" not found.`)) | |
} | |
// Authenticate request. | |
const isAuth = await isAuthorized(request, user) | |
console.assert(isAuth, `User "${user}" is unauthorized!`) | |
if (!isAuth) { | |
next(new HttpException(403, "Forbidden request")) | |
} else { | |
console.log(`User "${user}" is authorized!`) | |
next() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment