refactor(server): narrow auth types (#16066)

This commit is contained in:
Jason Rasmussen
2025-02-12 15:23:08 -05:00
committed by GitHub
parent 7c821dd205
commit 2d7c333c8c
25 changed files with 265 additions and 239 deletions

View File

@@ -1,12 +1,12 @@
import { Injectable } from '@nestjs/common';
import { Insertable, Kysely, Updateable } from 'kysely';
import { jsonObjectFrom } from 'kysely/helpers/postgres';
import { InjectKysely } from 'nestjs-kysely';
import { columns } from 'src/database';
import { ApiKeys, DB } from 'src/db';
import { DummyValue, GenerateSql } from 'src/decorators';
import { asUuid } from 'src/utils/database';
const columns = ['id', 'name', 'userId', 'createdAt', 'updatedAt', 'permissions'] as const;
@Injectable()
export class ApiKeyRepository {
constructor(@InjectKysely() private db: Kysely<DB>) {}
@@ -33,29 +33,15 @@ export class ApiKeyRepository {
getKey(hashedToken: string) {
return this.db
.selectFrom('api_keys')
.innerJoinLateral(
(eb) =>
.select((eb) => [
...columns.authApiKey,
jsonObjectFrom(
eb
.selectFrom('users')
.selectAll('users')
.select((eb) =>
eb
.selectFrom('user_metadata')
.whereRef('users.id', '=', 'user_metadata.userId')
.select((eb) => eb.fn('array_agg', [eb.table('user_metadata')]).as('metadata'))
.as('metadata'),
)
.select(columns.authUser)
.whereRef('users.id', '=', 'api_keys.userId')
.where('users.deletedAt', 'is', null)
.as('user'),
(join) => join.onTrue(),
)
.select((eb) => [
'api_keys.id',
'api_keys.key',
'api_keys.userId',
'api_keys.permissions',
eb.fn.toJson('user').as('user'),
.where('users.deletedAt', 'is', null),
).as('user'),
])
.where('api_keys.key', '=', hashedToken)
.executeTakeFirst();
@@ -65,7 +51,7 @@ export class ApiKeyRepository {
getById(userId: string, id: string) {
return this.db
.selectFrom('api_keys')
.select(columns)
.select(columns.apiKey)
.where('id', '=', asUuid(id))
.where('userId', '=', userId)
.executeTakeFirst();
@@ -75,7 +61,7 @@ export class ApiKeyRepository {
getByUserId(userId: string) {
return this.db
.selectFrom('api_keys')
.select(columns)
.select(columns.apiKey)
.where('userId', '=', userId)
.orderBy('createdAt', 'desc')
.execute();