|
| 1 | +import type { CloudRegion } from "@shared/types/oauth"; |
| 2 | +import { eq } from "drizzle-orm"; |
| 3 | +import { inject, injectable } from "inversify"; |
| 4 | +import { MAIN_TOKENS } from "../../di/tokens"; |
| 5 | +import { authSessions } from "../schema"; |
| 6 | +import type { DatabaseService } from "../service"; |
| 7 | + |
| 8 | +export type AuthSession = typeof authSessions.$inferSelect; |
| 9 | +export type NewAuthSession = typeof authSessions.$inferInsert; |
| 10 | + |
| 11 | +export interface PersistAuthSessionInput { |
| 12 | + refreshTokenEncrypted: string; |
| 13 | + cloudRegion: CloudRegion; |
| 14 | + selectedProjectId: number | null; |
| 15 | + scopeVersion: number; |
| 16 | +} |
| 17 | + |
| 18 | +export interface IAuthSessionRepository { |
| 19 | + getCurrent(): AuthSession | null; |
| 20 | + saveCurrent(input: PersistAuthSessionInput): AuthSession; |
| 21 | + clearCurrent(): void; |
| 22 | +} |
| 23 | + |
| 24 | +const CURRENT_AUTH_SESSION_ID = 1; |
| 25 | +const byId = eq(authSessions.id, CURRENT_AUTH_SESSION_ID); |
| 26 | +const now = () => new Date().toISOString(); |
| 27 | + |
| 28 | +@injectable() |
| 29 | +export class AuthSessionRepository implements IAuthSessionRepository { |
| 30 | + constructor( |
| 31 | + @inject(MAIN_TOKENS.DatabaseService) |
| 32 | + private readonly databaseService: DatabaseService, |
| 33 | + ) {} |
| 34 | + |
| 35 | + private get db() { |
| 36 | + return this.databaseService.db; |
| 37 | + } |
| 38 | + |
| 39 | + getCurrent(): AuthSession | null { |
| 40 | + return ( |
| 41 | + this.db.select().from(authSessions).where(byId).limit(1).get() ?? null |
| 42 | + ); |
| 43 | + } |
| 44 | + |
| 45 | + saveCurrent(input: PersistAuthSessionInput): AuthSession { |
| 46 | + const timestamp = now(); |
| 47 | + const existing = this.getCurrent(); |
| 48 | + |
| 49 | + const row: NewAuthSession = { |
| 50 | + id: CURRENT_AUTH_SESSION_ID, |
| 51 | + refreshTokenEncrypted: input.refreshTokenEncrypted, |
| 52 | + cloudRegion: input.cloudRegion, |
| 53 | + selectedProjectId: input.selectedProjectId, |
| 54 | + scopeVersion: input.scopeVersion, |
| 55 | + createdAt: existing?.createdAt ?? timestamp, |
| 56 | + updatedAt: timestamp, |
| 57 | + }; |
| 58 | + |
| 59 | + if (existing) { |
| 60 | + this.db.update(authSessions).set(row).where(byId).run(); |
| 61 | + } else { |
| 62 | + this.db.insert(authSessions).values(row).run(); |
| 63 | + } |
| 64 | + |
| 65 | + const saved = this.getCurrent(); |
| 66 | + if (!saved) { |
| 67 | + throw new Error("Failed to persist current auth session"); |
| 68 | + } |
| 69 | + return saved; |
| 70 | + } |
| 71 | + |
| 72 | + clearCurrent(): void { |
| 73 | + this.db.delete(authSessions).where(byId).run(); |
| 74 | + } |
| 75 | +} |
0 commit comments