fix(striker-ui-api): add assert authentication

main
Tsu-ba-me 2 years ago
parent 4a1cc577b5
commit 193727b93f
  1. 8
      striker-ui-api/src/app.ts
  2. 37
      striker-ui-api/src/lib/assertAuthentication.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' });

@ -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();
};
};
Loading…
Cancel
Save