81 lines
2.0 KiB
TypeScript
81 lines
2.0 KiB
TypeScript
"use client";
|
|
import { ROUTES } from "@/lib/routes";
|
|
|
|
import React, {
|
|
createContext,
|
|
useContext,
|
|
useState,
|
|
useEffect,
|
|
ReactNode,
|
|
} from "react";
|
|
import { useRouter } from "next/navigation";
|
|
|
|
export interface User {
|
|
id: number;
|
|
username: string;
|
|
name: string;
|
|
role: "employee" | "manager";
|
|
leaveBalance?: number;
|
|
}
|
|
|
|
interface AuthContextType {
|
|
user: User | null;
|
|
login: (
|
|
username: string,
|
|
password: string,
|
|
) => Promise<{ ok: boolean; error?: string }>;
|
|
logout: () => void;
|
|
isLoading: boolean;
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextType | null>(null);
|
|
|
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
const [user, setUser] = useState<User | null>(null);
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
const router = useRouter();
|
|
|
|
useEffect(() => {
|
|
const stored = localStorage.getItem("lms_user");
|
|
if (stored) {
|
|
try {
|
|
setUser(JSON.parse(stored));
|
|
} catch {}
|
|
}
|
|
setIsLoading(false);
|
|
}, []);
|
|
|
|
const login = async (username: string, password: string) => {
|
|
const mod = await import("@/data/users.json");
|
|
const raw = mod.default ?? mod;
|
|
const users: any[] = Array.isArray(raw) ? raw : ((raw as any).users ?? []);
|
|
const found = users.find(
|
|
(u) => u.username === username && u.password === password,
|
|
);
|
|
if (!found) return { ok: false, error: "Invalid username or password" };
|
|
const { password: _pw, ...safeUser } = found;
|
|
setUser(safeUser);
|
|
localStorage.setItem("lms_user", JSON.stringify(safeUser));
|
|
return { ok: true };
|
|
};
|
|
|
|
const logout = () => {
|
|
setUser(null);
|
|
localStorage.removeItem("lms_user");
|
|
// router.push("/");
|
|
router.push(ROUTES.home);
|
|
};
|
|
|
|
return (
|
|
<AuthContext.Provider value={{ user, login, logout, isLoading }}>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useAuth() {
|
|
const ctx = useContext(AuthContext);
|
|
if (!ctx) throw new Error("useAuth must be used inside AuthProvider");
|
|
return ctx;
|
|
}
|