From 1dc94277c2d72094ac4f3df385d62dbf501de6ed Mon Sep 17 00:00:00 2001 From: Peng Xiao Date: Wed, 6 Sep 2023 01:30:50 +0800 Subject: [PATCH] fix: use database session cookie for production (#4200) --- apps/server/src/modules/auth/next-auth-options.ts | 2 +- apps/server/src/modules/auth/resolver.ts | 9 +++++++-- apps/server/src/modules/auth/service.ts | 13 +++++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/apps/server/src/modules/auth/next-auth-options.ts b/apps/server/src/modules/auth/next-auth-options.ts index 60f401ae09..3c7508d8a4 100644 --- a/apps/server/src/modules/auth/next-auth-options.ts +++ b/apps/server/src/modules/auth/next-auth-options.ts @@ -121,7 +121,7 @@ export const NextAuthOptionsProvider: FactoryProvider = { adapter: prismaAdapter, debug: !config.node.prod, session: { - strategy: 'jwt', + strategy: config.node.prod ? 'database' : 'jwt', }, // @ts-expect-error Third part library type mismatch logger: console, diff --git a/apps/server/src/modules/auth/resolver.ts b/apps/server/src/modules/auth/resolver.ts index 9b85929e20..581b582e0e 100644 --- a/apps/server/src/modules/auth/resolver.ts +++ b/apps/server/src/modules/auth/resolver.ts @@ -49,13 +49,18 @@ export class AuthResolver { @Throttle(20, 60) @ResolveField(() => TokenType) - token(@CurrentUser() currentUser: UserType, @Parent() user: UserType) { + async token(@CurrentUser() currentUser: UserType, @Parent() user: UserType) { if (user.id !== currentUser.id) { throw new BadRequestException('Invalid user'); } + // on production we use session token that is stored in database (strategy = 'database') + const sessionToken = this.config.node.prod + ? await this.auth.getSessionToken(user.id) + : this.auth.sign(user); + return { - token: this.auth.sign(user), + token: sessionToken, refresh: this.auth.refresh(user), }; } diff --git a/apps/server/src/modules/auth/service.ts b/apps/server/src/modules/auth/service.ts index 7ac7828ddb..ad126092e9 100644 --- a/apps/server/src/modules/auth/service.ts +++ b/apps/server/src/modules/auth/service.ts @@ -251,4 +251,17 @@ export class AuthService { async sendChangeEmail(email: string, callbackUrl: string) { return this.mailer.sendChangeEmail(email, callbackUrl); } + async getSessionToken(userId: string) { + const session = await this.prisma.session.findFirst({ + where: { + userId: userId, + }, + }); + + if (!session) { + throw new BadRequestException(`No session found for user id ${userId}`); + } + + return session?.sessionToken; + } }