40 lines
No EOL
1.1 KiB
TypeScript
40 lines
No EOL
1.1 KiB
TypeScript
function parseJwt(token: string) {
|
|
try {
|
|
const base64Payload = token.split('.')[1]
|
|
const payload = Buffer.from(base64Payload, 'base64').toString('utf8')
|
|
return JSON.parse(payload)
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const config = useRuntimeConfig(event)
|
|
const body = await readBody(event).catch(() => ({}))
|
|
|
|
if (!body?.token) {
|
|
return { active: false, reason: 'No token provided' }
|
|
}
|
|
|
|
const userinfoUrl = `${config.public.keycloakUrl}/realms/${config.public.keycloakRealm}/protocol/openid-connect/userinfo`
|
|
|
|
try {
|
|
const user = await $fetch<any>(userinfoUrl, {
|
|
method: 'GET',
|
|
headers: {
|
|
Authorization: `Bearer ${body.token}`
|
|
}
|
|
})
|
|
|
|
const decodedToken = parseJwt(body.token)
|
|
const realmRoles: string[] = decodedToken?.realm_access?.roles || []
|
|
|
|
if (!realmRoles.includes('portal-access')) {
|
|
return { active: false, reason: 'Missing portal-access role' }
|
|
}
|
|
|
|
return { active: true, user }
|
|
} catch {
|
|
return { active: false, reason: 'Invalid or expired token' }
|
|
}
|
|
}) |