@@ -12,40 +12,56 @@ async function checkPermissionAgrement(
1212 res : Response ,
1313 next : NextFunction ,
1414) {
15- if ( ! req . decoded || typeof req . decoded . id === "undefined" ) {
16- log . w ( "Utilisateur non authentifié ou id manquant" ) ;
17- return next (
18- new AppError ( "Authentification requise" , {
19- statusCode : 401 ,
20- } ) ,
21- ) ;
22- }
23- const { id : userId } = req . decoded ;
24- // Récupère l'Id de l'organisme en fonction de la provenance (POST ou GET)
25- const organismeId = req . body ?. organismeId ?? req . params ?. id ?? null ;
26- log . i ( "IN" ) ;
27-
28- const query = `
29- SELECT uo.org_id
30- FROM front.user_organisme uo
31- JOIN front.users u ON uo.use_id = u.id
32- WHERE u.id = $1
33- ` ;
34- const { rows } = await getPool ( ) . query ( query , [ userId ] ) ;
35- if (
36- ! rows ||
37- rows . length !== 1 ||
38- rows [ 0 ] . org_id . toString ( ) !== organismeId . toString ( )
39- ) {
40- log . w ( "Utilisateur non autorisé à modifier l'agrement" ) ;
41- return next (
42- new AppError ( "Vous n'êtes pas autorisé à modifier cet agrément" , {
43- statusCode : 403 ,
44- } ) ,
45- ) ;
15+ try {
16+ if ( ! req . decoded || typeof req . decoded . id === "undefined" ) {
17+ log . w ( "Utilisateur non authentifié ou id manquant" ) ;
18+ return next (
19+ new AppError ( "Authentification requise" , {
20+ statusCode : 401 ,
21+ } ) ,
22+ ) ;
23+ }
24+ const { id : userId } = req . decoded ;
25+
26+ const agrementId =
27+ req . params ?. agrementId ?? req . body ?. agrementId ?? req . params ?. id ?? null ;
28+
29+ let organismeId = req . body ?. organismeId ?? req . params ?. organismeId ?? null ;
30+
31+ if ( ! organismeId && agrementId ) {
32+ const orgQuery = `SELECT organisme_id FROM front.agrements WHERE id = $1` ;
33+ const orgResult = await getPool ( ) . query ( orgQuery , [ agrementId ] ) ;
34+ organismeId = orgResult . rows ?. [ 0 ] ?. organisme_id ?? null ;
35+ }
36+
37+ log . i ( "IN" ) ;
38+
39+ const query = `
40+ SELECT uo.org_id
41+ FROM front.user_organisme uo
42+ JOIN front.users u ON uo.use_id = u.id
43+ WHERE u.id = $1
44+ ` ;
45+ const { rows } = await getPool ( ) . query ( query , [ userId ] ) ;
46+ if (
47+ ! rows ||
48+ rows . length !== 1 ||
49+ ! organismeId ||
50+ rows [ 0 ] . org_id . toString ( ) !== organismeId . toString ( )
51+ ) {
52+ log . w ( "Utilisateur non autorisé à modifier l'agrement" ) ;
53+ return next (
54+ new AppError ( "Vous n'êtes pas autorisé à modifier cet agrément" , {
55+ statusCode : 403 ,
56+ } ) ,
57+ ) ;
58+ }
59+ log . i ( "DONE" ) ;
60+ next ( ) ;
61+ } catch ( error ) {
62+ log . w ( "Erreur dans checkPermissionAgrement:" , error ) ;
63+ next ( error ) ;
4664 }
47- log . i ( "DONE" ) ;
48- next ( ) ;
4965}
5066
5167export default checkPermissionAgrement ;
0 commit comments