From 79e8f999577d580d243c75f282930134a9a1e26e Mon Sep 17 00:00:00 2001 From: Nimit Date: Tue, 18 Jun 2024 01:02:17 +0530 Subject: [PATCH] added check for mobile device --- src/lib/middleware-utils.ts | 16 +++++++++++++++- src/middleware.ts | 10 ++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/lib/middleware-utils.ts b/src/lib/middleware-utils.ts index 8ee02c6bd..d2cdf3d6f 100644 --- a/src/lib/middleware-utils.ts +++ b/src/lib/middleware-utils.ts @@ -1,6 +1,6 @@ import { importJWK, jwtVerify } from 'jose'; import { NextRequestWithAuth, withAuth } from 'next-auth/middleware'; -import { NextResponse } from 'next/server'; +import { NextRequest, NextResponse, userAgent } from 'next/server'; const PRIVATE_MOBILE_ROUTES = ['/api/auth/mobile/logout']; const SINGLE_USER_ROUTES = ['/courses', '/questions', '/bookmarks']; @@ -52,3 +52,17 @@ export const nextAuthMiddleware = withAuth(async (req) => { } } }); + +export const getDeviceType = (request: NextRequest) => { + const { device } = userAgent(request); + return device.type; +}; + +export const isMobile = (request: NextRequest) => { + const deviceType = getDeviceType(request); + return deviceType === 'mobile' || deviceType === 'tablet'; +}; + +export const isDesktop = (request: NextRequest) => { + return !isMobile(request); +}; diff --git a/src/middleware.ts b/src/middleware.ts index 5fe422898..329c61ced 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,6 +1,10 @@ import { NextRequestWithAuth } from 'next-auth/middleware'; import { NextResponse } from 'next/server'; -import { handleMobileAuth, nextAuthMiddleware } from './lib/middleware-utils'; +import { + handleMobileAuth, + isMobile, + nextAuthMiddleware, +} from './lib/middleware-utils'; const PUBLIC_ROUTES = [ '/', @@ -20,7 +24,9 @@ export async function middleware(request: NextRequestWithAuth) { } // Mobile Auth - await handleMobileAuth(request); + if (isMobile(request)) { + return await handleMobileAuth(request); + } /* NextJS Auth - Other public routes