You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.0 KiB

import { action, atom } from "nanostores";
import { api } from "../api";
import { logOut } from "../SignOut.jsx";
export const userInfoLoading$ = atom(true);
export const isAuthorized$ = atom(false);
export const setAuth = action(isAuthorized$, "setAuth", (store, newValue) => {
store.set(newValue);
});
export const refreshToken = () => {
const url = import.meta.env.VITE_KEYCLOAK_URL || 'https://kk.dev.selftech.ru/';
const clientId = import.meta.env.VITE_KEYCLOAK_CLIENT_ID || 'postnet';
const clientSecret = import.meta.env.VITE_KEYCLOAK_CLIENT_SECRET || 'K2yHweEUispkVeWn03VMk843sW2Moic5';
return api.request({
url: "/realms/SST/protocol/openid-connect/token",
baseURL: url,
method: "POST",
data: {
grant_type: "refresh_token",
client_id: clientId,
client_secret: clientSecret,
token_type: "bearer",
refresh_token: localStorage.getItem("refresh_token")
},
headers: {
'Content-type': 'application/x-www-form-urlencoded',
},
});
}
export const setAuthLocalStorage = (data) => {
localStorage.setItem("access_token", data.access_token);
localStorage.setItem("refresh_token", data.refresh_token);
localStorage.setItem("expires_in", data.expires_in);
}
export const refreshTokenIntervalFunction = async () => {
try {
const { data: refreshData } = await refreshToken();
setAuthLocalStorage(refreshData);
} catch (error) {
clearInterval(interval);
logOut();
throw error;
}
}
async function checkAuth() {
try {
const { data } = await refreshToken();
setAuthLocalStorage(data);
let interval;
setTimeout(async () => {
await refreshTokenIntervalFunction();
interval = setInterval(async () => {
await refreshTokenIntervalFunction();
}, (data.expires_in - 5) * 1000)
}, 0);
setAuth(true);
} catch (e) {
console.log("Not authorized");
clearInterval(interval);
} finally {
userInfoLoading$.set(false);
}
}
checkAuth();