Add host and basePath to general config and improve recognition of routes

This commit is contained in:
RaviAnand Mohabir 2021-05-21 13:14:11 +02:00
parent 9a48661d10
commit f58d3a9dda
2 changed files with 19 additions and 6 deletions

View File

@ -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<EndpointOutput> {
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: {

5
src/path.ts Normal file
View File

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