From f92aae620cbe05e7b3030f9ad843fc0d173cff53 Mon Sep 17 00:00:00 2001 From: Meier Lukas Date: Sat, 21 Oct 2023 10:41:45 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20device-id=20cookie=20for=20fu?= =?UTF-8?q?ture=20selection=20of=20default=20layout=20per=20device?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- data/constants.ts | 1 + src/middleware.ts | 28 +++++++++++++++++++++++----- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/data/constants.ts b/data/constants.ts index 6c43f365d..e7b27b3a5 100644 --- a/data/constants.ts +++ b/data/constants.ts @@ -2,3 +2,4 @@ export const REPO_URL = 'ajnart/homarr'; export const ICON_PICKER_SLICE_LIMIT = 36; export const COOKIE_LOCALE_KEY = 'config-locale'; export const COOKIE_COLOR_SCHEME_KEY = 'color-scheme'; +export const COOKIE_DEVICE_ID_KEY = 'deviceId'; diff --git a/src/middleware.ts b/src/middleware.ts index 7855ccb27..93420cb5f 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,9 +1,10 @@ import { NextRequest, NextResponse } from 'next/server'; import { env } from 'process'; +import { v4 } from 'uuid'; +import { COOKIE_DEVICE_ID_KEY } from '../data/constants'; import { getUrl } from './tools/server/url'; import { client } from './utils/api'; -import { isMobileUserAgent } from './validations/mobile'; const skippedUrls = [ '/onboard', @@ -19,20 +20,21 @@ let cachedUserCount = 0; export async function middleware(req: NextRequest) { const url = req.nextUrl.clone(); + const deviceId = req.cookies.get(COOKIE_DEVICE_ID_KEY)?.value ?? null; // Do not redirect if the url is in the skippedUrls array if (skippedUrls.some((skippedUrl) => url.pathname.startsWith(skippedUrl))) { - return NextResponse.next(); + return HomarrResponse.next(deviceId); } // Do not redirect if we are on Vercel if (env.VERCEL) { - return NextResponse.next(); + return HomarrResponse.next(deviceId); } // Do not redirect if there are users in the database if (cachedUserCount > 0) { - return NextResponse.next(); + return HomarrResponse.next(deviceId); } // is only called from when there were no users in the database in this session (Since the app started) @@ -40,8 +42,24 @@ export async function middleware(req: NextRequest) { // Do not redirect if there are users in the database if (cachedUserCount > 0) { - return NextResponse.next(); + return HomarrResponse.next(deviceId); } return NextResponse.redirect(getUrl(req) + '/onboard'); } + +const addDeviceIdToResponse = (response: NextResponse) => { + response.cookies.set(COOKIE_DEVICE_ID_KEY, v4(), { + expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 10), // 10 years + }); +}; + +const HomarrResponse = { + next: (deviceId: string | null) => { + const response = NextResponse.next(); + if (!deviceId) { + addDeviceIdToResponse(response); + } + return response; + }, +};