|
| 1 | +/** |
| 2 | + * Copyright (c) 2024 Gitpod GmbH. All rights reserved. |
| 3 | + * Licensed under the GNU Affero General Public License (AGPL). |
| 4 | + * See License.AGPL.txt in the project root for license information. |
| 5 | + */ |
| 6 | + |
| 7 | +import { inject, injectable } from "inversify"; |
| 8 | +import { TypeORM } from "./typeorm"; |
| 9 | + |
| 10 | +import { AuditLog } from "@gitpod/gitpod-protocol/lib/audit-log"; |
| 11 | +import { Between, FindConditions, LessThan, Repository } from "typeorm"; |
| 12 | +import { AuditLogDB } from "../audit-log-db"; |
| 13 | +import { DBAuditLog } from "./entity/db-audit-log"; |
| 14 | + |
| 15 | +@injectable() |
| 16 | +export class AuditLogDBImpl implements AuditLogDB { |
| 17 | + @inject(TypeORM) typeORM: TypeORM; |
| 18 | + |
| 19 | + private async getEntityManager() { |
| 20 | + return (await this.typeORM.getConnection()).manager; |
| 21 | + } |
| 22 | + |
| 23 | + private async getRepo(): Promise<Repository<DBAuditLog>> { |
| 24 | + return (await this.getEntityManager()).getRepository(DBAuditLog); |
| 25 | + } |
| 26 | + |
| 27 | + async recordAuditLog(logEntry: AuditLog): Promise<void> { |
| 28 | + const repo = await this.getRepo(); |
| 29 | + await repo.insert(logEntry); |
| 30 | + } |
| 31 | + |
| 32 | + async listAuditLogs( |
| 33 | + organizationId: string, |
| 34 | + params?: |
| 35 | + | { |
| 36 | + from?: string; |
| 37 | + to?: string; |
| 38 | + actorId?: string; |
| 39 | + action?: string; |
| 40 | + pagination?: { offset?: number; limit?: number }; |
| 41 | + } |
| 42 | + | undefined, |
| 43 | + ): Promise<AuditLog[]> { |
| 44 | + const repo = await this.getRepo(); |
| 45 | + const where: FindConditions<DBAuditLog> = { |
| 46 | + organizationId, |
| 47 | + }; |
| 48 | + if (params?.from && params?.to) { |
| 49 | + where.timestamp = Between(params.from, params.to); |
| 50 | + } |
| 51 | + if (params?.actorId) { |
| 52 | + where.actorId = params.actorId; |
| 53 | + } |
| 54 | + if (params?.action) { |
| 55 | + where.action = params.action; |
| 56 | + } |
| 57 | + return repo.find({ |
| 58 | + where, |
| 59 | + order: { |
| 60 | + timestamp: "DESC", |
| 61 | + }, |
| 62 | + skip: params?.pagination?.offset, |
| 63 | + take: params?.pagination?.limit, |
| 64 | + }); |
| 65 | + } |
| 66 | + |
| 67 | + async purgeAuditLogs(before: string, organizationId?: string): Promise<number> { |
| 68 | + const repo = await this.getRepo(); |
| 69 | + const findConditions: FindConditions<DBAuditLog> = { |
| 70 | + timestamp: LessThan(before), |
| 71 | + }; |
| 72 | + if (organizationId) { |
| 73 | + findConditions.organizationId = organizationId; |
| 74 | + } |
| 75 | + const result = await repo.delete(findConditions); |
| 76 | + return result.affected ?? 0; |
| 77 | + } |
| 78 | +} |
0 commit comments