@maxlkatze/cms
Version:
A git based Nuxt Module CMS - zero effort, zero cost
50 lines (49 loc) • 1.56 kB
JavaScript
import { useAuthentication } from "../composables/cms/useAuthentication.js";
import { defineNuxtRouteMiddleware, useCookie, useRuntimeConfig } from "#imports";
export default defineNuxtRouteMiddleware(async (to) => {
const checkAuth = import.meta.client ? clientSideAuthentication : serverSideAuthentication;
if (to.path === "/cms") {
if (await checkAuth()) {
if (import.meta.client) {
window.location.href = "/cms/dashboard";
}
return "/cms/dashboard";
}
return;
}
if (to.path.startsWith("/cms")) {
if (!await checkAuth()) {
if (import.meta.client) {
window.location.href = "/cms";
}
return "/cms";
}
return;
}
});
const serverSideAuthentication = async () => {
const token = useCookie("auth_token");
if (!token.value) return false;
const runtimeConfig = useRuntimeConfig();
const authentication = useAuthentication();
return await authentication.verifyToken(token.value, runtimeConfig.secret || "");
};
const clientSideAuthentication = async () => {
const tokenCookie = useCookie("auth_token");
const authentication = useAuthentication();
const tokenValue = tokenCookie.value || authentication.getToken();
if (!tokenValue) return false;
try {
const authResponse = await $fetch("/cms/api/auth", {
method: "POST",
body: {
action: "verify",
token: tokenValue
}
});
return authResponse.success === true;
} catch (error) {
console.error("Authentication verification failed:", error);
return false;
}
};