42 lines
1.3 KiB
TypeScript
42 lines
1.3 KiB
TypeScript
import { createContext, useContext, type ReactNode } from "react";
|
|
import { useAuth as useApplicationAuth } from "~/contexts/auth-context";
|
|
import type { CurrentUser } from "../types";
|
|
|
|
type AuthValue = {
|
|
user: CurrentUser | null;
|
|
loading: boolean;
|
|
login: (userName: string, password: string) => Promise<void>;
|
|
logout: () => Promise<void>;
|
|
};
|
|
|
|
const AuthContext = createContext<AuthValue | null>(null);
|
|
|
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
const auth = useApplicationAuth();
|
|
const user: CurrentUser | null = auth.user
|
|
? {
|
|
id: auth.user.id,
|
|
userName: auth.user.username,
|
|
displayName: [auth.user.name, auth.user.family].filter(Boolean).join(" ") || auth.user.username,
|
|
roles: auth.user.roles,
|
|
}
|
|
: null;
|
|
|
|
async function login(userName: string, password: string) {
|
|
const succeeded = await auth.login(userName, password);
|
|
if (!succeeded) throw new Error("ورود ناموفق بود.");
|
|
}
|
|
|
|
return (
|
|
<AuthContext.Provider value={{ user, loading: auth.isLoading, login, logout: auth.logout }}>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useAuth() {
|
|
const value = useContext(AuthContext);
|
|
if (!value) throw new Error("AuthProvider is missing");
|
|
return value;
|
|
}
|