duckil_plm/fems-app/src/hooks/useAuth.ts

46 lines
990 B
TypeScript
Raw Normal View History

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";
2024-11-02 18:01:31 +09:00
import Cookies from "js-cookie";
2024-11-02 07:15:56 +09:00
import { api } from "@/lib/api";
export function useAuth() {
const router = useRouter();
const { user, token, setAuth, clearAuth } = useAuthStore();
2024-11-02 18:01:31 +09:00
// console.log("user", user);
2024-11-02 07:15:56 +09:00
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-02 07:15:56 +09:00
setAuth(data.user, data.token);
2024-11-02 18:01:31 +09:00
// console.log("data", data);
// Set the token in a cookie
Cookies.set("token", data.token, { path: "/" });
router.push("/dashboard/overview"); // 그룹 이름 제거
2024-11-02 07:15:56 +09:00
} catch (error) {
throw error;
}
};
const logout = () => {
clearAuth();
router.push("/login");
};
return { user, token, login, logout };
}