0

I am trying to logout users that is blocked by admin wh

If the user is not logged in and is blacklisted by admin then he is unable to log in this is done but what I want is if user is already logged in and admin block that user the subsequent request he try to access any private route he will be kicked out , this all logic is working perfectly in development server as pages are not cached but on vercel deployment app didn't behave as expected where app kick out the blocked user when user refresh app if he is already logged in but didn't kick out if the accessing any route what I got is this behavior is happening because of nextjs cache

here is my code

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { getDataFromToken, getLatestDataOFActiveUser } from './helpers/auth'



export async function middleware(request: NextRequest) {
    const token = request.cookies.get('token')?.value || ''

    const userData = await getDataFromToken(request)
    console.log(" ~ file: middleware.ts:13 ~ middleware ~ userData:", userData)

    // black list validation
    const isBlackList = await getLatestDataOFActiveUser(request);



 

    // admin validation

    if (
           request.nextUrl.pathname === '/admin/home'
        || request.nextUrl.pathname === '/admin/profile'
        || request.nextUrl.pathname === '/admin/category'
        || request.nextUrl.pathname === '/admin/category/add-category'
        || request.nextUrl.pathname === '/admin/category/update-category'
        || request.nextUrl.pathname === '/admin/users'
        || request.nextUrl.pathname === '/admin/vendor'
    ) {
        if (token === '' || userData === null || userData?.role !== 'admin') {
            return NextResponse.redirect(new URL('/auth/login', request.url))
        }
    }


    if (request.nextUrl.pathname === '/auth/login' || request.nextUrl.pathname === '/auth/register') {
        if ((token !== '' || !token) && userData !== null && userData?.role === 'admin') {
            return NextResponse.redirect(new URL('/admin/home', request.url))
        }
    }


    // customer validation
    const isUserAccount = request.nextUrl.pathname === '/customer/account';
    const isUserCart = request.nextUrl.pathname === '/customer/cart';

    if (isBlackList && ( isUserAccount || isUserCart)  ) {
        let i = 0;
        console.log('i run ' ,  i++)

        return NextResponse.redirect(new URL('/auth/login', request.url))
    }


    if (request.nextUrl.pathname === '/auth/login' || request.nextUrl.pathname === '/auth/register') {
        if ((token !== '' || !token) && (userData !== null && !isBlackList)) {
            return NextResponse.redirect(new URL('/customer/account', request.url))
        }
    }

    if (isUserAccount || isUserCart) {
        if (token === '' || userData === null || (userData?.role !== 'customer' && userData?.role !== 'vendor')  ) {
            return NextResponse.redirect(new URL('/auth/login', request.url))
        }
    }
}


export const config = {
    matcher: [
        '/admin/:path*',
        '/auth/login',
        '/auth/register',
        '/',
        '/customer/account',
        '/customer/cart',
    ],
}

HELPERS

import { NextRequest } from "next/server";
import * as jose from 'jose'
import User from "@/models/User";

export const getDataFromToken = async (request: NextRequest) => {
    try {
        const token = request.cookies.get("token")?.value || '';
        if (!token || token === undefined) return null
        const privateKey = process.env.TOKEN_SECRET! ?? 'dumbScrete' as string
        const decodedToken = await jose.jwtVerify(token, Buffer.from(privateKey, 'utf-8'), {
            algorithms: ["HS256"],
        });
        return decodedToken.payload;
    } catch (error: any) {
        if (error instanceof Error && error.name === 'JWSError') {
            console.log('JWT verification error:', error.message);
        } else if (error instanceof Error && error.name === 'JWSInvalid') {
            console.log('JWT invalid  error:', error.message);
        } else {
            console.log('Error decoding JWT:', error);
        }
        return null;
    }
}


export const getLatestDataOFActiveUser = async (request : NextRequest) => {
    const validateToken  = await getDataFromToken(request);

    if(validateToken === null) return false;

    const userID =  validateToken.id;

    try {
        const res = await fetch(`${process.env.domain}/api/auth/blackListUserTracking?userID=${userID}`, {
            method: 'GET',
        })        
        const data = await res.json();
        if(data?.success){
            const isBlackListUser =  data?.data?.isBlackList;
            return isBlackListUser;
        }else{
            return false;
        }
    } catch (error) {
        console.log('error in getting User data (helper) => ', error);
        return false
    }
}

Abdullah moiz
  • 112
  • 1
  • 8

0 Answers0