fix: use database session cookie for production (#4200)

This commit is contained in:
Peng Xiao 2023-09-06 01:30:50 +08:00 committed by GitHub
parent 8407b2dd7c
commit 1dc94277c2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 3 deletions

View File

@ -121,7 +121,7 @@ export const NextAuthOptionsProvider: FactoryProvider<NextAuthOptions> = {
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,

View File

@ -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),
};
}

View File

@ -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;
}
}