fix(api): fix api endpoint logic #3

This commit is contained in:
shafin-r
2025-08-17 19:59:14 +06:00
parent 4f23f357e6
commit e3673951c6
7 changed files with 231 additions and 170 deletions

View File

@ -2,12 +2,16 @@
import React, { createContext, useContext, useState, useEffect } from "react";
import { useRouter, usePathname } from "next/navigation";
import { UserData } from "@/types/auth";
import { API_URL } from "@/lib/auth";
interface AuthContextType {
token: string | null;
setToken: (token: string | null) => void;
logout: () => void;
isLoading: boolean;
user: UserData | null;
fetchUser: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
@ -32,7 +36,6 @@ const setCookie = (
if (typeof document === "undefined") return;
if (value === null) {
// Delete cookie by setting expiration to past date
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Strict; Secure`;
} else {
const expires = new Date();
@ -46,22 +49,46 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
}) => {
const [token, setTokenState] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState<UserData | null>(null);
const router = useRouter();
const pathname = usePathname();
// Custom setToken function that also updates cookies
const setToken = (newToken: string | null) => {
setTokenState(newToken);
setCookie("authToken", newToken);
};
// On app load, check if there's a token in cookies
// Fetch user info from API
const fetchUser = async () => {
if (!token) return;
try {
const res = await fetch(`${API_URL}/me/profile/`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!res.ok) {
throw new Error("Failed to fetch user info");
}
const data: UserData = await res.json();
setUser(data);
} catch (error) {
console.error("Error fetching user:", error);
setUser(null);
logout();
}
};
useEffect(() => {
const initializeAuth = () => {
const initializeAuth = async () => {
const storedToken = getCookie("authToken");
if (storedToken) {
setTokenState(storedToken);
if (
pathname === "/" ||
pathname === "/login" ||
@ -69,6 +96,9 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
) {
router.replace("/home");
}
// Fetch user info when token is found
await fetchUser();
} else {
const publicPages = ["/", "/login", "/register"];
if (!publicPages.includes(pathname)) {
@ -82,21 +112,22 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
initializeAuth();
}, [pathname, router]);
// Function to log out
const logout = () => {
setTokenState(null);
setCookie("authToken", null); // Remove token from cookies
router.replace("/login"); // Redirect to login screen
setUser(null);
setCookie("authToken", null);
router.replace("/login");
};
return (
<AuthContext.Provider value={{ token, setToken, logout, isLoading }}>
<AuthContext.Provider
value={{ token, setToken, logout, isLoading, user, fetchUser }}
>
{children}
</AuthContext.Provider>
);
};
// Hook to use the AuthContext
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {