mirror of
https://github.com/i701/sarlink-portal.git
synced 2025-06-28 03:53:57 +00:00
refactor: update axios client import, enhance device and payment handling, and add cancel payment button component
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 6m28s
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 6m28s
This commit is contained in:
59
utils/axios-client.ts
Normal file
59
utils/axios-client.ts
Normal file
@ -0,0 +1,59 @@
|
||||
import { authOptions } from "@/app/auth";
|
||||
import axios, { type AxiosError } from "axios";
|
||||
import { type Session, getServerSession } from "next-auth";
|
||||
import { getSession } from "next-auth/react";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
axios.defaults.xsrfCookieName = "csrftoken";
|
||||
axios.defaults.xsrfHeaderName = "X-CSRFToken";
|
||||
|
||||
const APIClient = () => {
|
||||
const instance = axios.create({
|
||||
baseURL: process.env.SARLINK_API_BASE_URL,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
let lastSession: Session | null = null;
|
||||
console.log("Last session: ", lastSession);
|
||||
|
||||
instance.interceptors.request.use(
|
||||
async (request) => {
|
||||
if (lastSession == null || Date.now() > Date.parse(lastSession.expires)) {
|
||||
const session = await getServerSession(authOptions);
|
||||
console.log("Server session: ", session);
|
||||
lastSession = session;
|
||||
}
|
||||
|
||||
if (lastSession) {
|
||||
request.headers.Authorization = `Token ${lastSession.apiToken}`;
|
||||
} else {
|
||||
request.headers.Authorization = undefined;
|
||||
}
|
||||
|
||||
return request;
|
||||
},
|
||||
(error) => {
|
||||
console.error("API Request Error: ", error);
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
|
||||
instance.interceptors.response.use(
|
||||
async (response) => {
|
||||
return response;
|
||||
},
|
||||
async (error: AxiosError) => {
|
||||
if (error?.response?.status === 401) {
|
||||
// Redirect to the signin page if the user is unauthorized
|
||||
redirect("/auth/signin");
|
||||
}
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
|
||||
return instance;
|
||||
};
|
||||
|
||||
export const AxiosClient = APIClient();
|
Reference in New Issue
Block a user