From f58d3a9dda6f3c9ab7181da459596302a3932907 Mon Sep 17 00:00:00 2001 From: RaviAnand Mohabir Date: Fri, 21 May 2021 13:14:11 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20`host`=20and=20`basePath`=20t?= =?UTF-8?q?o=20general=20config=20and=20improve=20recognition=20of=20route?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/auth.ts | 20 ++++++++++++++------ src/path.ts | 5 +++++ 2 files changed, 19 insertions(+), 6 deletions(-) create mode 100644 src/path.ts diff --git a/src/auth.ts b/src/auth.ts index 7f4ace2..b57e3aa 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -4,13 +4,16 @@ import type { Headers } from "@sveltejs/kit/types/helper"; import cookie from "cookie"; import * as jsonwebtoken from "jsonwebtoken"; import type { JWT, Session } from "./interfaces"; +import { join } from "./path"; import type { Provider } from "./providers"; interface AuthConfig { - providers?: Provider[]; + providers: Provider[]; callbacks?: AuthCallbacks; jwtSecret?: string; jwtExpiresIn?: string | number; + host?: string; + basePath?: string; } interface AuthCallbacks { @@ -61,8 +64,13 @@ export class Auth { return token; } - getBaseUrl(host: string) { - return `http://${host}`; + getBaseUrl(host?: string) { + return this.config?.host ?? `http://${host}`; + } + + getPath(path: string, host?: string) { + const uri = join([this.config?.basePath ?? "/api/auth", path]); + return new URL(uri, this.getBaseUrl(host)).pathname; } setToken(headers: Headers, newToken: JWT | any) { @@ -122,7 +130,7 @@ export class Auth { async handleEndpoint(request: ServerRequest): Promise { const { path, headers, method, host } = request; - if (path === "/api/auth/signout") { + if (path === this.getPath("signout")) { const token = this.setToken(headers, {}); const jwt = this.signToken(token); @@ -167,9 +175,9 @@ export class Auth { get: RequestHandler = async (request) => { const { path } = request; - if (path === "/api/auth/csrf") { + if (path === this.getPath("csrf")) { return { body: "1234" }; // TODO: Generate real token - } else if (path === "/api/auth/session") { + } else if (path === this.getPath("session")) { const session = await this.getSession(request); return { body: { diff --git a/src/path.ts b/src/path.ts new file mode 100644 index 0000000..83d5135 --- /dev/null +++ b/src/path.ts @@ -0,0 +1,5 @@ +export function join(parts: string[], sep = "/") { + const separator = sep || "/"; + const replace = new RegExp(separator + "{1,}", "g"); + return parts.join(separator).replace(replace, separator); +}