103 lines
3.1 KiB
JavaScript
103 lines
3.1 KiB
JavaScript
import { defineStore } from "pinia";
|
|
import { ref, onMounted } from "vue";
|
|
import { useRoute, useRouter } from 'vue-router';
|
|
import { renewToken } from '../services/auth';
|
|
import {useNotificationsStore} from './notifications';
|
|
import { useLoadsStore } from "./loads";
|
|
import { updateMyUserProfile } from "../services/company";
|
|
|
|
export const useAuthStore = defineStore('auth', () => {
|
|
|
|
const router = useRouter();
|
|
const route = useRoute();
|
|
const noty = useNotificationsStore();
|
|
const loadStore = useLoadsStore();
|
|
const sesion = ref('')
|
|
const checking = ref(false);
|
|
const authStatus = ref('checking');
|
|
const token = ref('')
|
|
const lang = ref('es');
|
|
const user = ref(null);
|
|
const isAuthenticated = ref(false);
|
|
const publicNames = [
|
|
'terms-conditions',
|
|
'notice-privacy',
|
|
'tracking-load',
|
|
'faqs',
|
|
'login',
|
|
'register',
|
|
'recovery',
|
|
'register-company',
|
|
]
|
|
|
|
const checkSession = async() => {
|
|
const session = localStorage.getItem('session');
|
|
authStatus.value = 'checking';
|
|
if((session && !publicNames.includes(route.name)) && isAuthenticated.value === false && checking.value === false) {
|
|
checking.value = true;
|
|
const resp = await renewToken();
|
|
if(resp.msg === 'success') {
|
|
user.value = resp.data.user;
|
|
sesion.value = resp.data.session_token;
|
|
token.value = resp.data.accessToken;
|
|
localStorage.setItem('session', resp.data.session_token);
|
|
localStorage.setItem('access', resp.data.accessToken);
|
|
localStorage.setItem('id', resp.data.user.company._id);
|
|
checking.value = false;
|
|
isAuthenticated.value = true;
|
|
} else {
|
|
noty.show = true;
|
|
noty.text = 'Sesión ha expirado, ingresa nuevamente';
|
|
noty.error = true;
|
|
checking.value = false;
|
|
isAuthenticated.value = false;
|
|
router.push({name: 'login'});
|
|
}
|
|
}
|
|
authStatus.value = 'completed';
|
|
}
|
|
|
|
// const authenticationPromise = new Promise((resolve) => {
|
|
// onMounted(() => {
|
|
// resolve('success');
|
|
// });
|
|
// });
|
|
|
|
const updateProfile = async(data) => {
|
|
const response = await updateMyUserProfile(data);
|
|
if( response.msg === 'success') {
|
|
user.value = response.data;
|
|
return response;
|
|
} else {
|
|
return response;
|
|
}
|
|
}
|
|
|
|
const logout = () => {
|
|
localStorage.removeItem('access');
|
|
localStorage.removeItem('id');
|
|
localStorage.removeItem('session');
|
|
|
|
sesion.value = '';
|
|
token.value = '';
|
|
user.value = null;
|
|
checking.value = false;
|
|
authStatus.value = 'checking';
|
|
isAuthenticated.value = false;
|
|
loadStore.clear();
|
|
}
|
|
|
|
return {
|
|
sesion,
|
|
logout,
|
|
token,
|
|
user,
|
|
checking,
|
|
authStatus,
|
|
checkSession,
|
|
// authenticationPromise,
|
|
updateProfile,
|
|
lang,
|
|
isAuthenticated
|
|
}
|
|
}); |