auth-server-helper/lib/Gateway.ts

82 lines
2.1 KiB
TypeScript
Raw Normal View History

/*
* Copyright (C) Sapphirecode - All Rights Reserved
* This file is part of Auth-Server-Helper which is released under MIT.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, December 2020
*/
2020-12-13 12:26:40 +01:00
import { run_regex } from '@sapphirecode/utilities';
2020-12-19 15:40:49 +01:00
import authority from './Authority';
2020-12-12 15:53:47 +01:00
2020-12-06 15:51:59 +01:00
type AnyFunc = (...args: unknown) => unknown;
type Gateway = (req: Request, res: Response, next: AnyFunc) => Promise<void>;
interface GatewayOptions {
redirect_url: string;
2020-12-13 12:26:40 +01:00
cookie_name?: string;
2020-12-06 15:51:59 +01:00
}
class GatewayClass {
2020-12-06 21:06:40 +01:00
private _options: GatewayOptions;
2020-12-06 15:51:59 +01:00
public constructor (options: GatewayOptions) {
2020-12-06 21:06:40 +01:00
this._options = options;
2020-12-06 15:51:59 +01:00
}
private redirect (res): void {
res.statusCode = 302;
2020-12-06 21:06:40 +01:00
res.setHeader ('Location', this._options.redirect_url);
2020-12-06 15:51:59 +01:00
res.end ();
}
2020-12-13 12:26:40 +01:00
private get_header_auth (req: Request): string | null {
const auth_header = req.headers.get ('Authorization');
const auth = (/(?<type>\w)+ (?<data>.*)/u).exec (auth_header);
if (auth === null)
return null;
if (auth.groups.type !== 'Bearer')
return null;
return auth.groups.data;
}
private get_cookie_auth (req: Request): string | null {
if (typeof this._options.cookie_name === 'undefined')
return null;
2020-12-13 12:26:40 +01:00
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;
}
);
return auth;
}
2020-12-12 15:53:47 +01:00
private authenticate (req: Request): Promise<boolean> {
2020-12-13 12:26:40 +01:00
let auth = this.get_header_auth (req);
if (auth === null)
auth = this.get_cookie_auth (req);
if (auth === null)
2020-12-12 15:53:47 +01:00
return false;
2020-12-19 15:40:49 +01:00
return authority.verify (auth).authorized;
2020-12-06 15:51:59 +01:00
}
2020-12-12 15:53:47 +01:00
public process_request (
2020-12-06 21:06:40 +01:00
req: Request,
res: Response,
next: AnyFunc
): Promise<void> {
2020-12-12 15:53:47 +01:00
if (this.authenticate (req))
2020-12-06 21:06:40 +01:00
return next ();
return this.redirect (res);
2020-12-06 15:51:59 +01:00
}
}
export default function create_gateway (options: GatewayOptions): Gateway {
const g = new GatewayClass (options);
return g.process_request;
}