diff --git a/app/composables/useAuth.js b/app/composables/useAuth.js index 4852bc1..7f86707 100644 --- a/app/composables/useAuth.js +++ b/app/composables/useAuth.js @@ -37,7 +37,7 @@ export const useAuth = () => { method: 'POST', body: { code, - redirectUri: `${window.location.origin}/` + redirectUri: `${window.location.origin}/oauth` } }) diff --git a/app/pages/oauth/index.vue b/app/pages/oauth/index.vue index 8492940..cffd8a8 100644 --- a/app/pages/oauth/index.vue +++ b/app/pages/oauth/index.vue @@ -2,19 +2,35 @@ import { ref, onMounted } from 'vue' const config = useRuntimeConfig() +const route = useRoute() +const { exchangeCodeForToken } = useAuth() const isInitialized = ref(false) const isLoggingIn = ref(false) +const errorMessage = ref('') -onMounted(() => { +onMounted(async () => { isInitialized.value = true + + if (route.query.code) { + isLoggingIn.value = true + const success = await exchangeCodeForToken(route.query.code) + + if (success) { + await navigateTo('/') + } else { + errorMessage.value = 'Access Denied' + isLoggingIn.value = false + } + } }) const handleLogin = () => { if (isLoggingIn.value) return isLoggingIn.value = true + errorMessage.value = '' - const redirectUri = `${window.location.origin}/` + const redirectUri = `${window.location.origin}/oauth` const authUrl = new URL( `${config.public.keycloakUrl}/realms/${config.public.keycloakRealm}/protocol/openid-connect/auth` @@ -23,7 +39,7 @@ const handleLogin = () => { authUrl.searchParams.append('client_id', config.public.keycloakClientId) authUrl.searchParams.append('redirect_uri', redirectUri) authUrl.searchParams.append('response_type', 'code') - authUrl.searchParams.append('scope', 'openid profile email') + authUrl.searchParams.append('scope', 'openid profile email roles') window.location.href = authUrl.toString() } @@ -39,12 +55,17 @@ const handleLogin = () => {
Hai there :3
+ ++ {{ errorMessage }} +
+ diff --git a/server/api/auth/check-session.post.ts b/server/api/auth/check-session.post.ts index 969c808..209b153 100644 --- a/server/api/auth/check-session.post.ts +++ b/server/api/auth/check-session.post.ts @@ -1,23 +1,40 @@ +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) + const body = await readBody(event).catch(() => ({})) if (!body?.token) { - return { active: false } + 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(userinfoUrl, { + const user = await $fetch