This commit is contained in:
headlesdev
2025-05-19 16:51:32 +02:00
parent 59a32e0407
commit 2dea29287a
3 changed files with 71 additions and 29 deletions

59
hooks/useAuth.ts Normal file
View File

@@ -0,0 +1,59 @@
import { useState, useEffect, useCallback } from "react";
import axios from "axios";
import Cookies from "js-cookie";
import { useRouter } from "next/navigation";
const useAuth = () => {
const [validated, setValidated] = useState(false);
const [loading, setLoading] = useState(true);
const [username, setUsername] = useState("");
const [name, setName] = useState("");
const router = useRouter();
const validate = useCallback(async () => {
setLoading(true);
try {
const token = Cookies.get("token");
if (!token) {
setLoading(false);
setValidated(false);
router.push("/");
return;
}
const response = await axios.post("/api/user/validate", { token });
if (response.data.message === "Valid") {
setValidated(true);
setUsername(response.data.username);
setName(response.data.name);
} else {
setValidated(false);
Cookies.remove("token");
router.push("/");
}
} catch (error) {
console.error("Validation error:", error);
setValidated(false);
Cookies.remove("token");
router.push("/");
} finally {
setLoading(false);
}
}, [router]);
useEffect(() => {
validate();
}, [validate]);
return {
validated,
loading,
username,
name,
validate
};
}
export default useAuth;