testing gateway

This commit is contained in:
2020-12-28 16:53:08 +01:00
parent 051c2bdbbd
commit a8fb92b367
3 changed files with 192 additions and 20 deletions

@ -37,7 +37,14 @@ class Authority {
};
const data = verify_signature_get_info (
key,
(info) => keystore.get_key (info.iat / 1000),
(info) => {
try {
return keystore.get_key (info.iat / 1000);
}
catch {
return '';
}
},
(info) => info.valid_for * 1000
);

@ -5,11 +5,15 @@
* Created by Timo Hocker <timo@scode.ovh>, December 2020
*/
import { IncomingMessage, ServerResponse } from 'http';
import { run_regex } from '@sapphirecode/utilities';
import authority from './Authority';
type AnyFunc = (...args: unknown) => unknown;
type Gateway = (req: Request, res: Response, next: AnyFunc) => Promise<void>;
type AnyFunc = (...args: unknown[]) => unknown;
type Gateway = (
req: IncomingMessage,
res: ServerResponse, next: AnyFunc
) => unknown;
interface GatewayOptions {
redirect_url: string;
@ -23,38 +27,38 @@ class GatewayClass {
this._options = options;
}
private redirect (res): void {
private redirect (res: ServerResponse): void {
res.statusCode = 302;
res.setHeader ('Location', this._options.redirect_url);
res.end ();
}
private get_header_auth (req: Request): string | null {
const auth_header = req.headers.get ('Authorization');
const auth = (/(?<type>\w)+ (?<data>.*)/u).exec (auth_header);
private get_header_auth (req: IncomingMessage): string | null {
const auth_header = req.headers.authorization;
const auth = (/(?<type>\w+) (?<data>.*)/u).exec (auth_header || '');
if (auth === null)
return null;
if (auth.groups.type !== 'Bearer')
if (auth.groups?.type !== 'Bearer')
return null;
return auth.groups.data;
return auth.groups?.data;
}
private get_cookie_auth (req: Request): string | null {
private get_cookie_auth (req: IncomingMessage): string | null {
if (typeof this._options.cookie_name === 'undefined')
return null;
let auth = null;
run_regex (
/[\^;](?<name>[^;=]+)=(?<value>[^;]+)/gu,
req.headers.get ('cookie'),
(res) => {
if (res.groups.name === this._options.cookie_name)
auth = res.groups.value;
/(?:^|;)(?<name>[^;=]+)=(?<value>[^;]+)/gu,
req.headers.cookie,
(res: RegExpMatchArray) => {
if (res.groups?.name === this._options.cookie_name)
auth = res.groups?.value;
}
);
return auth;
}
private authenticate (req: Request): Promise<boolean> {
private authenticate (req: IncomingMessage): boolean {
let auth = this.get_header_auth (req);
if (auth === null)
auth = this.get_cookie_auth (req);
@ -65,10 +69,10 @@ class GatewayClass {
}
public process_request (
req: Request,
res: Response,
req: IncomingMessage,
res: ServerResponse,
next: AnyFunc
): Promise<void> {
): unknown {
if (this.authenticate (req))
return next ();
return this.redirect (res);
@ -77,5 +81,7 @@ class GatewayClass {
export default function create_gateway (options: GatewayOptions): Gateway {
const g = new GatewayClass (options);
return g.process_request;
return g.process_request.bind (g);
}
export { Gateway, AnyFunc };