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