2023-10-08 11:45:30 +02:00
|
|
|
import Consola from 'consola';
|
|
|
|
|
import fs from 'fs/promises';
|
2023-08-05 12:26:50 +02:00
|
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
|
|
|
import { env } from 'process';
|
|
|
|
|
|
2023-08-24 21:37:39 +02:00
|
|
|
import { getUrl } from './tools/server/url';
|
2023-08-05 12:26:50 +02:00
|
|
|
import { client } from './utils/api';
|
|
|
|
|
|
|
|
|
|
const skippedUrls = [
|
|
|
|
|
'/onboard',
|
|
|
|
|
'/api/',
|
|
|
|
|
'/_next/',
|
|
|
|
|
'/favicon.ico',
|
|
|
|
|
'/404',
|
|
|
|
|
'/pages/_app',
|
|
|
|
|
'/imgs/',
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
let cachedUserCount = 0;
|
|
|
|
|
|
|
|
|
|
export async function middleware(req: NextRequest) {
|
|
|
|
|
const url = req.nextUrl.clone();
|
|
|
|
|
|
|
|
|
|
// Do not redirect if the url is in the skippedUrls array
|
|
|
|
|
if (skippedUrls.some((skippedUrl) => url.pathname.startsWith(skippedUrl))) {
|
|
|
|
|
return NextResponse.next();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Do not redirect if we are on Vercel
|
|
|
|
|
if (env.VERCEL) {
|
|
|
|
|
return NextResponse.next();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Do not redirect if there are users in the database
|
|
|
|
|
if (cachedUserCount > 0) {
|
|
|
|
|
return NextResponse.next();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Do not redirect if there are users in the database
|
2023-10-08 11:45:30 +02:00
|
|
|
if (!(await shouldRedirectToOnboard())) {
|
2023-08-05 12:26:50 +02:00
|
|
|
return NextResponse.next();
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-24 21:37:39 +02:00
|
|
|
return NextResponse.redirect(getUrl(req) + '/onboard');
|
2023-08-05 12:26:50 +02:00
|
|
|
}
|
2023-10-08 11:45:30 +02:00
|
|
|
|
|
|
|
|
const shouldRedirectToOnboard = async (): Promise<boolean> => {
|
|
|
|
|
const cacheAndGetUserCount = async () => {
|
|
|
|
|
cachedUserCount = await client.user.count.query();
|
|
|
|
|
return cachedUserCount === 0;
|
2023-10-25 15:29:45 +02:00
|
|
|
};
|
2023-10-08 11:45:30 +02:00
|
|
|
|
|
|
|
|
if (!env.DATABASE_URL?.startsWith('file:')) {
|
|
|
|
|
return await cacheAndGetUserCount();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const fileUri = env.DATABASE_URL.substring(4);
|
|
|
|
|
try {
|
|
|
|
|
await fs.access(fileUri, fs.constants.W_OK);
|
|
|
|
|
return await cacheAndGetUserCount();
|
|
|
|
|
} catch {
|
|
|
|
|
Consola.warn(
|
|
|
|
|
`detected that the path ${fileUri} was not readable. Showing onboarding page for setup...`
|
|
|
|
|
);
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
};
|