feat: load userinfo and show username in topbar

This commit is contained in:
Settel 2022-07-29 23:41:24 +02:00
parent dad3207944
commit 9678a2bdeb
4 changed files with 25 additions and 4 deletions

View File

@ -1,7 +1,7 @@
<template>
<div class="topbar__container">
<div class="topbar__username">
&lt;username&gt;
{{ userInfo.name }}
</div>
<div class="topbar__separator" />
<div class="topbar__actionbar">
@ -17,13 +17,15 @@
<script setup lang="ts">
import { useRouter } from '#app'
import useAuth from '@/composables/useAuth';
import { useUserinfoStore } from "@/stores/UserinfoStore"
const { userInfo } = useUserinfoStore()
const actionLogout = async () => {
await useAuth().logout()
useRouter().push('/')
}
</script>
<style lang="scss">
@ -58,6 +60,7 @@ const actionLogout = async () => {
&__logout-button {
color: $text-primary-color;
font-size: 16px;
&:hover {
color: $text-primary-hover-color;

View File

@ -1,11 +1,15 @@
import { useUserinfoStore } from "@/stores/UserinfoStore"
export interface useAuth {
login(authCode: string): Promise<void>
logout(): Promise<void>
isAuthenticated(): Promise<boolean>
loadUserInfo(): Promise<boolean>
}
export default () => {
const userInfoStore = useUserinfoStore()
return {
isAuthenticated: async (): Promise<boolean> => {
return $fetch('/api/userinfo')
@ -13,6 +17,11 @@ export default () => {
.catch(() => false)
},
loadUserInfo: async (): Promise<void> => {
const userInfo = await $fetch('/api/userinfo')
userInfoStore.setUserInfo(userInfo)
},
login: async (authCode: string): Promise<void> => {
if (authCode.length != 6) {
throw Error('login failed')

View File

@ -9,11 +9,14 @@
import { useRouter } from '#app'
import useAuth from '@/composables/useAuth';
const { isAuthenticated } = useAuth()
const { isAuthenticated, loadUserInfo } = useAuth()
const router = useRouter()
if (!await isAuthenticated()) {
router.push('/')
}
await loadUserInfo()
</script>
<style lang="scss">

View File

@ -3,6 +3,12 @@ import { defineStore } from 'pinia'
export const useUserinfoStore = defineStore('UserinfoStore', {
state: () => {
return {
userInfo: null,
}
},
actions: {
setUserInfo(userInfo: unknown): void {
this.userInfo = userInfo
},
},
})