ff-admin/src/serverCom.ts

92 lines
2.4 KiB
TypeScript
Raw Normal View History

2024-08-22 09:48:04 +00:00
import axios from "axios";
2024-11-21 14:58:58 +00:00
import { isAuthenticatedPromise, type Payload } from "./router/authGuard";
import router from "./router";
import { useNotificationStore } from "./stores/notification";
2024-08-22 09:48:04 +00:00
2024-08-25 11:37:23 +00:00
let devMode = process.env.NODE_ENV === "development";
2024-12-05 15:37:10 +00:00
let host = devMode ? "localhost:5000" : process.env.SERVER_ADDRESS || "";
let url = devMode ? "http://" + host : (host ? "https://" : "") + host;
2024-08-22 09:48:04 +00:00
const http = axios.create({
2024-12-05 15:37:10 +00:00
baseURL: url + "/api",
2024-08-22 09:48:04 +00:00
headers: {
"Cache-Control": "no-cache",
Pragma: "no-cache",
Expires: "0",
},
});
http.interceptors.request.use(
(config) => {
const token = localStorage.getItem("accessToken");
if (token) {
if (config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
http.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
if (!error.config.url.includes("/admin") || !error.config.url.includes("/user")) {
2024-08-23 12:42:32 +00:00
return Promise.reject(error);
}
2024-08-22 09:48:04 +00:00
const originalRequest = error.config;
// Handle token expiration and retry the request with a refreshed token
if (error.response && error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
return await refreshToken()
.then(() => {
return http(originalRequest);
})
.catch();
}
const notificationStore = useNotificationStore();
notificationStore.push("Fehler", error.response.data, "error");
2024-08-22 09:48:04 +00:00
return Promise.reject(error);
}
);
2024-08-25 08:10:11 +00:00
export async function refreshToken(): Promise<void> {
2024-08-22 09:48:04 +00:00
return new Promise<void>(async (resolve, reject) => {
await http
.post(`/auth/refresh`, {
2024-08-25 08:10:11 +00:00
accessToken: localStorage.getItem("accessToken"),
2024-08-22 09:48:04 +00:00
refreshToken: localStorage.getItem("refreshToken"),
})
.then(async (response) => {
2024-08-25 08:10:11 +00:00
const { accessToken, refreshToken } = response.data;
2024-08-22 09:48:04 +00:00
2024-08-25 08:10:11 +00:00
localStorage.setItem("accessToken", accessToken);
2024-08-22 09:48:04 +00:00
localStorage.setItem("refreshToken", refreshToken);
await isAuthenticatedPromise().catch((err: string) => {
router.push({ name: err ?? "login" });
reject(err);
});
2024-08-22 09:48:04 +00:00
resolve();
})
.catch((error) => {
console.error("Error refreshing token:", error);
reject("login");
2024-08-22 09:48:04 +00:00
});
});
}
2024-12-05 15:37:10 +00:00
export { http, host };