2024-11-02 07:15:56 +09:00
|
|
|
// src/hooks/useAuth.ts
|
2024-11-02 18:01:31 +09:00
|
|
|
"use client";
|
|
|
|
|
2024-11-02 07:15:56 +09:00
|
|
|
import { useRouter } from "next/navigation";
|
|
|
|
import { useAuthStore } from "@/stores/auth";
|
|
|
|
import { api } from "@/lib/api";
|
|
|
|
|
|
|
|
export function useAuth() {
|
|
|
|
const router = useRouter();
|
|
|
|
const { user, token, setAuth, clearAuth } = useAuthStore();
|
|
|
|
|
|
|
|
const login = async ({
|
|
|
|
username,
|
|
|
|
password,
|
|
|
|
}: {
|
|
|
|
username: string;
|
|
|
|
password: string;
|
|
|
|
}) => {
|
|
|
|
try {
|
2024-11-02 18:01:31 +09:00
|
|
|
const { data } = await api.post("/api/v1/app/auth/login", {
|
|
|
|
username,
|
|
|
|
password,
|
|
|
|
});
|
2024-11-03 15:56:16 +09:00
|
|
|
|
|
|
|
// Zustand store에 저장
|
2024-11-02 07:15:56 +09:00
|
|
|
setAuth(data.user, data.token);
|
2024-11-02 18:01:31 +09:00
|
|
|
|
2024-11-03 15:56:16 +09:00
|
|
|
// localStorage에도 저장
|
|
|
|
localStorage.setItem("token", data.token);
|
2024-11-02 18:01:31 +09:00
|
|
|
|
2024-11-03 15:56:16 +09:00
|
|
|
router.push("/dashboard/overview");
|
2024-11-02 07:15:56 +09:00
|
|
|
} catch (error) {
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const logout = () => {
|
|
|
|
clearAuth();
|
2024-11-03 15:56:16 +09:00
|
|
|
localStorage.removeItem("token");
|
2024-11-02 07:15:56 +09:00
|
|
|
router.push("/login");
|
|
|
|
};
|
|
|
|
|
|
|
|
return { user, token, login, logout };
|
|
|
|
}
|