utils von SettingsModal ausgelagert
This commit is contained in:
44
components/header/settingsModal/hooks/useAdminAuth.ts
Normal file
44
components/header/settingsModal/hooks/useAdminAuth.ts
Normal 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 };
|
||||
}
|
||||
Reference in New Issue
Block a user