added authentication

This commit was merged in pull request #7.
This commit is contained in:
2023-10-21 03:06:58 -07:00
parent ed2ebe41e6
commit c48c959749
7 changed files with 327 additions and 55 deletions
+44 -9
View File
@@ -1,12 +1,32 @@
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
const checkAuthentication = async () => {
// Replace this logic with your actual authentication check.
const isAuthenticated = false; // Check if the user is authenticated.
const token = req.cookies["cmc-token"]; // Access the token from cookies
console.log("checking token", token);
const isAuthenticated = token ? true : false; // Check if the user is authenticated.
return isAuthenticated;
};
const isTokenValid = () => {
const cookies = document.cookie.split("; "); // Get all cookies and split them into an array
for (const cookie of cookies) {
const [name, value] = cookie.split("="); // Split the cookie into its name and value
if (name === "cmc-token" && value) {
return true; // The cmc-token cookie exists
}
}
return false; // The cmc-token cookie does not exist
};
export async function middleware(req) {
const token = isTokenValid()
// req.cookies["cmc-token"]; // Access the token from cookies
const cookieList = cookies();
const headers = new Headers(req.headers);
headers.set("X-XSS-Protection", "1; mode=block");
headers.set("X-Frame-Options", "SAMEORIGIN");
@@ -15,16 +35,31 @@ export async function middleware(req) {
const { origin, pathname } = req.nextUrl;
try {
const authenticated = await checkAuthentication();
if (pathname === "/auth/login" && authenticated) {
return NextResponse.redirect(new URL("/ecommerce"));
if (pathname === "/auth/login" && token) {
// Redirect to the home page if already authenticated
return NextResponse.redirect(new URL("/"), { status: 307 });
}
if (authenticationPages.includes(pathname) && !authenticated) {
return NextResponse.redirect(new URL("/auth/login", origin));
if (!authenticationPages.includes(pathname) && !token) {
// Redirect to the login page if not authenticated
return NextResponse.redirect(new URL("/auth/login", origin), {
status: 307,
});
}
// Add authentication logic here (verify the token, etc.)
// const isAuthenticated = verifyToken(token);
const isAuthenticated = cookieList.has("cmc-token");
console.log(token)
if (!isAuthenticated) {
// Handle unauthenticated users
return NextResponse.error(new Error("Authentication failed"), {
status: 401,
});
}
// Continue with the request if authenticated
return NextResponse.next();
} catch (error) {
console.error("Error during authentication check:", error);
@@ -37,7 +72,7 @@ export const config = {
};
const authenticationPages = [
"/",
// "/",
"/auth",
"/auth/login",
"/auth/sign-up",