Untitled

 avatar
unknown
javascript
a month ago
3.4 kB
3
Indexable
import { NextResponse } from "next/server";
import { isAuthRedirectPage, isAuthRequiredPage } from "@/middlewares/utils/auth-page-check";

const authMiddleware = async (req) => {
    const { url, nextUrl, cookies } = req;
    const { value: token } = cookies.get("token") ?? { value: null };
    const { value: i18next } = cookies.get("i18next") ?? { value: 'de' };

    const isAuthRequired = isAuthRequiredPage(nextUrl.pathname);
    const isAuthRedirect = isAuthRedirectPage(nextUrl.pathname);

    try {
        if(isAuthRequired && token) {
            const auth = await fetch(`${process.env.SERVER_API_URL}/user/auth/check`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                cache: 'no-store'
            });

            if (auth.status !== 200) {
                const response = NextResponse.redirect(nextUrl);
                response.cookies.set("token", "", {
                    path: "/",
                    maxAge: 0,
                    domain: ".wastestop.de",
                    httpOnly: true,
                    secure: true,
                    sameSite: "Lax"
                });
                return response;
            } else {
                const data = await auth.json();

                if (data.phone === false) {
                    const phoneTargetUrl = new URL(`/${i18next}/phone-verification`, url);
                    if (nextUrl.pathname !== phoneTargetUrl.pathname) {
                        return NextResponse.redirect(phoneTargetUrl);
                    }
                    return NextResponse.next();
                } else if (data.phone === true && nextUrl.pathname === `/${i18next}/phone-verification`) {
                    return NextResponse.redirect(new URL(`/${i18next}`, url));
                }

                if (data.email === false) {
                    const emailTargetUrl = new URL(`/${i18next}/email/notice`, url);
                    const verifyUrlPrefix = `/${i18next}/email/verify`;
                    if (nextUrl.pathname !== emailTargetUrl.pathname && !nextUrl.pathname.startsWith(verifyUrlPrefix)) {
                        return NextResponse.redirect(emailTargetUrl);
                    }
                    return NextResponse.next();
                } else if (data.email === true && (nextUrl.pathname === `/${i18next}/email/notice` || nextUrl.pathname.startsWith(`/${i18next}/email/verify`))) {
                    return NextResponse.redirect(new URL(`/${i18next}`, url));
                }

                return NextResponse.next();
            }
        }

        if (isAuthRequired && !token) {
            const searchParams = new URLSearchParams(nextUrl.searchParams);
            searchParams.set("nextUrl", nextUrl.pathname);

            return NextResponse.redirect(
                new URL(`/${i18next}/login?${searchParams}`, url)
            );
        }

        if (isAuthRedirect && token) {
            return NextResponse.redirect(new URL(`/${i18next}`, url));
        }

        return NextResponse.next();
    } catch (error) {
        console.error("An error occurred while fetching auth:", error);
    }
}

export default authMiddleware;
Editor is loading...
Leave a Comment