fix: stopper l'exécution après un refus d'autorisation dans parole.create

This commit is contained in:
2026-07-04 09:36:17 +04:00
parent 796b4379fd
commit f592d4ded7
2 changed files with 96 additions and 5 deletions
@@ -0,0 +1,91 @@
import {describe, it, expect, vi} from 'vitest'
const {default: createController} = await import('../parole.js')
function buildStrapi({jwtUserId, dbUser, artiste}) {
const paroleDocuments = {
findMany: vi.fn(async () => []),
create: vi.fn(async ({data}) => ({id: 42, ...data}))
}
const userDocuments = {
findOne: vi.fn(async () => dbUser),
update: vi.fn(async () => {})
}
const artisteDocuments = {
findOne: vi.fn(async () => artiste)
}
const strapi = {
contentType: vi.fn(() => ({uid: 'api::parole.parole', kind: 'collectionType'})),
service: vi.fn(() => ({
validateParoles: vi.fn(),
translateLyrics: vi.fn()
})),
plugins: {
'users-permissions': {
services: {
jwt: {
getToken: vi.fn(async () => ({id: jwtUserId}))
}
}
}
},
documents: vi.fn(uid => {
if (uid === 'plugin::users-permissions.user') return userDocuments
if (uid === 'api::artiste.artiste') return artisteDocuments
if (uid === 'api::parole.parole') return paroleDocuments
throw new Error(`unexpected uid: ${uid}`)
})
}
return {strapi, paroleDocuments, userDocuments, artisteDocuments}
}
function buildCtx(data) {
return {
request: {
body: {data},
header: {authorization: 'Bearer faketoken'}
},
unauthorized: vi.fn(),
badRequest: vi.fn(),
notFound: vi.fn()
}
}
const dbUser = {id: 1, documentId: 'user-doc-1', username: 'foo', email: 'foo@bar.com'}
const artiste = {documentId: 'artiste-doc-1'}
function buildData(overrides = {}) {
return {
titre: 'Test',
transcription: 'Paroles...',
user: {...dbUser},
artistes: [{documentId: 'artiste-doc-1'}],
...overrides
}
}
describe('parole.create', () => {
it('refuse et ne crée rien quand le user du JWT ne correspond pas au user du payload', async () => {
const {strapi, paroleDocuments} = buildStrapi({jwtUserId: 999, dbUser, artiste})
const controller = createController({strapi})
const ctx = buildCtx(buildData())
await controller.create(ctx)
expect(ctx.unauthorized).toHaveBeenCalled()
expect(paroleDocuments.create).not.toHaveBeenCalled()
})
it('crée la parole quand le user du JWT correspond au user du payload', async () => {
const {strapi, paroleDocuments} = buildStrapi({jwtUserId: 1, dbUser, artiste})
const controller = createController({strapi})
const ctx = buildCtx(buildData())
await controller.create(ctx)
expect(ctx.unauthorized).not.toHaveBeenCalled()
expect(paroleDocuments.create).toHaveBeenCalled()
})
})