utils von SettingsModal ausgelagert

This commit is contained in:
ISA
2025-02-24 08:34:38 +01:00
parent 69b825bd30
commit d901289c8d
5 changed files with 108 additions and 122 deletions

View File

@@ -0,0 +1,44 @@
// components/header/settingsModal/hooks/useAdminAuth.ts
import { useState, useEffect } from "react";
import CryptoJS from "crypto-js";
function decryptToken(encryptedToken: string) {
const encryptionKey = process.env.NEXT_PUBLIC_ENCRYPTION_KEY;
const encryptionIV = process.env.NEXT_PUBLIC_ENCRYPTION_IV;
if (!encryptionKey || !encryptionIV) {
throw new Error("Encryption key or IV is not defined.");
}
const key = CryptoJS.enc.Utf8.parse(encryptionKey);
const iv = CryptoJS.enc.Utf8.parse(encryptionIV);
const bytes = CryptoJS.AES.decrypt(encryptedToken, key, { iv });
return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
}
export function useAdminAuth(showModal: boolean) {
const [isAdminLoggedIn, setAdminLoggedIn] = useState(false);
useEffect(() => {
if (showModal) {
const token = sessionStorage.getItem("token");
if (token) {
try {
const { exp } = decryptToken(token);
if (Date.now() < exp) {
setAdminLoggedIn(true);
} else {
sessionStorage.removeItem("token");
setAdminLoggedIn(false);
}
} catch (error) {
console.error("Token-Entschlüsselung fehlgeschlagen:", error);
setAdminLoggedIn(false);
}
}
}
}, [showModal]);
return { isAdminLoggedIn, setAdminLoggedIn };
}