revamp template
This commit is contained in:
68
src/auth/_helpers.ts
Normal file
68
src/auth/_helpers.ts
Normal file
@ -0,0 +1,68 @@
|
||||
import { User as Auth0UserModel } from '@auth0/auth0-spa-js';
|
||||
|
||||
import { getData, setData } from '@/utils';
|
||||
import { type AuthModel } from './_models';
|
||||
|
||||
const AUTH_LOCAL_STORAGE_KEY = `${import.meta.env.VITE_APP_NAME}-auth-v${
|
||||
import.meta.env.VITE_APP_VERSION
|
||||
}`;
|
||||
|
||||
const getAuth = (): AuthModel | undefined => {
|
||||
try {
|
||||
const auth = getData(AUTH_LOCAL_STORAGE_KEY) as AuthModel | undefined;
|
||||
|
||||
if (auth) {
|
||||
return auth;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('AUTH LOCAL STORAGE PARSE ERROR', error);
|
||||
}
|
||||
};
|
||||
|
||||
const setAuth = (auth: AuthModel | Auth0UserModel) => {
|
||||
setData(AUTH_LOCAL_STORAGE_KEY, auth);
|
||||
};
|
||||
|
||||
const removeAuth = () => {
|
||||
if (!localStorage) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
localStorage.removeItem(AUTH_LOCAL_STORAGE_KEY);
|
||||
} catch (error) {
|
||||
console.error('AUTH LOCAL STORAGE REMOVE ERROR', error);
|
||||
}
|
||||
};
|
||||
|
||||
export function setupAxios(axios: any) {
|
||||
axios.defaults.headers.Accept = 'application/json';
|
||||
axios.interceptors.request.use(
|
||||
(config: { headers: { Authorization: string }; params?: any; url?: any }) => {
|
||||
const auth = getAuth();
|
||||
|
||||
if (auth?.access_token) {
|
||||
config.headers.Authorization = `Bearer ${auth.access_token}`;
|
||||
|
||||
if (
|
||||
config.url &&
|
||||
!config.url.includes('api/b/') &&
|
||||
!config.url.includes('api/bg/') &&
|
||||
!config.url.includes('api/c/')
|
||||
) {
|
||||
config.params = {
|
||||
...config.params,
|
||||
token: auth.access_token || ''
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
},
|
||||
async (err: any) => await Promise.reject(err)
|
||||
);
|
||||
}
|
||||
|
||||
export { AUTH_LOCAL_STORAGE_KEY, getAuth, removeAuth, setAuth };
|
||||
Reference in New Issue
Block a user