generated from muhtadeetaron/nextjs-template
fix(api): fix api endpoint logic #3
This commit is contained in:
@ -12,9 +12,17 @@ import FormField from "@/components/FormField";
|
|||||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||||
import { RegisterForm } from "@/types/auth";
|
import { RegisterForm } from "@/types/auth";
|
||||||
|
|
||||||
|
interface ValidationErrorItem {
|
||||||
|
type: string;
|
||||||
|
loc: string[];
|
||||||
|
msg: string;
|
||||||
|
input?: unknown;
|
||||||
|
ctx?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
interface CustomError extends Error {
|
interface CustomError extends Error {
|
||||||
response?: {
|
response?: {
|
||||||
detail?: string;
|
detail?: string | ValidationErrorItem;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,16 +44,27 @@ export default function RegisterPage() {
|
|||||||
});
|
});
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const handleError = (error: { detail: string }) => {
|
function formatError(error: unknown): string {
|
||||||
if (error?.detail) {
|
if (error && typeof error === "object" && "response" in (error as any)) {
|
||||||
const match = error.detail.match(/Key \((.*?)\)=\((.*?)\)/);
|
const customError = error as CustomError;
|
||||||
if (match) {
|
const detail = customError.response?.detail;
|
||||||
const field = match[1];
|
|
||||||
return `The ${field} already exists. Please try again.`;
|
if (typeof detail === "string") {
|
||||||
|
return detail; // plain backend error string
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(detail)) {
|
||||||
|
// Pick the first validation error, or join them if multiple
|
||||||
|
return detail.map((d) => d.msg).join("; ");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return "An unexpected error occurred. Please try again.";
|
|
||||||
};
|
if (error instanceof Error) {
|
||||||
|
return error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return "An unexpected error occurred.";
|
||||||
|
}
|
||||||
|
|
||||||
const validateForm = () => {
|
const validateForm = () => {
|
||||||
const { ssc_roll, hsc_roll, password } = form;
|
const { ssc_roll, hsc_roll, password } = form;
|
||||||
@ -69,31 +88,12 @@ export default function RegisterPage() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await register(form, setToken);
|
await register(form, setToken);
|
||||||
router.push("/home");
|
router.push("/login");
|
||||||
} catch (error) {
|
} catch (err: unknown) {
|
||||||
// Type guard for built-in Error type
|
setError(formatError(err));
|
||||||
if (error instanceof Error) {
|
console.error("User creation error: ", err);
|
||||||
console.error(
|
|
||||||
"Error:",
|
|
||||||
(error as CustomError).response || error.message
|
|
||||||
);
|
|
||||||
|
|
||||||
const response = (error as CustomError).response;
|
|
||||||
|
|
||||||
if (response?.detail) {
|
|
||||||
const decodedError = handleError({ detail: response.detail });
|
|
||||||
setError(decodedError);
|
|
||||||
} else {
|
|
||||||
setError(error.message || "An unexpected error occurred.");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Fallback for non-standard errors
|
|
||||||
console.error("Unexpected error:", error);
|
|
||||||
setError("An unexpected error occurred.");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BackgroundWrapper>
|
<BackgroundWrapper>
|
||||||
<div className="min-h-screen flex flex-col items-center justify-center px-4 py-10">
|
<div className="min-h-screen flex flex-col items-center justify-center px-4 py-10">
|
||||||
|
|||||||
@ -3,7 +3,14 @@
|
|||||||
import ProfileManager from "@/components/ProfileManager";
|
import ProfileManager from "@/components/ProfileManager";
|
||||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||||
import { getToken, API_URL } from "@/lib/auth";
|
import { getToken, API_URL } from "@/lib/auth";
|
||||||
import { ChevronLeft, Edit2, Lock, Save } from "lucide-react";
|
import {
|
||||||
|
BadgeCheck,
|
||||||
|
ChevronLeft,
|
||||||
|
Edit2,
|
||||||
|
Lock,
|
||||||
|
Save,
|
||||||
|
ShieldX,
|
||||||
|
} from "lucide-react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import React, { useEffect, useState } from "react";
|
import React, { useEffect, useState } from "react";
|
||||||
import { UserData } from "@/types/auth";
|
import { UserData } from "@/types/auth";
|
||||||
@ -85,7 +92,22 @@ const ProfilePage = () => {
|
|||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
|
|
||||||
<div className="pt-14 space-y-8">
|
<div className="pt-14 space-y-4">
|
||||||
|
{userData?.is_verified ? (
|
||||||
|
<div className="flex gap-4 justify-center items-center bg-green-200 border border-green-700 px-3 py-4 rounded-2xl ">
|
||||||
|
<BadgeCheck size={30} />
|
||||||
|
<p className="text-sm font-semibold text-black">
|
||||||
|
This account is verified.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex gap-2 justify-center items-center bg-red-200 border border-red-700 px-3 py-4 rounded-2xl ">
|
||||||
|
<ShieldX size={30} />
|
||||||
|
<p className="text-sm font-semibold text-black">
|
||||||
|
This account is not verified.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<ProfileManager
|
<ProfileManager
|
||||||
userData={userData}
|
userData={userData}
|
||||||
edit={editStatus}
|
edit={editStatus}
|
||||||
|
|||||||
@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||||
import { API_URL, getToken } from "@/lib/auth";
|
import { useAuth } from "@/context/AuthContext";
|
||||||
import { UserData } from "@/types/auth";
|
import { clearAuthToken } from "@/lib/auth";
|
||||||
import {
|
import {
|
||||||
Bookmark,
|
Bookmark,
|
||||||
ChartColumn,
|
ChartColumn,
|
||||||
@ -19,49 +19,16 @@ import {
|
|||||||
UserCircle2,
|
UserCircle2,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import React, { useEffect, useState } from "react";
|
import React from "react";
|
||||||
|
|
||||||
const SettingsPage = () => {
|
const SettingsPage = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [userData, setUserData] = useState<UserData>({
|
const { user, isLoading } = useAuth();
|
||||||
user_id: "3fa85f64-5717-4562-b3fc-2c963f66afa6",
|
|
||||||
username: "",
|
|
||||||
full_name: "",
|
|
||||||
email: "",
|
|
||||||
is_verified: false,
|
|
||||||
phone_number: "",
|
|
||||||
ssc_roll: 0,
|
|
||||||
ssc_board: "",
|
|
||||||
hsc_roll: 0,
|
|
||||||
hsc_board: "",
|
|
||||||
college: "",
|
|
||||||
preparation_unit: "Science",
|
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(() => {
|
function handleLogout() {
|
||||||
async function fetchUser() {
|
clearAuthToken();
|
||||||
try {
|
router.replace("/");
|
||||||
const token = await getToken();
|
}
|
||||||
if (!token) return;
|
|
||||||
|
|
||||||
const response = await fetch(`${API_URL}/me/`, {
|
|
||||||
method: "GET",
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
const fetchedUserData = await response.json();
|
|
||||||
setUserData(fetchedUserData);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error fetching user data: ", error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fetchUser();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BackgroundWrapper>
|
<BackgroundWrapper>
|
||||||
@ -81,16 +48,14 @@ const SettingsPage = () => {
|
|||||||
<div className="flex gap-4 items-center">
|
<div className="flex gap-4 items-center">
|
||||||
<Avatar className="bg-[#113768] w-20 h-20">
|
<Avatar className="bg-[#113768] w-20 h-20">
|
||||||
<AvatarFallback className="text-3xl text-white">
|
<AvatarFallback className="text-3xl text-white">
|
||||||
{userData?.username
|
{user?.username
|
||||||
? userData.username.charAt(0).toUpperCase()
|
? user.username.charAt(0).toUpperCase()
|
||||||
: ""}
|
: ""}
|
||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
<div className="flex flex-col items-start">
|
<div className="flex flex-col items-start">
|
||||||
<h1 className="font-semibold text-2xl">
|
<h1 className="font-semibold text-2xl">{user?.full_name}</h1>
|
||||||
{userData?.full_name}
|
<h3 className=" text-md">{user?.email}</h3>
|
||||||
</h1>
|
|
||||||
<h3 className=" text-md">{userData?.email}</h3>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@ -181,7 +146,7 @@ const SettingsPage = () => {
|
|||||||
</div>
|
</div>
|
||||||
<ChevronRight size={30} color="#113768" />
|
<ChevronRight size={30} color="#113768" />
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between">
|
<button onClick={handleLogout} className="flex justify-between">
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<LogOut size={30} color="#113768" />
|
<LogOut size={30} color="#113768" />
|
||||||
<h3 className="text-md font-medium text-[#113768]">
|
<h3 className="text-md font-medium text-[#113768]">
|
||||||
@ -189,7 +154,7 @@ const SettingsPage = () => {
|
|||||||
</h3>
|
</h3>
|
||||||
</div>
|
</div>
|
||||||
<ChevronRight size={30} color="#113768" />
|
<ChevronRight size={30} color="#113768" />
|
||||||
</div>
|
</button>
|
||||||
<div className="h-[0.5px] border-[0.1px] w-full border-[#113768]/20"></div>
|
<div className="h-[0.5px] border-[0.1px] w-full border-[#113768]/20"></div>
|
||||||
<p className="text-center text-[#113768]/50 font-medium">
|
<p className="text-center text-[#113768]/50 font-medium">
|
||||||
ExamJam | Version 1.0
|
ExamJam | Version 1.0
|
||||||
|
|||||||
@ -6,8 +6,7 @@ import styles from "@/css/Header.module.css";
|
|||||||
import { useExam } from "@/context/ExamContext";
|
import { useExam } from "@/context/ExamContext";
|
||||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||||
import { useModal } from "@/context/ModalContext";
|
import { useModal } from "@/context/ModalContext";
|
||||||
import { API_URL, getToken } from "@/lib/auth";
|
import { useAuth } from "@/context/AuthContext";
|
||||||
import { UserData } from "@/types/auth";
|
|
||||||
|
|
||||||
interface HeaderProps {
|
interface HeaderProps {
|
||||||
displayUser?: boolean;
|
displayUser?: boolean;
|
||||||
@ -29,7 +28,7 @@ const Header = ({
|
|||||||
examDuration ? parseInt(examDuration) * 60 : 0
|
examDuration ? parseInt(examDuration) * 60 : 0
|
||||||
);
|
);
|
||||||
const { stopTimer } = useTimer();
|
const { stopTimer } = useTimer();
|
||||||
const [userData, setUserData] = useState<UserData>();
|
const { user, isLoading } = useAuth();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!examDuration) return;
|
if (!examDuration) return;
|
||||||
@ -47,33 +46,6 @@ const Header = ({
|
|||||||
return () => clearInterval(timer);
|
return () => clearInterval(timer);
|
||||||
}, [examDuration]);
|
}, [examDuration]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
async function fetchUser() {
|
|
||||||
try {
|
|
||||||
const token = await getToken();
|
|
||||||
if (!token) return;
|
|
||||||
|
|
||||||
const response = await fetch(`${API_URL}/me/`, {
|
|
||||||
method: "GET",
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
const fetchedUserData = await response.json();
|
|
||||||
setUserData(fetchedUserData);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error fetching user data:", error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (displayUser) {
|
|
||||||
fetchUser();
|
|
||||||
}
|
|
||||||
}, [displayUser]);
|
|
||||||
|
|
||||||
const hours = Math.floor(totalSeconds / 3600);
|
const hours = Math.floor(totalSeconds / 3600);
|
||||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||||
const seconds = totalSeconds % 60;
|
const seconds = totalSeconds % 60;
|
||||||
@ -100,13 +72,11 @@ const Header = ({
|
|||||||
<div className={styles.profile}>
|
<div className={styles.profile}>
|
||||||
<Avatar className="bg-gray-200 w-10 h-10">
|
<Avatar className="bg-gray-200 w-10 h-10">
|
||||||
<AvatarFallback className=" text-lg">
|
<AvatarFallback className=" text-lg">
|
||||||
{userData?.username
|
{user?.username ? user.username.charAt(0).toUpperCase() : ""}
|
||||||
? userData.username.charAt(0).toUpperCase()
|
|
||||||
: ""}
|
|
||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
<span className={styles.text}>
|
<span className={styles.text}>
|
||||||
Hello, {userData?.username ? userData.username.split(" ")[0] : ""}
|
Hello, {user?.username ? user.username.split(" ")[0] : ""}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@ -19,10 +19,15 @@ export default function ProfileManager({
|
|||||||
setUserData((prev) => (prev ? { ...prev, [field]: value } : prev));
|
setUserData((prev) => (prev ? { ...prev, [field]: value } : prev));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
console.log(userData);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto">
|
<div className="mx-auto">
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{/* Full Name */}
|
{/* Full Name */}
|
||||||
|
<h1 className="text-xl font-semibold tracking-tight">
|
||||||
|
Personal Information
|
||||||
|
</h1>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label
|
<Label
|
||||||
htmlFor="full_name"
|
htmlFor="full_name"
|
||||||
@ -39,61 +44,24 @@ export default function ProfileManager({
|
|||||||
readOnly={!edit}
|
readOnly={!edit}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* College */}
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label
|
<Label
|
||||||
htmlFor="college"
|
htmlFor="username"
|
||||||
className="text-sm font-semibold text-gray-700"
|
className="text-sm font-semibold text-gray-700"
|
||||||
>
|
>
|
||||||
College
|
Username
|
||||||
</Label>
|
</Label>
|
||||||
<Input
|
<Input
|
||||||
id="college"
|
id="username"
|
||||||
type="text"
|
type="text"
|
||||||
value={userData.college}
|
value={userData.username}
|
||||||
onChange={(e) => handleChange("college", e.target.value)}
|
onChange={(e) => handleChange("username", e.target.value)}
|
||||||
className="bg-gray-50 py-6"
|
className="bg-gray-50 py-6"
|
||||||
readOnly={!edit}
|
readOnly={!edit}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* SSC & HSC Rolls */}
|
{/* SSC & HSC Rolls */}
|
||||||
<div className="flex gap-4">
|
|
||||||
<div className="space-y-2 w-full">
|
|
||||||
<Label
|
|
||||||
htmlFor="ssc_roll"
|
|
||||||
className="text-sm font-semibold text-gray-700"
|
|
||||||
>
|
|
||||||
SSC Roll
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="ssc_roll"
|
|
||||||
type="number"
|
|
||||||
value={userData.ssc_roll}
|
|
||||||
onChange={(e) => handleChange("ssc_roll", Number(e.target.value))}
|
|
||||||
className="bg-gray-50 py-6"
|
|
||||||
readOnly={!edit}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2 w-full">
|
|
||||||
<Label
|
|
||||||
htmlFor="hsc_roll"
|
|
||||||
className="text-sm font-semibold text-gray-700"
|
|
||||||
>
|
|
||||||
HSC Roll
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="hsc_roll"
|
|
||||||
type="number"
|
|
||||||
value={userData.hsc_roll}
|
|
||||||
onChange={(e) => handleChange("hsc_roll", Number(e.target.value))}
|
|
||||||
className="bg-gray-50 py-6"
|
|
||||||
readOnly={!edit}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Email */}
|
{/* Email */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@ -130,6 +98,111 @@ export default function ProfileManager({
|
|||||||
readOnly={!edit}
|
readOnly={!edit}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<h1 className="text-xl tracking-tight font-semibold">
|
||||||
|
Educational Background
|
||||||
|
</h1>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label
|
||||||
|
htmlFor="preparation_unit"
|
||||||
|
className="text-sm font-semibold text-gray-700"
|
||||||
|
>
|
||||||
|
Unit
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="preparation_unit"
|
||||||
|
type="text"
|
||||||
|
value={userData.preparation_unit}
|
||||||
|
onChange={(e) => handleChange("preparation_unit", e.target.value)}
|
||||||
|
className="bg-gray-50 py-6"
|
||||||
|
readOnly={!edit}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label
|
||||||
|
htmlFor="college"
|
||||||
|
className="text-sm font-semibold text-gray-700"
|
||||||
|
>
|
||||||
|
College
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="college"
|
||||||
|
type="text"
|
||||||
|
value={userData.college}
|
||||||
|
onChange={(e) => handleChange("college", e.target.value)}
|
||||||
|
className="bg-gray-50 py-6"
|
||||||
|
readOnly={!edit}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-4">
|
||||||
|
<div className="space-y-2 w-full">
|
||||||
|
<Label
|
||||||
|
htmlFor="ssc_roll"
|
||||||
|
className="text-sm font-semibold text-gray-700"
|
||||||
|
>
|
||||||
|
SSC Roll
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="ssc_roll"
|
||||||
|
type="number"
|
||||||
|
value={userData.ssc_roll}
|
||||||
|
onChange={(e) => handleChange("ssc_roll", Number(e.target.value))}
|
||||||
|
className="bg-gray-50 py-6"
|
||||||
|
readOnly={!edit}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2 w-full">
|
||||||
|
<Label
|
||||||
|
htmlFor="ssc_board"
|
||||||
|
className="text-sm font-semibold text-gray-700"
|
||||||
|
>
|
||||||
|
SSC Board
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="ssc_board"
|
||||||
|
type="text"
|
||||||
|
value={userData.ssc_board}
|
||||||
|
onChange={(e) => handleChange("ssc_board", e.target.value)}
|
||||||
|
className="bg-gray-50 py-6"
|
||||||
|
readOnly={!edit}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-4">
|
||||||
|
<div className="space-y-2 w-full">
|
||||||
|
<Label
|
||||||
|
htmlFor="hsc_roll"
|
||||||
|
className="text-sm font-semibold text-gray-700"
|
||||||
|
>
|
||||||
|
HSC Roll
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="hsc_roll"
|
||||||
|
type="number"
|
||||||
|
value={userData.hsc_roll}
|
||||||
|
onChange={(e) => handleChange("hsc_roll", Number(e.target.value))}
|
||||||
|
className="bg-gray-50 py-6"
|
||||||
|
readOnly={!edit}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2 w-full">
|
||||||
|
<Label
|
||||||
|
htmlFor="hsc_board"
|
||||||
|
className="text-sm font-semibold text-gray-700"
|
||||||
|
>
|
||||||
|
HSC Board
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="hsc_board"
|
||||||
|
type="text"
|
||||||
|
value={userData.hsc_board}
|
||||||
|
onChange={(e) => handleChange("hsc_board", e.target.value)}
|
||||||
|
className="bg-gray-50 py-6"
|
||||||
|
readOnly={!edit}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@ -2,12 +2,16 @@
|
|||||||
|
|
||||||
import React, { createContext, useContext, useState, useEffect } from "react";
|
import React, { createContext, useContext, useState, useEffect } from "react";
|
||||||
import { useRouter, usePathname } from "next/navigation";
|
import { useRouter, usePathname } from "next/navigation";
|
||||||
|
import { UserData } from "@/types/auth";
|
||||||
|
import { API_URL } from "@/lib/auth";
|
||||||
|
|
||||||
interface AuthContextType {
|
interface AuthContextType {
|
||||||
token: string | null;
|
token: string | null;
|
||||||
setToken: (token: string | null) => void;
|
setToken: (token: string | null) => void;
|
||||||
logout: () => void;
|
logout: () => void;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
|
user: UserData | null;
|
||||||
|
fetchUser: () => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||||
@ -32,7 +36,6 @@ const setCookie = (
|
|||||||
if (typeof document === "undefined") return;
|
if (typeof document === "undefined") return;
|
||||||
|
|
||||||
if (value === null) {
|
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`;
|
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Strict; Secure`;
|
||||||
} else {
|
} else {
|
||||||
const expires = new Date();
|
const expires = new Date();
|
||||||
@ -46,22 +49,46 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||||||
}) => {
|
}) => {
|
||||||
const [token, setTokenState] = useState<string | null>(null);
|
const [token, setTokenState] = useState<string | null>(null);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const [user, setUser] = useState<UserData | null>(null);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
|
|
||||||
// Custom setToken function that also updates cookies
|
|
||||||
const setToken = (newToken: string | null) => {
|
const setToken = (newToken: string | null) => {
|
||||||
setTokenState(newToken);
|
setTokenState(newToken);
|
||||||
setCookie("authToken", 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(() => {
|
useEffect(() => {
|
||||||
const initializeAuth = () => {
|
const initializeAuth = async () => {
|
||||||
const storedToken = getCookie("authToken");
|
const storedToken = getCookie("authToken");
|
||||||
|
|
||||||
if (storedToken) {
|
if (storedToken) {
|
||||||
setTokenState(storedToken);
|
setTokenState(storedToken);
|
||||||
|
|
||||||
if (
|
if (
|
||||||
pathname === "/" ||
|
pathname === "/" ||
|
||||||
pathname === "/login" ||
|
pathname === "/login" ||
|
||||||
@ -69,6 +96,9 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||||||
) {
|
) {
|
||||||
router.replace("/home");
|
router.replace("/home");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Fetch user info when token is found
|
||||||
|
await fetchUser();
|
||||||
} else {
|
} else {
|
||||||
const publicPages = ["/", "/login", "/register"];
|
const publicPages = ["/", "/login", "/register"];
|
||||||
if (!publicPages.includes(pathname)) {
|
if (!publicPages.includes(pathname)) {
|
||||||
@ -82,21 +112,22 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||||||
initializeAuth();
|
initializeAuth();
|
||||||
}, [pathname, router]);
|
}, [pathname, router]);
|
||||||
|
|
||||||
// Function to log out
|
|
||||||
const logout = () => {
|
const logout = () => {
|
||||||
setTokenState(null);
|
setTokenState(null);
|
||||||
setCookie("authToken", null); // Remove token from cookies
|
setUser(null);
|
||||||
router.replace("/login"); // Redirect to login screen
|
setCookie("authToken", null);
|
||||||
|
router.replace("/login");
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider value={{ token, setToken, logout, isLoading }}>
|
<AuthContext.Provider
|
||||||
|
value={{ token, setToken, logout, isLoading, user, fetchUser }}
|
||||||
|
>
|
||||||
{children}
|
{children}
|
||||||
</AuthContext.Provider>
|
</AuthContext.Provider>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Hook to use the AuthContext
|
|
||||||
export const useAuth = () => {
|
export const useAuth = () => {
|
||||||
const context = useContext(AuthContext);
|
const context = useContext(AuthContext);
|
||||||
if (!context) {
|
if (!context) {
|
||||||
|
|||||||
4
types/auth.d.ts
vendored
4
types/auth.d.ts
vendored
@ -10,7 +10,7 @@ export interface UserData {
|
|||||||
hsc_roll: number;
|
hsc_roll: number;
|
||||||
hsc_board: string;
|
hsc_board: string;
|
||||||
college: string;
|
college: string;
|
||||||
preparation_unit: "Science" | "Arts" | "Commerce" | string;
|
preparation_unit: "Science" | "Humanities" | "Business" | string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RegisterForm {
|
export interface RegisterForm {
|
||||||
@ -24,7 +24,7 @@ export interface RegisterForm {
|
|||||||
hsc_roll: number;
|
hsc_roll: number;
|
||||||
hsc_board: string;
|
hsc_board: string;
|
||||||
college: string;
|
college: string;
|
||||||
preparation_unit: "Science" | "Arts" | "Commerce" | string;
|
preparation_unit: "Science" | "Humanities" | "Business" | string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LoginForm {
|
export interface LoginForm {
|
||||||
|
|||||||
Reference in New Issue
Block a user