fix: requireAuth uses onBeforeHandle instead of error() in derive
This commit is contained in:
parent
0918478255
commit
0b69fbfc72
|
|
@ -13,27 +13,31 @@ function hashEmail(email: string): string {
|
|||
}
|
||||
|
||||
export function requireAuth(app: Elysia) {
|
||||
return app.derive(async ({ headers, error }) => {
|
||||
return app
|
||||
.derive(async ({ headers, set }) => {
|
||||
const key = headers["authorization"]?.replace("Bearer ", "").trim();
|
||||
if (!key) return error(401, { error: "Missing account key. Use: Authorization: Bearer <key>" });
|
||||
if (!key) {
|
||||
set.status = 401;
|
||||
return { accountId: null as string | null, keyId: null as string | null };
|
||||
}
|
||||
|
||||
// Check primary account key
|
||||
const [account] = await sql`SELECT id FROM accounts WHERE id = ${key}`;
|
||||
if (account) {
|
||||
return { accountId: account.id, keyId: null as string | null };
|
||||
}
|
||||
if (account) return { accountId: account.id as string, keyId: null as string | null };
|
||||
|
||||
// Check sub-key
|
||||
const [apiKey] = await sql`
|
||||
SELECT id, account_id FROM api_keys WHERE id = ${key}
|
||||
`;
|
||||
const [apiKey] = await sql`SELECT id, account_id FROM api_keys WHERE id = ${key}`;
|
||||
if (apiKey) {
|
||||
// Update last_used_at async (don't await)
|
||||
sql`UPDATE api_keys SET last_used_at = now() WHERE id = ${key}`.catch(() => {});
|
||||
return { accountId: apiKey.account_id, keyId: apiKey.id as string };
|
||||
return { accountId: apiKey.account_id as string, keyId: apiKey.id as string };
|
||||
}
|
||||
|
||||
return error(401, { error: "Invalid account key" });
|
||||
set.status = 401;
|
||||
return { accountId: null as string | null, keyId: null as string | null };
|
||||
})
|
||||
.onBeforeHandle(({ accountId, set }) => {
|
||||
if (!accountId) {
|
||||
set.status = 401;
|
||||
return { error: "Invalid or missing account key" };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue