CoreControl/hooks/useAuth.ts

63 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-05-19 16:51:32 +02:00
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("");
2025-05-20 00:52:17 +02:00
const [email, setEmail] = useState("");
2025-05-19 16:51:32 +02:00
const router = useRouter();
const validate = useCallback(async () => {
setLoading(true);
try {
const token = Cookies.get("token");
if (!token) {
setLoading(false);
setValidated(false);
router.push("/");
2025-05-20 00:52:17 +02:00
return "Invalid";
2025-05-19 16:51:32 +02:00
}
const response = await axios.post("/api/user/validate", { token });
if (response.data.message === "Valid") {
setValidated(true);
setUsername(response.data.username);
setName(response.data.name);
2025-05-20 00:52:17 +02:00
setEmail(response.data.email);
return "Validated";
2025-05-19 16:51:32 +02:00
} else {
setValidated(false);
Cookies.remove("token");
router.push("/");
2025-05-20 00:52:17 +02:00
return "Invalid";
2025-05-19 16:51:32 +02:00
}
} catch (error) {
console.error("Validation error:", error);
setValidated(false);
Cookies.remove("token");
router.push("/");
2025-05-20 00:52:17 +02:00
return "Invalid";
2025-05-19 16:51:32 +02:00
} finally {
setLoading(false);
}
}, [router]);
useEffect(() => {
validate();
}, [validate]);
return {
validated,
loading,
username,
name,
2025-05-20 00:52:17 +02:00
email,
2025-05-19 16:51:32 +02:00
validate
};
}
export default useAuth;