mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-16 04:27:21 +00:00
refactor: extracted auth as middleware to be added manually to endpoints
This commit is contained in:
@@ -1,42 +1,17 @@
|
||||
import type { AppAuth } from "auth";
|
||||
import { type ClassController, isDebug } from "core";
|
||||
import { Hono, type MiddlewareHandler } from "hono";
|
||||
import { Controller } from "modules/Controller";
|
||||
|
||||
export class AuthController implements ClassController {
|
||||
constructor(private auth: AppAuth) {}
|
||||
export class AuthController extends Controller {
|
||||
constructor(private auth: AppAuth) {
|
||||
super();
|
||||
}
|
||||
|
||||
get guard() {
|
||||
return this.auth.ctx.guard;
|
||||
}
|
||||
|
||||
getMiddleware: MiddlewareHandler = async (c, next) => {
|
||||
// @todo: ONLY HOTFIX
|
||||
// middlewares are added for all routes are registered. But we need to make sure that
|
||||
// only HTML/JSON routes are adding a cookie to the response. Config updates might
|
||||
// also use an extension "syntax", e.g. /api/system/patch/data/entities.posts
|
||||
// This middleware should be extracted and added by each Controller individually,
|
||||
// but it requires access to the auth secret.
|
||||
// Note: This doesn't mean endpoints aren't protected, just the cookie is not set.
|
||||
const url = new URL(c.req.url);
|
||||
const last = url.pathname.split("/")?.pop();
|
||||
const ext = last?.includes(".") ? last.split(".")?.pop() : undefined;
|
||||
if (
|
||||
!this.auth.authenticator.isJsonRequest(c) &&
|
||||
["GET", "HEAD", "OPTIONS"].includes(c.req.method) &&
|
||||
ext &&
|
||||
["js", "css", "png", "jpg", "jpeg", "svg", "ico"].includes(ext)
|
||||
) {
|
||||
isDebug() && console.log("Skipping auth", { ext }, url.pathname);
|
||||
} else {
|
||||
const user = await this.auth.authenticator.resolveAuthFromRequest(c);
|
||||
this.auth.ctx.guard.setUserContext(user);
|
||||
}
|
||||
|
||||
await next();
|
||||
};
|
||||
|
||||
getController(): Hono<any> {
|
||||
const hono = new Hono();
|
||||
override getController() {
|
||||
const hono = this.create();
|
||||
const strategies = this.auth.authenticator.getStrategies();
|
||||
|
||||
for (const [name, strategy] of Object.entries(strategies)) {
|
||||
|
||||
Reference in New Issue
Block a user