This commit is contained in:
@ -1,31 +1,36 @@
|
||||
import axios, {type AxiosError, type AxiosResponse} from "axios";
|
||||
import {store} from "@/main.ts";
|
||||
import {addNewMessage, color} from "@/services/popupDisplayer.ts";
|
||||
import axios, { type AxiosError, type AxiosResponse } from "axios";
|
||||
import { store } from "@/main.ts";
|
||||
import { addNewMessage, color } from "@/services/popupDisplayer.ts";
|
||||
|
||||
const axiosInstance = axios.create({
|
||||
baseURL: import.meta.env.VITE_BACKEND_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
axiosInstance.interceptors.response.use(
|
||||
response => response, // Directly return successful responses.
|
||||
async error => {
|
||||
(response) => response, // Directly return successful responses.
|
||||
async (error) => {
|
||||
const originalRequest = error.config;
|
||||
if (error.response.status === 401 && !originalRequest._retry && store.authenticated) {
|
||||
if (
|
||||
error.response.status === 401 &&
|
||||
!originalRequest._retry &&
|
||||
store.authenticated
|
||||
) {
|
||||
originalRequest._retry = true; // Mark the request as retried to avoid infinite loops.
|
||||
try {
|
||||
await store.refreshUserToken();
|
||||
// Update the authorization header with the new access token.
|
||||
axiosInstance.defaults.headers.common['Authorization'] = `Bearer ${store.user.token}`;
|
||||
axiosInstance.defaults.headers.common["Authorization"] =
|
||||
`Bearer ${store.user.token}`;
|
||||
return axiosInstance(originalRequest); // Retry the original request with the new access token.
|
||||
} catch (refreshError) {
|
||||
// Handle refresh token errors by clearing stored tokens and redirecting to the login page.
|
||||
console.error('Token refresh failed:', refreshError);
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
window.location.href = '/login';
|
||||
console.error("Token refresh failed:", refreshError);
|
||||
localStorage.removeItem("accessToken");
|
||||
localStorage.removeItem("refreshToken");
|
||||
window.location.href = "/login";
|
||||
return Promise.reject(refreshError);
|
||||
}
|
||||
}
|
||||
@ -34,20 +39,29 @@ axiosInstance.interceptors.response.use(
|
||||
);
|
||||
|
||||
// TODO: spawn a error modal
|
||||
function defaultApiErrorHandler(err: AxiosError){
|
||||
function defaultApiErrorHandler(err: AxiosError) {
|
||||
addNewMessage(err.message, color.Red);
|
||||
}
|
||||
|
||||
function defaultApiSuccessHandler(response: AxiosResponse){
|
||||
addNewMessage(response.data, color.Green)
|
||||
}
|
||||
function callApi(endpoint: string, onSuccessHandler?: (response: AxiosResponse) => void, onErrorHandler?: (error: AxiosError) => void): void {
|
||||
axiosInstance.get(endpoint).then(
|
||||
onSuccessHandler == null ? defaultApiSuccessHandler : onSuccessHandler
|
||||
).catch(
|
||||
onErrorHandler == null ? defaultApiErrorHandler: onErrorHandler
|
||||
)
|
||||
function defaultApiSuccessHandler(response: AxiosResponse) {
|
||||
addNewMessage(response.data, color.Green);
|
||||
}
|
||||
|
||||
function callApi(
|
||||
endpoint: string,
|
||||
onSuccessHandler?: (response: AxiosResponse) => void,
|
||||
onErrorHandler?: (error: AxiosError) => void
|
||||
): void {
|
||||
axiosInstance
|
||||
.get(endpoint)
|
||||
.then(
|
||||
onSuccessHandler == null
|
||||
? defaultApiSuccessHandler
|
||||
: onSuccessHandler
|
||||
)
|
||||
.catch(
|
||||
onErrorHandler == null ? defaultApiErrorHandler : onErrorHandler
|
||||
);
|
||||
}
|
||||
|
||||
export {callApi}
|
||||
export { callApi };
|
||||
|
@ -1,34 +1,31 @@
|
||||
import Keycloak from 'keycloak-js';
|
||||
import type {AuthStore} from "@/stores/authStore.ts";
|
||||
import Keycloak from "keycloak-js";
|
||||
import type { AuthStore } from "@/stores/authStore.ts";
|
||||
|
||||
const options = {
|
||||
url: import.meta.env.VITE_KEYCLOAK_URL,
|
||||
clientId: import.meta.env.VITE_KEYCLOAK_CLIENT_ID,
|
||||
realm: import.meta.env.VITE_KEYCLOAK_REALM
|
||||
}
|
||||
|
||||
realm: import.meta.env.VITE_KEYCLOAK_REALM,
|
||||
};
|
||||
|
||||
const keycloak = new Keycloak(options);
|
||||
let authenticated: boolean | undefined;
|
||||
let store = null;
|
||||
|
||||
async function login(){
|
||||
async function login() {
|
||||
try {
|
||||
await keycloak.login() // https://www.keycloak.org/securing-apps/javascript-adapter#:~:text=when%20initialization%20completes.-,login(options),-Redirects%20to%20login
|
||||
await keycloak.login(); // https://www.keycloak.org/securing-apps/javascript-adapter#:~:text=when%20initialization%20completes.-,login(options),-Redirects%20to%20login
|
||||
return keycloak;
|
||||
} catch (error) {
|
||||
console.log(error)
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function signup(){
|
||||
async function signup() {
|
||||
try {
|
||||
await keycloak.login(
|
||||
{action: "register"}
|
||||
) // https://www.keycloak.org/securing-apps/javascript-adapter#:~:text=when%20initialization%20completes.-,login(options),-Redirects%20to%20login
|
||||
await keycloak.login({ action: "register" }); // https://www.keycloak.org/securing-apps/javascript-adapter#:~:text=when%20initialization%20completes.-,login(options),-Redirects%20to%20login
|
||||
return keycloak;
|
||||
} catch (error) {
|
||||
console.log(error)
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
@ -43,13 +40,13 @@ async function init(onInitCallback: () => void) {
|
||||
onLoad: "check-sso",
|
||||
silentCheckSsoRedirectUri: `${location.origin}/silent-check-sso.htm`,
|
||||
responseMode: "query",
|
||||
})
|
||||
onInitCallback()
|
||||
});
|
||||
onInitCallback();
|
||||
} catch (error) {
|
||||
console.error("Keycloak init failed")
|
||||
console.error(error)
|
||||
console.error("Keycloak init failed");
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes store with Keycloak user data
|
||||
@ -57,17 +54,19 @@ async function init(onInitCallback: () => void) {
|
||||
*/
|
||||
async function initStore(storeInstance: AuthStore) {
|
||||
try {
|
||||
store = storeInstance
|
||||
console.log(keycloak)
|
||||
await store.initOauth(keycloak)
|
||||
store = storeInstance;
|
||||
console.log(keycloak);
|
||||
await store.initOauth(keycloak);
|
||||
|
||||
// Show alert if user is not authenticated
|
||||
if (!authenticated) { console.warn("not authenticated") }
|
||||
if (!authenticated) {
|
||||
console.warn("not authenticated");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Keycloak init failed")
|
||||
console.error(error)
|
||||
console.error("Keycloak init failed");
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout user
|
||||
@ -84,7 +83,7 @@ async function refreshToken() {
|
||||
await keycloak.updateToken(480);
|
||||
return keycloak;
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh token');
|
||||
console.error("Failed to refresh token");
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
@ -98,4 +97,4 @@ const KeycloakService = {
|
||||
callSignup: signup,
|
||||
};
|
||||
|
||||
export default KeycloakService;
|
||||
export default KeycloakService;
|
||||
|
@ -1,6 +1,11 @@
|
||||
import {ref} from "vue";
|
||||
import {type Ref} from "vue";
|
||||
enum color {Red, Yellow, Blue, Green}
|
||||
import { ref, type Ref } from "vue";
|
||||
|
||||
enum color {
|
||||
Red,
|
||||
Yellow,
|
||||
Blue,
|
||||
Green,
|
||||
}
|
||||
|
||||
type ErrorMessageContent = {
|
||||
message: string;
|
||||
@ -11,23 +16,28 @@ type ErrorMessageContent = {
|
||||
|
||||
let id: number = 0;
|
||||
const getId = () => {
|
||||
id = id+1;
|
||||
id = id + 1;
|
||||
return id;
|
||||
}
|
||||
};
|
||||
|
||||
function addNewMessage(errorMessage: string, type?: color, timeout?: number){
|
||||
if (timeout == null){
|
||||
function addNewMessage(errorMessage: string, type?: color, timeout?: number) {
|
||||
if (timeout == null) {
|
||||
timeout = 5000;
|
||||
}
|
||||
if (type == null){
|
||||
if (type == null) {
|
||||
type = color.Red;
|
||||
}
|
||||
|
||||
const data: ErrorMessageContent = {message: errorMessage, timeout: timeout, color: type, id: getId()};
|
||||
errorList.value.push(data)
|
||||
setTimeout(() => errorList.value.slice(0, 1), timeout)
|
||||
const data: ErrorMessageContent = {
|
||||
message: errorMessage,
|
||||
timeout: timeout,
|
||||
color: type,
|
||||
id: getId(),
|
||||
};
|
||||
errorList.value.push(data);
|
||||
setTimeout(() => errorList.value.slice(0, 1), timeout);
|
||||
}
|
||||
|
||||
const errorList: Ref<ErrorMessageContent[]>= ref([])
|
||||
const errorList: Ref<ErrorMessageContent[]> = ref([]);
|
||||
|
||||
export {addNewMessage, errorList, color, type ErrorMessageContent}
|
||||
export { addNewMessage, errorList, color, type ErrorMessageContent };
|
||||
|
Reference in New Issue
Block a user