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); +}