67 lines
1.2 KiB
Vue
67 lines
1.2 KiB
Vue
|
<script setup async lang="ts">
|
||
|
import { provide, ref } from 'vue';
|
||
|
import { useRouter } from 'vue-router';
|
||
|
import { refresh_token, TokenInjectType, isErrorResponse } from '@/api';
|
||
|
|
||
|
const router = useRouter();
|
||
|
|
||
|
const jwt = ref<string | null>(null);
|
||
|
|
||
|
function setToken(token: string) {
|
||
|
jwt.value = token;
|
||
|
localStorage.setItem('token', token);
|
||
|
}
|
||
|
|
||
|
function logout() {
|
||
|
jwt.value = null;
|
||
|
localStorage.removeItem('token');
|
||
|
router.push({ name: 'login' });
|
||
|
}
|
||
|
|
||
|
jwt.value = localStorage.getItem('token');
|
||
|
if (jwt.value == null) await router.push({ name: 'login' });
|
||
|
else {
|
||
|
const new_token = await refresh_token(jwt.value ?? '');
|
||
|
if (isErrorResponse(new_token)) logout();
|
||
|
else setToken(new_token.jwt);
|
||
|
}
|
||
|
|
||
|
provide<TokenInjectType>('jwt', {
|
||
|
jwt,
|
||
|
setToken,
|
||
|
logout
|
||
|
});
|
||
|
</script>
|
||
|
|
||
|
<template>
|
||
|
<nav>
|
||
|
<router-link to="/login" v-if="jwt != null" @click="logout()">
|
||
|
Logout
|
||
|
</router-link>
|
||
|
</nav>
|
||
|
<router-view />
|
||
|
</template>
|
||
|
|
||
|
<style lang="scss">
|
||
|
#app {
|
||
|
font-family: Avenir, Helvetica, Arial, sans-serif;
|
||
|
-webkit-font-smoothing: antialiased;
|
||
|
-moz-osx-font-smoothing: grayscale;
|
||
|
text-align: center;
|
||
|
color: #2c3e50;
|
||
|
}
|
||
|
|
||
|
nav {
|
||
|
padding: 30px;
|
||
|
|
||
|
a {
|
||
|
font-weight: bold;
|
||
|
color: #2c3e50;
|
||
|
|
||
|
&.router-link-exact-active {
|
||
|
color: #42b983;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
</style>
|