FUJI/src/components/NavigationUser.vue
2024-08-24 16:55:33 +08:00

73 lines
2.6 KiB
Vue

<script setup lang="ts">
import { onMounted, ref } from "vue"
import { logtoClient } from "../utils/auth"
import type { IdTokenClaims } from "@logto/browser"
import { Menu, MenuButton, MenuItems, MenuItem } from "@headlessui/vue"
const onSignIn = async () => {
logtoClient.signIn(import.meta.env.PUBLIC_LOGTO_CALLBACK_URL)
}
const onSignOut = async () => {
logtoClient.signOut(import.meta.env.PUBLIC_LOGTO_REDIRECT_URL)
}
const isAuthenticated = ref<boolean>()
const userInfo = ref<IdTokenClaims>()
const initAuth = async () => {
try {
await Promise.all([
userInfo.value = await logtoClient.getIdTokenClaims(),
isAuthenticated.value = await logtoClient.isAuthenticated()
])
} catch (error) {
isAuthenticated.value = false
}
}
onMounted(() => {
initAuth()
})
</script>
<template>
<div class="flex items-center justify-center w-12">
<div @click="onSignIn" v-if="isAuthenticated === false" class="">
<a class="nav-item-content px-2 hover:text-[#2997ff] text-nowrap cursor-pointer">登入</a>
</div>
<div class="flex items-center" v-if="isAuthenticated">
<Menu as="div" class="relative inline-block text-left">
<div>
<MenuButton class="flex items-center focus:outline-none">
<div class="h-7 w-7 rounded-full border border-gray-300 overflow-hidden">
<img :src="userInfo.picture" alt="" class="w-full" />
</div>
</MenuButton>
</div>
<transition
enter-active-class="transition duration-100 ease-out"
enter-from-class="transform scale-95 opacity-0"
enter-to-class="transform scale-100 opacity-100"
leave-active-class="transition duration-75 ease-in"
leave-from-class="transform scale-100 opacity-100"
leave-to-class="transform scale-95 opacity-0"
>
<MenuItems
class="absolute right-0 mt-2 w-32 origin-top-right divide-y divide-gray-100 rounded-md bg-white shadow-lg ring-1 ring-black/5 focus:outline-none"
>
<div class="px-1 py-1">
<MenuItem v-slot="{ active }">
<button
@click="onSignOut"
:class="[active ? 'bg-violet-500 text-white' : 'text-gray-900', 'flex w-full items-center rounded-md px-2 py-2 text-sm']"
>
登出
</button>
</MenuItem>
</div>
</MenuItems>
</transition>
</Menu>
</div>
<!-- <div v-if="isAuthenticated" @click="onSignOut" class="px-2">Sign-Out</div> -->
</div>
</template>