add: guard in router

This commit is contained in:
Alexandro Uc Santos
2023-11-24 21:07:42 -06:00
parent afa8e1983b
commit ec02b98272
18 changed files with 914 additions and 47 deletions

55
src/stores/auth.js Normal file
View File

@@ -0,0 +1,55 @@
import { defineStore } from "pinia";
import { ref, onMounted } from "vue";
import { useRouter } from 'vue-router';
import { renewToken } from '../services/auth';
import {useNotificationsStore} from './notifications';
export const useAuthStore = defineStore('auth', () => {
const router = useRouter();
const noty = useNotificationsStore();
const sesion = ref('')
const checking = ref(false);
const token = ref('')
const user = ref(null)
onMounted( async() => {
console.log('Se ejecuta onMounted auth');
checkSession();
});
const checkSession = async() => {
checking.value = true;
const resp = await renewToken();
if(resp.msg === 'success') {
localStorage.setItem('session', resp.data.session_token);
sesion.value = resp.data.session_token;
token.value = resp.data.accessToken;
user.value = resp.data.user;
checking.value = false;
} else {
noty.show = true;
noty.text = 'Sesión ha expirado, ingresa nuevamente';
noty.error = true;
checking.value = false;
router.push({name: 'login'});
}
}
const logout = () => {
localStorage.removeItem('session');
router.push({name: 'login'});
sesion.value = '';
token.value = '';
user.value = null;
}
return {
sesion,
logout,
token,
user,
checking
}
});