Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feature: prepare for demo mode

Carl-Gerhard Lindesvärd9b16bbaccd12
diff --git a/apps/dashboard/src/middleware.ts b/apps/dashboard/src/middleware.ts
index b3f5cc008..d7154a5b7 100644
--- a/apps/dashboard/src/middleware.ts
+++ b/apps/dashboard/src/middleware.ts
@@ -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));
}
diff --git a/packages/auth/src/session.ts b/packages/auth/src/session.ts
index dd99c487c..f91ef63de 100644
--- a/packages/auth/src/session.ts
+++ b/packages/auth/src/session.ts
@@ -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;
}
diff --git a/packages/trpc/src/trpc.ts b/packages/trpc/src/trpc.ts
index a90219501..10f709d27 100644
--- a/packages/trpc/src/trpc.ts
+++ b/packages/trpc/src/trpc.ts
@@ -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!,