%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/contexts/
Upload File :
Create Path :
Current File : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/contexts/AuthContext.tsx

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from "react";
import { apiRequest } from "@/lib/api";
import type { AuthResponse, User } from "@/types/api";

interface AuthContextValue {
  user: User | null;
  isLoading: boolean;
  login: (email: string, password: string) => Promise<void>;
  setPassword: (password: string, currentPassword?: string) => Promise<void>;
  completeOAuth: (code: string, state: string) => Promise<User>;
  logout: () => Promise<void>;
  updateUser: (user: User) => void;
}

const AuthContext = createContext<AuthContextValue | null>(null);

export function AuthProvider({ children }: { children: ReactNode }) {
  // Sesu disimpan di cookie HttpOnly di backend — browser mengirimnya otomatis.
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // Validasi sesi (cookie) saat aplikasi dimuat.
  useEffect(() => {
    let cancelled = false;
    apiRequest<{ user: User }>("/auth/me")
      .then((res) => {
        if (!cancelled) setUser(res.user);
      })
      .catch(() => {
        if (!cancelled) setUser(null);
      })
      .finally(() => {
        if (!cancelled) setIsLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  const login = useCallback(async (email: string, password: string) => {
    const res = await apiRequest<AuthResponse>("/auth/login", {
      method: "POST",
      body: { email, password },
    });
    setUser(res.user);
  }, []);

  const setPassword = useCallback(
    async (password: string, currentPassword?: string) => {
      const res = await apiRequest<{ user: User }>("/me/password", {
        method: "POST",
        body: currentPassword
          ? { password, current_password: currentPassword }
          : { password },
      });
      setUser(res.user);
    },
    [],
  );

  const completeOAuth = useCallback(async (code: string, state: string) => {
    const res = await apiRequest<AuthResponse>("/auth/google/callback", {
      method: "POST",
      body: { code, state },
    });
    setUser(res.user);
    return res.user;
  }, []);

  const logout = useCallback(async () => {
    // Best-effort: invalidasi session di backend (via cookie), abaikan error.
    await apiRequest("/auth/logout", { method: "POST" }).catch(
      () => undefined,
    );
    setUser(null);
  }, []);

  const updateUser = useCallback((next: User) => {
    setUser(next);
  }, []);

  const value = useMemo(
    () => ({ user, isLoading, login, setPassword, completeOAuth, logout, updateUser }),
    [user, isLoading, login, setPassword, completeOAuth, logout, updateUser],
  );

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

export function useAuth(): AuthContextValue {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error("useAuth harus dipakai di dalam <AuthProvider>");
  return ctx;
}

Zerion Mini Shell 1.0