feat: add functional authentication
This commit is contained in:
@@ -1,16 +1,41 @@
|
||||
import { RouteContext } from "@spec/relay";
|
||||
import { ServerContext, UnauthorizedError } from "@spec/relay";
|
||||
|
||||
export function getRequestContext(request: Request): RouteContext {
|
||||
return {
|
||||
request,
|
||||
};
|
||||
}
|
||||
import { Session } from "../auth/auth.ts";
|
||||
import { req } from "./request.ts";
|
||||
|
||||
declare module "@spec/relay" {
|
||||
interface RouteContext {
|
||||
interface ServerContext {
|
||||
/**
|
||||
* Current request instance being handled.
|
||||
*/
|
||||
request: Request;
|
||||
|
||||
/**
|
||||
* Get request session instance.
|
||||
*/
|
||||
session: Session;
|
||||
|
||||
/**
|
||||
* Get account id from session, throws an error if the request
|
||||
* does not have a valid session.
|
||||
*/
|
||||
accountId: string;
|
||||
}
|
||||
}
|
||||
|
||||
export function getRequestContext(request: Request): ServerContext {
|
||||
return {
|
||||
request,
|
||||
|
||||
get session(): Session {
|
||||
if (req.session === undefined) {
|
||||
throw new UnauthorizedError();
|
||||
}
|
||||
return req.session;
|
||||
},
|
||||
|
||||
get accountId() {
|
||||
return this.session.accountId;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import { Route } from "@spec/relay";
|
||||
export async function resolveRoutes(path: string, routes: Route[] = []): Promise<Route[]> {
|
||||
for await (const entry of Deno.readDir(path)) {
|
||||
if (entry.isDirectory === true) {
|
||||
await loadRoutes(`${path}/${entry.name}/routes`, routes, [name]);
|
||||
await loadRoutes(`${path}/${entry.name}`, routes, [name]);
|
||||
}
|
||||
}
|
||||
return routes;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Session } from "../auth/auth.ts";
|
||||
import { asyncLocalStorage } from "./storage.ts";
|
||||
|
||||
export const req = {
|
||||
@@ -24,14 +25,14 @@ export const req = {
|
||||
/**
|
||||
* Check if the request is authenticated.
|
||||
*/
|
||||
get isAuthenticated() {
|
||||
get isAuthenticated(): boolean {
|
||||
return this.session !== undefined;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get current session.
|
||||
*/
|
||||
get session() {
|
||||
get session(): Session | undefined {
|
||||
return this.store.session;
|
||||
},
|
||||
|
||||
|
||||
Reference in New Issue
Block a user