2022-08-17 19:59:51 +00:00
|
|
|
<script setup async lang="ts">
|
|
|
|
import { provide, ref } from 'vue';
|
|
|
|
import { useRouter } from 'vue-router';
|
2022-08-24 14:15:33 +00:00
|
|
|
import { Auth, TokenInjectType, isErrorResponse } from '@/api';
|
2022-08-17 19:59:51 +00:00
|
|
|
|
|
|
|
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 {
|
2022-08-24 14:15:33 +00:00
|
|
|
const new_token = await Auth.refresh_token(jwt.value ?? '');
|
2022-08-17 19:59:51 +00:00
|
|
|
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>
|