-
Notifications
You must be signed in to change notification settings - Fork 6
refactor(admin-roles): migrate from server #2371
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| import type { Prisma } from '@prisma/client' | ||
|
|
||
| export const adminRoleSelect = { | ||
| id: true, | ||
| name: true, | ||
| permissions: true, | ||
| position: true, | ||
| oidcGroup: true, | ||
| type: true, | ||
| } satisfies Prisma.AdminRoleSelect | ||
|
|
||
| export type AdminRole = Prisma.AdminRoleGetPayload<{ | ||
| select: typeof adminRoleSelect | ||
| }> | ||
|
|
||
| export async function getAdminRoleMaxPosition(tx: Prisma.TransactionClient): Promise<number> { | ||
| const role = await tx.adminRole.findFirst({ | ||
| orderBy: { position: 'desc' }, | ||
| select: { position: true }, | ||
| }) | ||
|
|
||
| return role?.position ?? -1 | ||
| } | ||
|
|
||
| export async function createAdminRole(tx: Prisma.TransactionClient, name: string): Promise<{ role: AdminRole, members: { id: string, email: string, firstName: string, lastName: string }[] }> { | ||
| const maxPosition = await getAdminRoleMaxPosition(tx) | ||
| const role = await tx.adminRole.create({ | ||
| data: { | ||
| name, | ||
| permissions: 0n, | ||
| position: maxPosition + 1, | ||
| }, | ||
| select: adminRoleSelect, | ||
| }) | ||
|
|
||
| const members = await tx.user.findMany({ | ||
| where: { adminRoleIds: { has: role.id } }, | ||
| select: { id: true, email: true, firstName: true, lastName: true }, | ||
| }) | ||
|
|
||
| return { role, members } | ||
| } | ||
|
|
||
| export async function getAdminRoleMemberCounts(tx: Prisma.TransactionClient): Promise<Record<string, number>> { | ||
| const roles = await tx.adminRole.findMany({ | ||
| where: { oidcGroup: { equals: '' } }, | ||
| select: { id: true }, | ||
| }) | ||
| const roleIds = roles.map(role => role.id) | ||
| const users = await tx.user.findMany({ | ||
| where: { adminRoleIds: { hasSome: roleIds } }, | ||
| select: { adminRoleIds: true }, | ||
| }) | ||
|
|
||
| const counts: Record<string, number> = Object.fromEntries(roleIds.map(roleId => [roleId, 0])) | ||
| for (const { adminRoleIds } of users) { | ||
| for (const roleId of adminRoleIds) { | ||
| if (typeof counts[roleId] === 'number') counts[roleId]++ | ||
| } | ||
| } | ||
|
|
||
| return counts | ||
| } | ||
|
|
||
| export async function getRoles(tx: Prisma.TransactionClient): Promise<AdminRole[]> { | ||
| return await tx.adminRole.findMany({ | ||
| orderBy: { position: 'asc' }, | ||
| select: adminRoleSelect, | ||
| }) | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| import type { AdminRole } from './admin-role-queries.utils' | ||
| import type { AdminRoleService } from './admin-role.service' | ||
| import type { CreateAdminRoleBody, PatchAdminRolesBody } from './admin-role.utils' | ||
|
|
||
| export type AdminRoleContract = Parameters<AdminRoleService['patch']>[0][number] | ||
| export type AdminRoleResponse = NonNullable<Awaited<ReturnType<AdminRoleService['list']>>>[number] | ||
|
|
||
| export interface AdminRoleMember { | ||
| id: string | ||
| email: string | ||
| firstName: string | ||
| lastName: string | ||
| } | ||
|
|
||
| export function makeAdminRole(overrides: Partial<AdminRole> = {}): AdminRole { | ||
| return { | ||
| id: overrides.id ?? crypto.randomUUID(), | ||
| name: overrides.name ?? 'New role', | ||
| permissions: overrides.permissions ?? 0n, | ||
| position: overrides.position ?? 0, | ||
| oidcGroup: overrides.oidcGroup ?? '', | ||
| type: overrides.type ?? 'managed', | ||
| ...overrides, | ||
| } | ||
| } | ||
|
|
||
| export function makeAdminRoleMember(overrides: Partial<AdminRoleMember> = {}): AdminRoleMember { | ||
| return { | ||
| id: crypto.randomUUID(), | ||
| email: 'user@example.com', | ||
| firstName: 'First', | ||
| lastName: 'Last', | ||
| ...overrides, | ||
| } | ||
| } | ||
|
|
||
| export function makeCreateAdminRoleBody(overrides: { name?: string } = {}): CreateAdminRoleBody { | ||
| return { | ||
| name: overrides.name ?? 'New role', | ||
| } | ||
| } | ||
|
|
||
| export function makePatchAdminRoleBody( | ||
| role: AdminRole, | ||
| overrides: Partial<PatchAdminRolesBody[number]> = {}, | ||
| ): PatchAdminRolesBody[number] { | ||
| return { | ||
| id: role.id, | ||
| name: overrides.name ?? role.name, | ||
| permissions: | ||
| overrides.permissions | ||
| ?? (typeof role.permissions === 'bigint' ? role.permissions.toString() : String(role.permissions)), | ||
| position: overrides.position ?? role.position, | ||
| oidcGroup: overrides.oidcGroup ?? role.oidcGroup, | ||
| type: overrides.type ?? role.type, | ||
| ...overrides, | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| import type { AdminRole } from '@cpn-console/shared' | ||
| import type { CreateAdminRoleBody, PatchAdminRolesBody } from './admin-role.utils' | ||
| import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Inject, Param, ParseUUIDPipe, Patch, Post, UseGuards } from '@nestjs/common' | ||
| import { RequireAdminPermission } from '../infrastructure/permission/user/user-admin-permission.decorator' | ||
| import { UserGuard } from '../infrastructure/permission/user/user.guard' | ||
| import { ZodValidationPipe } from '../infrastructure/pipe/zod-validation.pipe' | ||
| import { AdminRoleService } from './admin-role.service' | ||
| import { CreateAdminRoleBodySchema, PatchAdminRolesBodySchema } from './admin-role.utils' | ||
|
|
||
| @Controller('api/v1/admin/roles') | ||
| export class AdminRoleController { | ||
| constructor( | ||
| @Inject(AdminRoleService) private readonly adminRoleService: AdminRoleService, | ||
| ) {} | ||
|
|
||
| @Get('') | ||
| @UseGuards(UserGuard) | ||
| // TODO: ListRoles is intentionally not protected by admin permission because of | ||
|
Check notice on line 18 in apps/server-nestjs/src/modules/admin-role/admin-role.controller.ts
|
||
| // certain behaviours of the legacy client | ||
| // @RequireAdminPermission('ListRoles') | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ça demande un ticket, à mon avis, car c'est suffisament atomique, comme considération 🙂 |
||
| async listAdminRoles(): Promise<AdminRole[]> { | ||
| return this.adminRoleService.list() | ||
| } | ||
|
|
||
| @Post('') | ||
| @HttpCode(HttpStatus.CREATED) | ||
| @UseGuards(UserGuard) | ||
| @RequireAdminPermission('ManageRoles') | ||
| async createAdminRole( | ||
| @Body(new ZodValidationPipe(CreateAdminRoleBodySchema)) body: CreateAdminRoleBody, | ||
| ): Promise<AdminRole> { | ||
| return this.adminRoleService.create(body) | ||
| } | ||
|
|
||
| @Patch('') | ||
| @HttpCode(HttpStatus.OK) | ||
| @UseGuards(UserGuard) | ||
| @RequireAdminPermission('ManageRoles') | ||
| async patchAdminRoles( | ||
| @Body(new ZodValidationPipe(PatchAdminRolesBodySchema)) body: PatchAdminRolesBody, | ||
| ): Promise<AdminRole[]> { | ||
| return this.adminRoleService.patch(body) | ||
| } | ||
|
|
||
| @Get('member-counts') | ||
| @UseGuards(UserGuard) | ||
| @RequireAdminPermission('ManageRoles') | ||
| async adminRoleMemberCounts(): Promise<Record<string, number>> { | ||
| return this.adminRoleService.memberCounts() | ||
| } | ||
|
|
||
| @Delete(':roleId') | ||
| @HttpCode(HttpStatus.NO_CONTENT) | ||
| @UseGuards(UserGuard) | ||
| @RequireAdminPermission('ManageRoles') | ||
| async deleteAdminRole( | ||
| @Param('roleId', ParseUUIDPipe) roleId: string, | ||
| ): Promise<void> { | ||
| await this.adminRoleService.delete(roleId) | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| import { Module } from '@nestjs/common' | ||
| import { AuthModule } from '../infrastructure/auth/auth.module' | ||
| import { InfrastructureModule } from '../infrastructure/infrastructure.module' | ||
| import { AdminRoleController } from './admin-role.controller' | ||
| import { AdminRoleService } from './admin-role.service' | ||
|
|
||
| @Module({ | ||
| imports: [InfrastructureModule, AuthModule], | ||
| controllers: [AdminRoleController], | ||
| providers: [AdminRoleService], | ||
| exports: [AdminRoleService], | ||
| }) | ||
| export class AdminRoleModule {} |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| import type { EventEmitter2 } from '@nestjs/event-emitter' | ||
| import type { PrismaService } from '../infrastructure/database/prisma.service' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
| import { mockDeep } from 'vitest-mock-extended' | ||
| import { | ||
| makeAdminRole, | ||
| makeCreateAdminRoleBody, | ||
| } from './admin-role-testing.utils' | ||
| import { AdminRoleService } from './admin-role.service' | ||
|
|
||
| describe('adminRoleService', () => { | ||
| let prisma: ReturnType<typeof mockDeep<PrismaService>> | ||
| let eventEmitter: ReturnType<typeof mockDeep<EventEmitter2>> | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| prisma = mockDeep<PrismaService>() | ||
| eventEmitter = mockDeep<EventEmitter2>() | ||
| eventEmitter.emitAsync.mockResolvedValue([]) | ||
| }) | ||
|
|
||
| it('creates a role at the next position and returns the created role', async () => { | ||
| const existingRole = makeAdminRole({ | ||
| position: 5, | ||
| permissions: 4n, | ||
| type: 'managed', | ||
| }) | ||
|
|
||
| const createdRole = makeAdminRole({ | ||
| ...existingRole, | ||
| name: 'New role', | ||
| position: 6, | ||
| permissions: 0n, | ||
| }) | ||
|
|
||
| prisma.adminRole.findFirst.mockResolvedValue(existingRole) | ||
| prisma.adminRole.create.mockResolvedValue(createdRole) | ||
| prisma.adminRole.findUnique.mockResolvedValue(createdRole) | ||
| prisma.user.findMany.mockResolvedValue([]) | ||
| prisma.$transaction.mockImplementation(async callback => callback(prisma)) | ||
|
|
||
| const createBody = makeCreateAdminRoleBody({ name: 'New role' }) | ||
| const service = new AdminRoleService(prisma, eventEmitter) | ||
| const result = await service.create(createBody) | ||
|
|
||
| expect(result).toEqual( | ||
| expect.objectContaining({ | ||
| id: existingRole.id, | ||
| permissions: '0', | ||
| position: 6, | ||
| }), | ||
| ) | ||
| expect(prisma.adminRole.create).toHaveBeenCalledWith({ | ||
| data: { | ||
| name: 'New role', | ||
| permissions: 0n, | ||
| position: 6, | ||
| }, | ||
| select: { | ||
| id: true, | ||
| name: true, | ||
| oidcGroup: true, | ||
| permissions: true, | ||
| position: true, | ||
| type: true, | ||
| }, | ||
| }) | ||
| expect(eventEmitter.emitAsync).toHaveBeenCalledWith('adminRole.upsert', { | ||
| id: existingRole.id, | ||
| name: 'New role', | ||
| oidcGroup: '', | ||
| permissions: 0n, | ||
| position: 6, | ||
| type: 'managed', | ||
| members: [], | ||
| }) | ||
| }) | ||
| }) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unused testing-utils exports:
AdminRoleContract,AdminRoleResponse, andmakeAdminRoleMember(lines 5, 6, 27) have no importers — the spec only usesmakeAdminRole/makeCreateAdminRoleBody. Drop them or wire them into the spec to avoid dead surface.