add: guard in router
This commit is contained in:
55
src/stores/auth.js
Normal file
55
src/stores/auth.js
Normal 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
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user