From 193727b93f3d30f4ac82df3613f4a7d9ed01c15e Mon Sep 17 00:00:00 2001 From: Tsu-ba-me Date: Tue, 18 Apr 2023 17:08:23 -0400 Subject: [PATCH] fix(striker-ui-api): add assert authentication --- striker-ui-api/src/app.ts | 8 +++- .../src/lib/assertAuthentication.ts | 37 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 striker-ui-api/src/lib/assertAuthentication.ts diff --git a/striker-ui-api/src/app.ts b/striker-ui-api/src/app.ts index 8ae7df14..feea2742 100644 --- a/striker-ui-api/src/app.ts +++ b/striker-ui-api/src/app.ts @@ -1,6 +1,7 @@ import cors from 'cors'; import express, { json } from 'express'; +import { assertAuthentication } from './lib/assertAuthentication'; import passport from './passport'; import routes from './routes'; import { rrouters } from './lib/rrouters'; @@ -19,7 +20,12 @@ app.use(sessionHandler); app.use(passport.initialize()); app.use(passport.authenticate('session')); -rrouters(app, routes, { key: 'api' }); +const authenticationHandler = assertAuthentication(); + +rrouters(app, routes, { + assign: (router) => [authenticationHandler, router], + key: 'api', +}); rrouters(app, routes, { key: 'auth' }); rrouters(app, routes, { key: 'echo' }); diff --git a/striker-ui-api/src/lib/assertAuthentication.ts b/striker-ui-api/src/lib/assertAuthentication.ts new file mode 100644 index 00000000..a49d7889 --- /dev/null +++ b/striker-ui-api/src/lib/assertAuthentication.ts @@ -0,0 +1,37 @@ +import { Handler, Request, Response } from 'express'; + +import { stdout } from './shell'; + +export const assertAuthentication: (options?: { + failureRedirect?: string; + failureReturnTo?: boolean | string; +}) => Handler = ({ failureRedirect, failureReturnTo } = {}) => { + const redirectOnFailure: (response: Response) => void = failureRedirect + ? (response) => response.redirect(failureRedirect) + : (response) => response.status(404).send(); + + let getSessionReturnTo: ((request: Request) => string) | undefined; + + if (failureReturnTo === true) { + getSessionReturnTo = ({ originalUrl, url }) => originalUrl || url; + } else if (typeof failureReturnTo === 'string') { + getSessionReturnTo = () => failureReturnTo; + } + + return (request, response, next) => { + const { originalUrl, session } = request; + const { passport } = session; + + if (!passport?.user) { + session.returnTo = getSessionReturnTo?.call(null, request); + + stdout( + `Unauthenticated access to ${originalUrl}; set return to ${session.returnTo}`, + ); + + return redirectOnFailure?.call(null, response); + } + + next(); + }; +};