-
Notifications
You must be signed in to change notification settings - Fork 7
refactor(user-tokens): migrate from server #2279
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
Open
shikanime
wants to merge
5
commits into
main
Choose a base branch
from
shikanime/push-uotmotuknkvy
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
0cc00b5
refactor(shared): add token pair generation and expiration schema
shikanime 318548e
refactor(user-tokens): migrate from server
shikanime 50bbb02
test(user-tokens): assert orderBy status then createdAt in list
shikanime 3a6fbc9
refactor(user-tokens): realign module with server-nestjs conventions
shikanime a13636b
test(gitlab): pin mirror token age in rotation spec
shikanime File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 change: 0 additions & 1 deletion
1
apps/server-nestjs/src/modules/admin-role/admin-role-testing.utils.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
apps/server-nestjs/src/modules/user-tokens/user-tokens-queries.utils.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| import type { Prisma } from '@prisma/client' | ||
| import type { DeepMockProxy } from 'vitest-mock-extended' | ||
| import { faker } from '@faker-js/faker' | ||
| import { beforeEach, describe, expect, it } from 'vitest' | ||
| import { mockDeep } from 'vitest-mock-extended' | ||
| import { | ||
| createUserToken, | ||
| listUserTokens, | ||
| userTokenSelect, | ||
| } from './user-tokens-queries.utils' | ||
|
|
||
| describe('user-tokens-queries.utils', () => { | ||
| let tx: DeepMockProxy<Prisma.TransactionClient> | ||
|
|
||
| beforeEach(() => { | ||
| tx = mockDeep<Prisma.TransactionClient>() | ||
| }) | ||
|
|
||
| describe('listUserTokens', () => { | ||
| it('scopes by userId and uses the shared select', async () => { | ||
| const userId = faker.string.uuid() | ||
| tx.personalAccessToken.findMany.mockResolvedValue([]) | ||
|
|
||
| await listUserTokens(tx, userId) | ||
|
|
||
| expect(tx.personalAccessToken.findMany).toHaveBeenCalledWith( | ||
| expect.objectContaining({ where: { userId }, select: userTokenSelect }), | ||
| ) | ||
| }) | ||
| }) | ||
|
|
||
| describe('createUserToken', () => { | ||
| it('creates a personal access token with the provided fields', async () => { | ||
| const data = { | ||
| name: faker.word.noun(), | ||
| expirationDate: faker.date.future(), | ||
| hash: faker.string.alphanumeric(64), | ||
| userId: faker.string.uuid(), | ||
| } | ||
|
|
||
| await createUserToken(tx, data) | ||
|
|
||
| expect(tx.personalAccessToken.create).toHaveBeenCalledWith({ data, select: userTokenSelect }) | ||
| }) | ||
| }) | ||
| }) |
58 changes: 58 additions & 0 deletions
58
apps/server-nestjs/src/modules/user-tokens/user-tokens-queries.utils.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| import type { Prisma } from '@prisma/client' | ||
|
|
||
| export const userTokenOwnerSelect = { | ||
| id: true, | ||
| email: true, | ||
| firstName: true, | ||
| lastName: true, | ||
| type: true, | ||
| } satisfies Prisma.UserSelect | ||
|
|
||
| export const userTokenSelect = { | ||
| id: true, | ||
| name: true, | ||
| lastUse: true, | ||
| expirationDate: true, | ||
| status: true, | ||
| createdAt: true, | ||
| userId: true, | ||
| owner: { | ||
| select: userTokenOwnerSelect, | ||
| }, | ||
| } satisfies Prisma.PersonalAccessTokenSelect | ||
|
|
||
| export type UserTokenRecord = Prisma.PersonalAccessTokenGetPayload<{ | ||
| select: typeof userTokenSelect | ||
| }> | ||
|
|
||
| export function listUserTokens(tx: Prisma.TransactionClient, userId: string) { | ||
| return tx.personalAccessToken.findMany({ | ||
| where: { userId }, | ||
| orderBy: [{ status: 'asc' }, { createdAt: 'asc' }], | ||
| select: userTokenSelect, | ||
| }) | ||
| } | ||
|
|
||
| export function createUserToken(tx: Prisma.TransactionClient, data: { | ||
| name: string | ||
| expirationDate: Date | ||
| hash: string | ||
| userId: string | ||
| }) { | ||
| return tx.personalAccessToken.create({ | ||
| data: { | ||
| name: data.name, | ||
| hash: data.hash, | ||
| expirationDate: data.expirationDate, | ||
| userId: data.userId, | ||
| }, | ||
| select: userTokenSelect, | ||
| }) | ||
| } | ||
|
|
||
| export function deleteUserToken(tx: Prisma.TransactionClient, where: { | ||
| id: string | ||
| userId: string | ||
| }) { | ||
| return tx.personalAccessToken.deleteMany({ where }) | ||
| } |
39 changes: 39 additions & 0 deletions
39
apps/server-nestjs/src/modules/user-tokens/user-tokens.controller.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import type { UserContext } from '../infrastructure/auth/auth-user.decorator' | ||
| import type { CreatePersonalAccessTokenBody } from './user-tokens.utils' | ||
| import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Inject, Param, ParseUUIDPipe, Post, UseGuards } from '@nestjs/common' | ||
| import { AuthUser } from '../infrastructure/auth/auth-user.decorator' | ||
| import { RequireUserType } from '../infrastructure/permission/user/user-type.decorator' | ||
| import { UserGuard } from '../infrastructure/permission/user/user.guard' | ||
| import { ZodValidationPipe } from '../infrastructure/pipe/zod-validation.pipe' | ||
| import { UserTokensService } from './user-tokens.service' | ||
| import { CreatePersonalAccessTokenBodySchema } from './user-tokens.utils' | ||
|
|
||
| @Controller('api/v1/user/tokens') | ||
| @UseGuards(UserGuard) | ||
| @RequireUserType('human') | ||
| export class UserTokensController { | ||
| constructor(@Inject(UserTokensService) private readonly service: UserTokensService) {} | ||
|
|
||
| @Get() | ||
| async list(@AuthUser() user: UserContext) { | ||
| return this.service.list(user.userId) | ||
| } | ||
|
|
||
| @Post() | ||
| @HttpCode(HttpStatus.CREATED) | ||
| async create( | ||
| @Body(new ZodValidationPipe(CreatePersonalAccessTokenBodySchema)) data: CreatePersonalAccessTokenBody, | ||
| @AuthUser() user: UserContext, | ||
| ) { | ||
| return this.service.create(data, user.userId) | ||
| } | ||
|
|
||
| @Delete(':tokenId') | ||
| @HttpCode(HttpStatus.NO_CONTENT) | ||
| async delete( | ||
| @Param('tokenId', ParseUUIDPipe) tokenId: string, | ||
| @AuthUser() user: UserContext, | ||
| ): Promise<void> { | ||
| return this.service.delete(tokenId, user.userId) | ||
| } | ||
| } |
14 changes: 14 additions & 0 deletions
14
apps/server-nestjs/src/modules/user-tokens/user-tokens.module.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import { Module } from '@nestjs/common' | ||
| import { AuthModule } from '../infrastructure/auth/auth.module' | ||
| import { DatabaseModule } from '../infrastructure/database/database.module' | ||
| import { UserPermissionModule } from '../infrastructure/permission/user/user.module' | ||
| import { UserTokensController } from './user-tokens.controller' | ||
| import { UserTokensService } from './user-tokens.service' | ||
|
|
||
| @Module({ | ||
| imports: [AuthModule, DatabaseModule, UserPermissionModule], | ||
| controllers: [UserTokensController], | ||
| providers: [UserTokensService], | ||
| exports: [UserTokensService], | ||
| }) | ||
| export class UserTokensModule {} |
149 changes: 149 additions & 0 deletions
149
apps/server-nestjs/src/modules/user-tokens/user-tokens.service.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| import type { TestingModule } from '@nestjs/testing' | ||
| import type { DeepMockProxy } from 'vitest-mock-extended' | ||
| import { faker } from '@faker-js/faker' | ||
| import { Test } from '@nestjs/testing' | ||
| import { beforeEach, describe, expect, it } from 'vitest' | ||
| import { mockDeep } from 'vitest-mock-extended' | ||
| import { PrismaService } from '../infrastructure/database/prisma.service' | ||
| import { userTokenSelect } from './user-tokens-queries.utils' | ||
| import { UserTokensService } from './user-tokens.service' | ||
| import { CreatePersonalAccessTokenBodySchema } from './user-tokens.utils' | ||
|
|
||
| describe('userTokensService', () => { | ||
| let module: TestingModule | ||
| let service: UserTokensService | ||
| let prisma: DeepMockProxy<PrismaService> | ||
|
|
||
| beforeEach(async () => { | ||
| prisma = mockDeep<PrismaService>() | ||
|
|
||
| module = await Test.createTestingModule({ | ||
| providers: [ | ||
| UserTokensService, | ||
| { provide: PrismaService, useValue: prisma }, | ||
| ], | ||
| }).compile() | ||
|
|
||
| service = module.get(UserTokensService) | ||
| }) | ||
|
|
||
| describe('list', () => { | ||
| it('returns user tokens ordered by status then creation date', async () => { | ||
|
shikanime marked this conversation as resolved.
|
||
| const userId = faker.string.uuid() | ||
| const tokenId = faker.string.uuid() | ||
| prisma.personalAccessToken.findMany.mockResolvedValue([{ | ||
| id: tokenId, | ||
| name: faker.word.noun(), | ||
| lastUse: null, | ||
| expirationDate: faker.date.future(), | ||
| status: 'active' as const, | ||
| createdAt: faker.date.past(), | ||
| userId, | ||
| hash: faker.string.alphanumeric(64), | ||
| }]) | ||
|
|
||
| const result = await service.list(userId) | ||
|
|
||
| expect(prisma.personalAccessToken.findMany).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| where: { userId }, | ||
| orderBy: [{ status: 'asc' }, { createdAt: 'asc' }], | ||
| }), | ||
| ) | ||
| expect(result).toHaveLength(1) | ||
| expect(result[0].id).toBe(tokenId) | ||
| }) | ||
|
|
||
| it('selects only exposed token fields', async () => { | ||
| const userId = faker.string.uuid() | ||
| prisma.personalAccessToken.findMany.mockResolvedValue([]) | ||
|
|
||
| await service.list(userId) | ||
|
|
||
| expect(prisma.personalAccessToken.findMany).toHaveBeenCalledWith( | ||
| expect.objectContaining({ select: userTokenSelect }), | ||
| ) | ||
| }) | ||
| }) | ||
|
|
||
| describe('create', () => { | ||
| it('rejects a non-parseable expirationDate via the body schema', () => { | ||
| const name = faker.word.noun() | ||
| const result = CreatePersonalAccessTokenBodySchema.safeParse({ name, expirationDate: 'not-a-date' }) | ||
| expect(result.success).toBe(false) | ||
| }) | ||
|
|
||
| it('rejects an expirationDate that is too soon via the body schema', () => { | ||
| const name = faker.word.noun() | ||
| const today = faker.date.recent() | ||
| const result = CreatePersonalAccessTokenBodySchema.safeParse({ name, expirationDate: today.toISOString() }) | ||
| expect(result.success).toBe(false) | ||
| }) | ||
|
|
||
| it('returns created token with plaintext password', async () => { | ||
| const userId = faker.string.uuid() | ||
| const tokenId = faker.string.uuid() | ||
| const tokenName = faker.word.noun() | ||
| prisma.personalAccessToken.create.mockResolvedValue({ | ||
| id: tokenId, | ||
| name: tokenName, | ||
| lastUse: null, | ||
| expirationDate: faker.date.future(), | ||
| status: 'active' as const, | ||
| createdAt: faker.date.past(), | ||
| userId, | ||
| hash: faker.string.alphanumeric(64), | ||
| }) | ||
|
|
||
| const result = await service.create({ name: tokenName, expirationDate: faker.date.future() }, userId) | ||
|
|
||
| expect(prisma.personalAccessToken.create).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| data: expect.objectContaining({ | ||
| userId, | ||
| name: tokenName, | ||
| }), | ||
| select: userTokenSelect, | ||
| }), | ||
| ) | ||
| expect(result.id).toBe(tokenId) | ||
| expect(result.password).toBeTruthy() | ||
| }) | ||
|
|
||
| it('rejects an expirationDate that is not at least tomorrow', async () => { | ||
| const userId = faker.string.uuid() | ||
| const tokenName = faker.word.noun() | ||
|
|
||
| await expect( | ||
| service.create({ name: tokenName, expirationDate: faker.date.past() }, userId), | ||
| ).rejects.toThrow('Date d\'expiration trop courte') | ||
| expect(prisma.personalAccessToken.create).not.toHaveBeenCalled() | ||
| }) | ||
| }) | ||
|
|
||
| describe('delete', () => { | ||
| it('deletes token scoped to its owner in a single atomic call', async () => { | ||
| const tokenId = faker.string.uuid() | ||
| const userId = faker.string.uuid() | ||
| prisma.personalAccessToken.deleteMany.mockResolvedValue({ count: 1 }) | ||
|
|
||
| await service.delete(tokenId, userId) | ||
|
|
||
| expect(prisma.personalAccessToken.deleteMany).toHaveBeenCalledWith({ | ||
| where: { id: tokenId, userId }, | ||
| }) | ||
| }) | ||
|
|
||
| it('no-ops (count 0) when token is missing or belongs to another user', async () => { | ||
| const tokenId = faker.string.uuid() | ||
| const userId = faker.string.uuid() | ||
| prisma.personalAccessToken.deleteMany.mockResolvedValue({ count: 0 }) | ||
|
|
||
| await service.delete(tokenId, userId) | ||
|
|
||
| expect(prisma.personalAccessToken.deleteMany).toHaveBeenCalledWith({ | ||
| where: { id: tokenId, userId }, | ||
| }) | ||
| }) | ||
| }) | ||
| }) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.