Joaquín Reñé
2025-10-07 146a0fb8b0e90f9196e569152f649baf60d6cc8f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*
 * Copyright @ 2013 CurisTEC, S.A.S. All Rights Reserved.
 */
package net.curisit.securis.services;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import jakarta.annotation.security.RolesAllowed;
import jakarta.enterprise.context.RequestScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.curisit.integrity.commons.Utils;
import net.curisit.securis.DefaultExceptionHandler;
import net.curisit.securis.SeCurisException;
import net.curisit.securis.db.Organization;
import net.curisit.securis.db.User;
import net.curisit.securis.db.User.Rol;
import net.curisit.securis.ioc.EnsureTransaction;
import net.curisit.securis.security.BasicSecurityContext;
import net.curisit.securis.security.Securable;
import net.curisit.securis.utils.TokenHelper;
/**
 * OrganizationResource
 * <p>
 * CRUD and listing of organizations. Non-admin users are scoped by their
 * accessible organization ids when listing.
 *
 * Last reviewed by JRA on Oct 5, 2025.
 */
@Path("/organization")
@RequestScoped
public class OrganizationResource {
   private static final Logger LOG = LogManager.getLogger(OrganizationResource.class);
   @Context EntityManager em;
   @Context BasicSecurityContext bsc;
   public OrganizationResource() { }
   /**
    * index
    * <p>
    * List organizations. For admins returns all; for non-admins filters
    * by the ids in {@link BasicSecurityContext#getOrganizationsIds()}.
    *
    * @return 200 OK with the list.
    */
   @GET
   @Path("/")
   @Produces({ MediaType.APPLICATION_JSON })
   @Securable
   public Response index() {
       LOG.info("Getting organizations list ");
       em.clear();
       TypedQuery<Organization> q;
       if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
           LOG.info("GEtting all orgs for user: " + bsc.getUserPrincipal());
           q = em.createNamedQuery("list-organizations", Organization.class);
       } else {
           if (bsc.getOrganizationsIds() == null || bsc.getOrganizationsIds().isEmpty()) {
               return Response.ok().build();
           } else {
               q = em.createNamedQuery("list-organizations-by-ids", Organization.class);
               q.setParameter("list_ids", bsc.getOrganizationsIds());
           }
       }
       List<Organization> list = q.getResultList();
       return Response.ok(list).build();
   }
   /**
    * get
    * <p>
    * Fetch an organization by id.
    *
    * @param orgid organization id (string form).
    * @param token header token (unused).
    * @return 200 OK with entity or 404 if not found.
    */
   @GET
   @Path("/{orgid}")
   @Produces({ MediaType.APPLICATION_JSON })
   @Securable
   public Response get(@PathParam("orgid") String orgid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
       LOG.info("Getting organization data for id: {}: ", orgid);
       if (orgid == null || "".equals(orgid)) {
           LOG.error("Organization ID is mandatory");
           return Response.status(Status.NOT_FOUND).build();
       }
       em.clear();
       Organization org = em.find(Organization.class, Integer.parseInt(orgid));
       if (org == null) {
           LOG.error("Organization with id {} not found in DB", orgid);
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization not found, id: " + orgid).build();
       }
       return Response.ok(org).build();
   }
   /**
    * create
    * <p>
    * Create a new organization, setting optional parent and user members.
    * Requires ADMIN.
    *
    * @param org payload with code/name/etc., optional parentOrgId and usersIds.
    * @return 200 OK with created organization or 404 when parent/user not found.
    */
   @POST
   @Path("/")
   @Consumes(MediaType.APPLICATION_JSON)
   @Produces({ MediaType.APPLICATION_JSON })
   @EnsureTransaction
   @Securable(roles = Rol.ADMIN)
   @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
   public Response create(Organization org) {
       LOG.info("Creating new organization");
       try {
           this.setParentOrg(org, org.getParentOrgId(), em);
       } catch (SeCurisException e) {
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
       }
       Set<User> users = null;
       Set<String> usersIds = org.getUsersIds();
       if (usersIds != null && !usersIds.isEmpty()) {
           users = new HashSet<>();
           for (String username : usersIds) {
               User user = em.find(User.class, username);
               if (user == null) {
                   LOG.error("Organization user with id {} not found in DB", username);
                   return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization's user not found with ID: " + username).build();
               }
               users.add(user);
           }
       }
       org.setUsers(users);
       org.setCreationTimestamp(new Date());
       em.persist(org);
       return Response.ok(org).build();
   }
   /**
    * modify
    * <p>
    * Update an organization. Validates no cyclic parent relationship,
    * updates parent and user set. Requires ADMIN.
    *
    * @param org   new values (including optional parent/usersIds).
    * @param orgid target id.
    * @param token (unused) header token.
    * @return 200 OK with updated organization, or specific error status.
    */
   @PUT
   @POST
   @Path("/{orgid}")
   @Consumes(MediaType.APPLICATION_JSON)
   @Produces({ MediaType.APPLICATION_JSON })
   @EnsureTransaction
   @Securable(roles = Rol.ADMIN)
   @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
   public Response modify(Organization org, @PathParam("orgid") String orgid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
       LOG.info("Modifying organization with id: {}", orgid);
       Organization currentOrg = em.find(Organization.class, Integer.parseInt(orgid));
       if (currentOrg == null) {
           LOG.error("Organization with id {} not found in DB", orgid);
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization not found with ID: " + orgid).build();
       }
       try {
           this.setParentOrg(currentOrg, org.getParentOrgId(), em);
       } catch (SeCurisException e) {
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
       }
       if (org.getParentOrganization() != null && (isCyclicalRelationship(currentOrg.getId(), org.getParentOrganization()))) {
           LOG.error("Organization parent generate a cyclical relationship, parent id {}, current id: {}", org.getParentOrgId(), currentOrg.getId());
           return Response.status(Status.FORBIDDEN).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER,
                   "Cyclical relationships are not allowed, please change the parent organization, current Parent: " + org.getParentOrganization().getName()).build();
       }
       try {
           setOrgUsers(currentOrg, org.getUsersIds(), em);
       } catch (SeCurisException e) {
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
       }
       currentOrg.setCode(org.getCode());
       currentOrg.setName(org.getName());
       currentOrg.setDescription(org.getDescription());
       em.persist(currentOrg);
       return Response.ok(currentOrg).build();
   }
   /**
    * delete
    * <p>
    * Delete an organization if it has no children. Requires ADMIN.
    *
    * @param orgid target id.
    * @param req   request (unused).
    * @return 200 OK with success map, or 404/403 on constraints.
    */
   @DELETE
   @Path("/{orgid}")
   @EnsureTransaction
   @Produces({ MediaType.APPLICATION_JSON })
   @Securable(roles = Rol.ADMIN)
   @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
   public Response delete(@PathParam("orgid") String orgid, @Context HttpServletRequest req) {
       LOG.info("Deleting organization with id: {}", orgid);
       Organization org = em.find(Organization.class, Integer.parseInt(orgid));
       if (org == null) {
           LOG.error("Organization with id {} can not be deleted, It was not found in DB", orgid);
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization was not found, ID: " + orgid).build();
       }
       if (org.getChildOrganizations() != null && !org.getChildOrganizations().isEmpty()) {
           LOG.error("Organization has children and can not be deleted, ID: " + orgid);
           return Response.status(Status.FORBIDDEN).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization has children and can not be deleted, ID: " + orgid).build();
       }
       em.remove(org);
       return Response.ok(Utils.createMap("success", true, "id", orgid)).build();
   }
   // ---------------------------------------------------------------------
   // Helpers
   // ---------------------------------------------------------------------
   /** 
    * isCyclicalRelationship<p>
    * Detects cycles by walking up the parent chain. 
    * 
    * @param currentId
    * @param parent
    * @return isCyclicalRelationship
    */
   private boolean isCyclicalRelationship(int currentId, Organization parent) {
       while (parent != null) {
           if (parent.getId() == currentId) return true;
           parent = parent.getParentOrganization();
       }
       return false;
   }
   /** 
    * setParentOrg<p>
    * Resolve and set parent organization (nullable). 
    * 
    * @param org
    * @param parentOrgId
    * @param entitymanager
    * @throws SeCurisException
    */
   private void setParentOrg(Organization org, Integer parentOrgId, EntityManager em) throws SeCurisException {
       Organization parentOrg = null;
       if (parentOrgId != null) {
           parentOrg = em.find(Organization.class, parentOrgId);
           if (parentOrg == null) {
               LOG.error("Organization parent with id {} not found in DB", org.getParentOrgId());
               throw new SecurityException("Organization's parent not found with ID: " + org.getParentOrgId());
           }
       }
       org.setParentOrganization(parentOrg);
   }
   /** 
    * setOrgUsers<p>
    * Replace organization users from the provided usernames set. 
    * 
    * @param org
    * @param usersIds
    * @param entityManager
    * @throws SeCurisException
    */
   private void setOrgUsers(Organization org, Set<String> usersIds, EntityManager em) throws SeCurisException {
       Set<User> users = null;
       if (usersIds != null && !usersIds.isEmpty()) {
           users = new HashSet<>();
           for (String username : usersIds) {
               User user = em.find(User.class, username);
               if (user == null) {
                   LOG.error("Organization user with id '{}' not found in DB", username);
                   throw new SecurityException("Organization's user not found with ID: " + username);
               }
               users.add(user);
           }
       }
       org.setUsers(users);
   }
}