-
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
f5d6401
87f29a1
e280da7
0bc5040
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,38 @@ | ||
| import type { AdminRole } from './admin-role-queries.utils' | ||
| import type { AdminRoleService } from './admin-role.service' | ||
|
Check notice on line 2 in apps/server-nestjs/src/modules/admin-role/admin-role-testing.utils.ts
|
||
| import type { CreateAdminRoleBody, PatchAdminRolesBody } from './admin-role.utils' | ||
|
|
||
| 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 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') | ||
|
shikanime marked this conversation as resolved.
|
||
| 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,95 @@ | ||
| 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, | ||
| makePatchAdminRoleBody, | ||
| } 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: [], | ||
| }) | ||
| }) | ||
|
|
||
| it('patch does not throw on coherent positions and emits upsert per role', async () => { | ||
| const roleA = makeAdminRole({ id: 'a', name: 'A', position: 1 }) | ||
| const roleB = makeAdminRole({ id: 'b', name: 'B', position: 2 }) | ||
| const patchedA = makePatchAdminRoleBody(roleA, { name: 'A-renamed' }) | ||
| const patchedB = makePatchAdminRoleBody(roleB, { name: 'B-renamed' }) | ||
|
|
||
| prisma.adminRole.findMany.mockResolvedValue([roleA, roleB]) | ||
| prisma.adminRole.findFirst.mockResolvedValueOnce(roleA).mockResolvedValueOnce(roleB) | ||
| prisma.user.findMany.mockResolvedValue([]) | ||
| prisma.$transaction.mockImplementation(async (cb: (tx: unknown) => unknown) => cb(prisma)) | ||
|
|
||
| const service = new AdminRoleService(prisma, eventEmitter) | ||
| await expect(service.patch([patchedA, patchedB])).resolves.toBeDefined() | ||
| expect(eventEmitter.emitAsync).toHaveBeenCalledTimes(2) | ||
| }) | ||
| }) |
Uh oh!
There was an error while loading. Please reload this page.