This commit is contained in:
bipproduction
2025-10-28 16:18:13 +08:00
parent 9c96031574
commit 5dc83dbd35

View File

@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
import jwt, { type JWTPayloadSpec } from '@elysiajs/jwt' import jwt, { type JWTPayloadSpec } from '@elysiajs/jwt'
import Elysia from 'elysia' import Elysia from 'elysia'
import { prisma } from '../lib/prisma' import { prisma } from '../lib/prisma' // pastikan nama file sama persis!
const secret = process.env.JWT_SECRET const secret = process.env.JWT_SECRET
@@ -9,6 +9,7 @@ export default function apiAuth(app: Elysia) {
if (!secret) { if (!secret) {
throw new Error('JWT_SECRET is not defined') throw new Error('JWT_SECRET is not defined')
} }
return app return app
.use( .use(
jwt({ jwt({
@@ -19,17 +20,24 @@ export default function apiAuth(app: Elysia) {
.derive(async ({ cookie, headers, jwt }) => { .derive(async ({ cookie, headers, jwt }) => {
let token: string | undefined let token: string | undefined
// Cek token dari cookie
if (cookie?.token?.value) { if (cookie?.token?.value) {
token = cookie.token.value as any token = cookie.token.value as any
} }
if (headers['x-token']?.startsWith('Bearer ')) {
token = (headers['x-token'] as string).slice(7) // Normalisasi header key
} const headerToken =
if (headers['authorization']?.startsWith('Bearer ')) { headers['x-token'] ||
token = (headers['authorization'] as string).slice(7) headers['X-Token'] ||
headers['authorization'] ||
headers['Authorization']
if (headerToken?.startsWith('Bearer ')) {
token = headerToken.slice(7)
} }
let user: null | Awaited<ReturnType<typeof prisma.user.findUnique>> = null let user: null | Awaited<ReturnType<typeof prisma.user.findUnique>> = null
if (token) { if (token) {
try { try {
const decoded = (await jwt.verify(token)) as JWTPayloadSpec const decoded = (await jwt.verify(token)) as JWTPayloadSpec