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 { RegisterForm } from "@/types/auth";
|
||||
|
||||
interface ValidationErrorItem {
|
||||
type: string;
|
||||
loc: string[];
|
||||
msg: string;
|
||||
input?: unknown;
|
||||
ctx?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface CustomError extends Error {
|
||||
response?: {
|
||||
detail?: string;
|
||||
detail?: string | ValidationErrorItem;
|
||||
};
|
||||
}
|
||||
|
||||
@ -36,16 +44,27 @@ export default function RegisterPage() {
|
||||
});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleError = (error: { detail: string }) => {
|
||||
if (error?.detail) {
|
||||
const match = error.detail.match(/Key \((.*?)\)=\((.*?)\)/);
|
||||
if (match) {
|
||||
const field = match[1];
|
||||
return `The ${field} already exists. Please try again.`;
|
||||
function formatError(error: unknown): string {
|
||||
if (error && typeof error === "object" && "response" in (error as any)) {
|
||||
const customError = error as CustomError;
|
||||
const detail = customError.response?.detail;
|
||||
|
||||
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 { ssc_roll, hsc_roll, password } = form;
|
||||
@ -69,31 +88,12 @@ export default function RegisterPage() {
|
||||
|
||||
try {
|
||||
await register(form, setToken);
|
||||
router.push("/home");
|
||||
} catch (error) {
|
||||
// Type guard for built-in Error type
|
||||
if (error instanceof Error) {
|
||||
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.");
|
||||
}
|
||||
router.push("/login");
|
||||
} catch (err: unknown) {
|
||||
setError(formatError(err));
|
||||
console.error("User creation error: ", err);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<BackgroundWrapper>
|
||||
<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 { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
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 React, { useEffect, useState } from "react";
|
||||
import { UserData } from "@/types/auth";
|
||||
@ -85,7 +92,22 @@ const ProfilePage = () => {
|
||||
</AvatarFallback>
|
||||
</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
|
||||
userData={userData}
|
||||
edit={editStatus}
|
||||
|
||||
@ -2,8 +2,8 @@
|
||||
|
||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { API_URL, getToken } from "@/lib/auth";
|
||||
import { UserData } from "@/types/auth";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { clearAuthToken } from "@/lib/auth";
|
||||
import {
|
||||
Bookmark,
|
||||
ChartColumn,
|
||||
@ -19,49 +19,16 @@ import {
|
||||
UserCircle2,
|
||||
} from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import React from "react";
|
||||
|
||||
const SettingsPage = () => {
|
||||
const router = useRouter();
|
||||
const [userData, setUserData] = useState<UserData>({
|
||||
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",
|
||||
});
|
||||
const { user, isLoading } = useAuth();
|
||||
|
||||
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);
|
||||
function handleLogout() {
|
||||
clearAuthToken();
|
||||
router.replace("/");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching user data: ", error);
|
||||
}
|
||||
}
|
||||
|
||||
fetchUser();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<BackgroundWrapper>
|
||||
@ -81,16 +48,14 @@ const SettingsPage = () => {
|
||||
<div className="flex gap-4 items-center">
|
||||
<Avatar className="bg-[#113768] w-20 h-20">
|
||||
<AvatarFallback className="text-3xl text-white">
|
||||
{userData?.username
|
||||
? userData.username.charAt(0).toUpperCase()
|
||||
{user?.username
|
||||
? user.username.charAt(0).toUpperCase()
|
||||
: ""}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex flex-col items-start">
|
||||
<h1 className="font-semibold text-2xl">
|
||||
{userData?.full_name}
|
||||
</h1>
|
||||
<h3 className=" text-md">{userData?.email}</h3>
|
||||
<h1 className="font-semibold text-2xl">{user?.full_name}</h1>
|
||||
<h3 className=" text-md">{user?.email}</h3>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@ -181,7 +146,7 @@ const SettingsPage = () => {
|
||||
</div>
|
||||
<ChevronRight size={30} color="#113768" />
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<button onClick={handleLogout} className="flex justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<LogOut size={30} color="#113768" />
|
||||
<h3 className="text-md font-medium text-[#113768]">
|
||||
@ -189,7 +154,7 @@ const SettingsPage = () => {
|
||||
</h3>
|
||||
</div>
|
||||
<ChevronRight size={30} color="#113768" />
|
||||
</div>
|
||||
</button>
|
||||
<div className="h-[0.5px] border-[0.1px] w-full border-[#113768]/20"></div>
|
||||
<p className="text-center text-[#113768]/50 font-medium">
|
||||
ExamJam | Version 1.0
|
||||
|
||||
@ -6,8 +6,7 @@ import styles from "@/css/Header.module.css";
|
||||
import { useExam } from "@/context/ExamContext";
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { useModal } from "@/context/ModalContext";
|
||||
import { API_URL, getToken } from "@/lib/auth";
|
||||
import { UserData } from "@/types/auth";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
|
||||
interface HeaderProps {
|
||||
displayUser?: boolean;
|
||||
@ -29,7 +28,7 @@ const Header = ({
|
||||
examDuration ? parseInt(examDuration) * 60 : 0
|
||||
);
|
||||
const { stopTimer } = useTimer();
|
||||
const [userData, setUserData] = useState<UserData>();
|
||||
const { user, isLoading } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
if (!examDuration) return;
|
||||
@ -47,33 +46,6 @@ const Header = ({
|
||||
return () => clearInterval(timer);
|
||||
}, [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 minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
@ -100,13 +72,11 @@ const Header = ({
|
||||
<div className={styles.profile}>
|
||||
<Avatar className="bg-gray-200 w-10 h-10">
|
||||
<AvatarFallback className=" text-lg">
|
||||
{userData?.username
|
||||
? userData.username.charAt(0).toUpperCase()
|
||||
: ""}
|
||||
{user?.username ? user.username.charAt(0).toUpperCase() : ""}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className={styles.text}>
|
||||
Hello, {userData?.username ? userData.username.split(" ")[0] : ""}
|
||||
Hello, {user?.username ? user.username.split(" ")[0] : ""}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@ -19,10 +19,15 @@ export default function ProfileManager({
|
||||
setUserData((prev) => (prev ? { ...prev, [field]: value } : prev));
|
||||
};
|
||||
|
||||
console.log(userData);
|
||||
|
||||
return (
|
||||
<div className="mx-auto">
|
||||
<div className="space-y-4">
|
||||
{/* Full Name */}
|
||||
<h1 className="text-xl font-semibold tracking-tight">
|
||||
Personal Information
|
||||
</h1>
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="full_name"
|
||||
@ -39,61 +44,24 @@ export default function ProfileManager({
|
||||
readOnly={!edit}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* College */}
|
||||
<div className="space-y-2">
|
||||
<Label
|
||||
htmlFor="college"
|
||||
htmlFor="username"
|
||||
className="text-sm font-semibold text-gray-700"
|
||||
>
|
||||
College
|
||||
Username
|
||||
</Label>
|
||||
<Input
|
||||
id="college"
|
||||
id="username"
|
||||
type="text"
|
||||
value={userData.college}
|
||||
onChange={(e) => handleChange("college", e.target.value)}
|
||||
value={userData.username}
|
||||
onChange={(e) => handleChange("username", e.target.value)}
|
||||
className="bg-gray-50 py-6"
|
||||
readOnly={!edit}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 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 */}
|
||||
<div className="space-y-2">
|
||||
@ -130,6 +98,111 @@ export default function ProfileManager({
|
||||
readOnly={!edit}
|
||||
/>
|
||||
</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>
|
||||
);
|
||||
|
||||
@ -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) {
|
||||
|
||||
4
types/auth.d.ts
vendored
4
types/auth.d.ts
vendored
@ -10,7 +10,7 @@ export interface UserData {
|
||||
hsc_roll: number;
|
||||
hsc_board: string;
|
||||
college: string;
|
||||
preparation_unit: "Science" | "Arts" | "Commerce" | string;
|
||||
preparation_unit: "Science" | "Humanities" | "Business" | string;
|
||||
}
|
||||
|
||||
export interface RegisterForm {
|
||||
@ -24,7 +24,7 @@ export interface RegisterForm {
|
||||
hsc_roll: number;
|
||||
hsc_board: string;
|
||||
college: string;
|
||||
preparation_unit: "Science" | "Arts" | "Commerce" | string;
|
||||
preparation_unit: "Science" | "Humanities" | "Business" | string;
|
||||
}
|
||||
|
||||
export interface LoginForm {
|
||||
|
||||
Reference in New Issue
Block a user