mirror of
				https://github.com/i701/sarlink-portal.git
				synced 2025-11-04 06:26:59 +00:00 
			
		
		
		
	
		
			Some checks failed
		
		
	
	Build and Push Docker Images / Build and Push Docker Images (push) Failing after 6m28s
				
			
		
			
				
	
	
		
			60 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
			
		
		
	
	
			60 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
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();
 |