|
|
|
|
@ -1,5 +1,6 @@
|
|
|
|
|
import { action, atom } from "nanostores";
|
|
|
|
|
import { api } from "../api";
|
|
|
|
|
import { logOut } from "../SignOut.jsx";
|
|
|
|
|
|
|
|
|
|
export const userInfoLoading$ = atom(true);
|
|
|
|
|
|
|
|
|
|
@ -9,13 +10,63 @@ 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 {
|
|
|
|
|
await api.get("/accounts/profile/");
|
|
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|