feature: prepare for demo mode

This commit is contained in:
Carl-Gerhard Lindesvärd
2025-06-17 23:10:23 +02:00
parent 02be728499
commit 9b16bbaccd
3 changed files with 38 additions and 1 deletions

View File

@@ -45,6 +45,10 @@ export default (request: NextRequest) => {
const response = NextResponse.next();
const token = request.cookies.get('session')?.value ?? null;
if (process.env.DEMO_USER_ID) {
return response;
}
if (!isPublicRoute(request) && token === null) {
return NextResponse.redirect(new URL('/login', request.url));
}

View File

@@ -37,9 +37,35 @@ export const EMPTY_SESSION: SessionValidationResult = {
userId: null,
};
export async function createDemoSession(
userId: string,
): Promise<SessionValidationResult> {
const user = await db.user.findUniqueOrThrow({
where: {
id: userId,
},
});
return {
user,
userId: user.id,
session: {
id: '1',
userId: user.id,
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30 * 365),
createdAt: new Date(),
updatedAt: new Date(),
},
};
}
export async function validateSessionToken(
token: string | null,
): Promise<SessionValidationResult> {
if (process.env.DEMO_USER_ID) {
return createDemoSession(process.env.DEMO_USER_ID);
}
if (!token) {
return EMPTY_SESSION;
}

View File

@@ -88,7 +88,14 @@ const enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => {
});
// Only used on protected routes
const enforceAccess = t.middleware(async ({ ctx, next, rawInput }) => {
const enforceAccess = t.middleware(async ({ ctx, next, rawInput, type }) => {
if (type === 'mutation' && process.env.DEMO_USER_ID) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'You are not allowed to do this in demo mode',
});
}
if (has('projectId', rawInput)) {
const access = await getProjectAccessCached({
userId: ctx.session.userId!,