fix(striker-ui-api): allow override fail/succeed in assert authentication

main
Tsu-ba-me 2 years ago
parent 0f223950e4
commit feae630370
  1. 62
      striker-ui-api/src/lib/assertAuthentication.ts

@ -1,38 +1,54 @@
import { Handler, Request, Response } from 'express'; import { Handler } from 'express';
import { stdout } from './shell'; import { stdout } from './shell';
export const assertAuthentication: (options?: { type AssertAuthenticationOptions = {
failureRedirect?: string; fail?: string | ((...args: Parameters<Handler>) => void);
failureReturnTo?: boolean | string; failReturnTo?: boolean | string;
}) => Handler = ({ failureRedirect, failureReturnTo } = {}) => { succeed?: string | ((...args: Parameters<Handler>) => void);
const redirectOnFailure: (response: Response) => void = failureRedirect };
? (response) => response.redirect(failureRedirect)
: (response) => response.status(404).send();
let getSessionReturnTo: ((request: Request) => string) | undefined;
if (failureReturnTo === true) { type AssertAuthenticationFunction = (
getSessionReturnTo = ({ originalUrl, url }) => originalUrl || url; options?: AssertAuthenticationOptions,
} else if (typeof failureReturnTo === 'string') { ) => Handler;
getSessionReturnTo = () => failureReturnTo;
export const assertAuthentication: AssertAuthenticationFunction = ({
fail: initFail = (request, response) => response.status(404).send(),
failReturnTo,
succeed: initSucceed = (request, response, next) => next(),
}: AssertAuthenticationOptions = {}) => {
const fail: (...args: Parameters<Handler>) => void =
typeof initFail === 'string'
? (request, response) => response.redirect(initFail)
: initFail;
const succeed: (...args: Parameters<Handler>) => void =
typeof initSucceed === 'string'
? (request, response) => response.redirect(initSucceed)
: initSucceed;
let getReturnTo: ((...args: Parameters<Handler>) => string) | undefined;
if (failReturnTo === true) {
getReturnTo = ({ originalUrl, url }) => originalUrl || url;
} else if (typeof failReturnTo === 'string') {
getReturnTo = () => failReturnTo;
} }
return (request, response, next) => { return (...args) => {
const { 0: request } = args;
const { originalUrl, session } = request; const { originalUrl, session } = request;
const { passport } = session; const { passport } = session;
if (!passport?.user) { if (passport?.user) return succeed(...args);
session.returnTo = getSessionReturnTo?.call(null, request);
stdout( session.returnTo = getReturnTo?.call(null, ...args);
`Unauthenticated access to ${originalUrl}; set return to ${session.returnTo}`,
);
return redirectOnFailure?.call(null, response); stdout(
} `Unauthenticated access to ${originalUrl}; set return to ${session.returnTo}`,
);
next(); return fail(...args);
}; };
}; };

Loading…
Cancel
Save