refactor(auth): bubble up auth error to hono
This commit is contained in:
parent
a2432c2e58
commit
2361d2e062
3 changed files with 9 additions and 3 deletions
|
|
@ -3,6 +3,7 @@ import { and, eq, ne } from "drizzle-orm";
|
|||
import { db } from "~/server/db/db";
|
||||
import { account, usersTable } from "~/server/db/schema";
|
||||
import type { AuthMiddlewareContext } from "../auth";
|
||||
import { UnauthorizedError } from "http-errors-enhanced";
|
||||
|
||||
export const convertLegacyUserOnFirstLogin = async (ctx: AuthMiddlewareContext) => {
|
||||
const { path, body } = ctx;
|
||||
|
|
@ -45,7 +46,7 @@ export const convertLegacyUserOnFirstLogin = async (ctx: AuthMiddlewareContext)
|
|||
});
|
||||
});
|
||||
} else {
|
||||
throw new Error("Invalid credentials");
|
||||
throw new UnauthorizedError("Invalid credentials");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import type { AuthMiddlewareContext } from "../auth";
|
|||
import { logger } from "~/server/utils/logger";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { appMetadataTable } from "~/server/db/schema";
|
||||
import { ForbiddenError } from "http-errors-enhanced";
|
||||
|
||||
export const REGISTRATION_DISABLED_KEY = "registrationsDisabled";
|
||||
|
||||
|
|
@ -20,6 +21,6 @@ export const ensureOnlyOneUser = async (ctx: AuthMiddlewareContext) => {
|
|||
|
||||
if (result?.value === "true" && existingUser) {
|
||||
logger.info("User registration attempt blocked: registrations are disabled.");
|
||||
throw new Error("User registrations are currently disabled. Please contact an administrator for access.");
|
||||
throw new ForbiddenError("User registrations are currently disabled. Please contact an administrator for access.");
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
} from "better-auth";
|
||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import { admin, createAuthMiddleware, twoFactor, username, organization } from "better-auth/plugins";
|
||||
import { UnauthorizedError } from "http-errors-enhanced";
|
||||
import { convertLegacyUserOnFirstLogin } from "./auth-middlewares/convert-legacy-user";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { config } from "../server/core/config";
|
||||
|
|
@ -21,6 +22,9 @@ const createBetterAuth = (secret: string) =>
|
|||
betterAuth({
|
||||
secret,
|
||||
trustedOrigins: config.trustedOrigins ?? ["*"],
|
||||
onAPIError: {
|
||||
throw: true,
|
||||
},
|
||||
hooks: {
|
||||
before: createAuthMiddleware(async (ctx) => {
|
||||
await ensureOnlyOneUser(ctx);
|
||||
|
|
@ -81,7 +85,7 @@ const createBetterAuth = (secret: string) =>
|
|||
});
|
||||
|
||||
if (!orgMembership) {
|
||||
throw new Error("User does not belong to any organization");
|
||||
throw new UnauthorizedError("User does not belong to any organization");
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
|
|||
Loading…
Reference in a new issue