mirror of
https://github.com/ramvignesh-b/pi-ku.git
synced 2026-05-04 08:56:52 +00:00
refactor: implement automatic token refresh and credential support for auth API client
This commit is contained in:
@@ -1,10 +1,30 @@
|
||||
import axios from "axios";
|
||||
|
||||
const apiClient = axios.create({
|
||||
const authApiClient = axios.create({
|
||||
baseURL: `${import.meta.env.VITE_API_URL}/api/auth/`,
|
||||
withCredentials: true,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
export default apiClient;
|
||||
authApiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
if (error.response.status === 401) {
|
||||
// token expired, refresh it
|
||||
try {
|
||||
const response = await authApiClient.post("refresh/");
|
||||
if (response.status === 200) {
|
||||
// refresh successful, retry the request
|
||||
return authApiClient(error.config);
|
||||
}
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
|
||||
export default authApiClient;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { CheckCircleIcon, XCircleIcon } from "@phosphor-icons/react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import apiClient from "../api/apiClient";
|
||||
import authApiClient from "../api/apiClient";
|
||||
import Logo from "../components/Logo";
|
||||
|
||||
export default function Activate() {
|
||||
@@ -20,7 +20,7 @@ export default function Activate() {
|
||||
|
||||
const activateAccount = async () => {
|
||||
try {
|
||||
await apiClient.get(`/activate/${uidb64}/${token}/`);
|
||||
await authApiClient.get(`/activate/${uidb64}/${token}/`);
|
||||
setStatus("success");
|
||||
} catch (err) {
|
||||
console.error("Activation error:", err);
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { z } from "zod";
|
||||
import apiClient from "../api/apiClient";
|
||||
import authApiClient from "../api/apiClient";
|
||||
import Logo from "../components/Logo";
|
||||
import FormField from "../components/ui/FormField";
|
||||
|
||||
@@ -41,7 +41,7 @@ export default function Register() {
|
||||
setIsLoading(true);
|
||||
setApiError(null);
|
||||
try {
|
||||
await apiClient.post("/register/", {
|
||||
await authApiClient.post("/register/", {
|
||||
full_name: data.full_name,
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
|
||||
Reference in New Issue
Block a user