Add login functionality

This commit is contained in:
Esa Kataja
2025-05-10 13:04:30 +03:00
parent fa7fe83866
commit a87cc4018c
2 changed files with 79 additions and 5 deletions
+60 -3
View File
@@ -1,10 +1,67 @@
<script setup lang="ts">
import { onMounted } from 'vue'
import { useState, useRuntimeConfig } from '#imports'
// Using Nuxt's useState composable instead of Vue's ref
const config = useRuntimeConfig()
const apiBase = config.public.apiBase
const user = useState('user', () => ({}))
const isLoggedIn = useState('isLoggedIn', () => false)
onMounted(() => {
// Checking if code is running in browser environment before accessing localStorage
if (process.client) {
try {
const userData = JSON.parse(localStorage.getItem('user') || '{}')
user.value = userData
if (Object.keys(userData).length > 0) {
isLoggedIn.value = true
}
} catch (error) {
console.error('Error accessing localStorage:', error)
}
}
})
const logout = () => {
if (process.client) {
try {
localStorage.removeItem('user')
isLoggedIn.value = false
user.value = {}
} catch (error) {
console.error('Error during logout:', error)
}
}
}
</script>
<template> <template>
<header class="p-4 shadow-md flex justify-between bg-slate-100"> <header class="p-4 shadow-md flex justify-between bg-slate-100">
<h1><NuxtLink to="/">Eurovision 2025</NuxtLink></h1> <h1><NuxtLink to="/">Eurovision 2025</NuxtLink></h1>
<nav> <nav>
<ul class="flex gap-4"> <ul class="flex items-center gap-4">
<li><NuxtLink to="/profile">Profile</NuxtLink></li> <li v-if="isLoggedIn" class="flex items-center gap-2">
<li><NuxtLink to="/login">Login</NuxtLink></li> <NuxtLink to="/profile">
<NuxtImg
v-if="'avatar_id' in user"
:src="`${apiBase}/static/avatars/${user.avatar_id}.webp`"
class="w-4 h-4 rounded-full object-cover"
:alt="user.username"
/></NuxtLink>
</li>
<li v-if="!isLoggedIn">
<NuxtLink to="/login" class="flex items-center gap-1">
<Icon name="qlementine-icons:log-in-16" class="w-5 h-5" />
</NuxtLink>
</li>
<li v-if="isLoggedIn">
<button @click="logout" class="flex items-center gap-1">
<Icon name="qlementine-icons:log-out-16" class="w-5 h-5" />
</button>
</li>
</ul> </ul>
</nav> </nav>
</header> </header>
+19 -2
View File
@@ -3,8 +3,25 @@ definePageMeta({
layout: 'login' layout: 'login'
}) })
const login = () => { const login = async () => {
console.log('login') const payload = {
username: document.getElementById('username')?.value,
password: document.getElementById('password')?.value
}
const config = useRuntimeConfig()
const apiBase = config.public.apiBase
const api_url = `${apiBase}/auth/token`
const { data: user } = await useFetch(api_url, {
method: 'POST',
body: payload
})
if (!user.value) {
throw createError({
statusCode: 401,
statusMessage: 'Unauthorized'
})
}
localStorage.setItem('user', JSON.stringify(user.value))
navigateTo('/') navigateTo('/')
} }
</script> </script>