feat!: replace auth with OIDC

This commit is contained in:
Cfp
2025-06-22 11:48:07 +02:00
parent 51c0e0c16f
commit 03dd27efc0
4 changed files with 122 additions and 93 deletions

View File

@ -1,15 +1,38 @@
import { betterAuth } from "better-auth";
import { username } from "better-auth/plugins";
import { pool } from "./db";
import { decode, verify, type Algorithm } from "jsonwebtoken";
import jwkToPem, { type JWK } from "jwk-to-pem";
export const auth = betterAuth({
database: pool,
emailAndPassword: {
enabled: true
},
plugins: [
username({
minUsernameLength: 3
})
]
});
const JWKS = process.env.OIDC_JWKS_URL || "";
type JWKSResponse = {
keys: Array<{ kid: string; kty: string; use: string; alg: Algorithm; n: string; e: string }>;
}
export async function verifyToken(token: string): Promise<boolean> {
const decoded = decode(token, { complete: true });
const jwks = await fetch(JWKS)
.then(res => res.json() as Promise<JWKSResponse>);
if (!decoded || !decoded.header || !decoded.header.kid) {
return false;
}
const key = jwks.keys.find(k => k.kid === decoded.header.kid);
if (!key) {
return false;
}
const pem = jwkToPem(key as JWK);
try {
const res = verify(token, pem, { algorithms: [key.alg] });
console.log(res);
return typeof res === "object" && "sub" in res;
} catch (err) {
return false;
}
}
export function getTokenUID(token: string): string | null {
const decoded = decode(token);
if (typeof decoded === "object" && decoded !== null && "sub" in decoded) {
return decoded.sub as string;
}
return null;
}