From 6379e7f9b48f1c1b8ee9ed750740d6df0534b919 Mon Sep 17 00:00:00 2001 From: Gregory Rushton Date: Fri, 17 Jul 2026 11:35:07 -0400 Subject: [PATCH 1/9] refactor: migrate to AuthUser -> DuosUser where possible --- .../resources/DACAutomationRuleResource.java | 19 ++- .../consent/http/resources/DacResource.java | 7 +- .../resources/DataAccessRequestResource.java | 45 +++---- .../http/resources/DatasetResource.java | 17 ++- .../consent/http/resources/DraftResource.java | 47 ++++---- .../http/resources/EmailNotifierResource.java | 6 +- .../http/resources/FeatureFlagResource.java | 19 ++- .../consent/http/resources/MailResource.java | 8 +- .../consent/http/resources/MatchResource.java | 3 +- .../consent/http/resources/StudyResource.java | 17 +-- .../consent/http/resources/UserResource.java | 26 ++-- .../consent/http/resources/VoteResource.java | 20 ++- .../DACAutomationRuleResourceTest.java | 28 ++--- .../http/resources/DacResourceTest.java | 25 +++- .../DataAccessRequestResourceTest.java | 101 ++++++---------- .../http/resources/DatasetResourceTest.java | 38 +++--- .../http/resources/DraftResourceTest.java | 67 +++++----- .../resources/EmailNotifierResourceTest.java | 16 +-- .../resources/FeatureFlagResourceTest.java | 32 ++--- .../http/resources/MailResourceTest.java | 24 ++-- .../http/resources/MatchResourceTest.java | 2 +- .../http/resources/StudyResourceTest.java | 60 ++++----- .../http/resources/UserResourceTest.java | 114 ++++++------------ .../http/resources/VoteResourceTest.java | 69 +++++------ 24 files changed, 347 insertions(+), 463 deletions(-) diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResource.java index 5c8a60ca1f..187c1cde59 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResource.java @@ -15,28 +15,23 @@ import jakarta.ws.rs.core.Response; import java.util.List; import org.broadinstitute.consent.http.enumeration.UserRoles; -import org.broadinstitute.consent.http.models.AuthUser; import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.models.User; import org.broadinstitute.consent.http.rules.AuditPageResults; import org.broadinstitute.consent.http.rules.DACAutomationRule; import org.broadinstitute.consent.http.service.DACAutomationRuleService; import org.broadinstitute.consent.http.service.DacService; -import org.broadinstitute.consent.http.service.UserService; @Path("api/dac/") public class DACAutomationRuleResource extends Resource { private final DACAutomationRuleService ruleService; private final DacService dacService; - private final UserService userService; @Inject - public DACAutomationRuleResource( - DACAutomationRuleService ruleService, DacService dacService, UserService userService) { + public DACAutomationRuleResource(DACAutomationRuleService ruleService, DacService dacService) { this.ruleService = ruleService; this.dacService = dacService; - this.userService = userService; } @GET @@ -56,9 +51,9 @@ public Response getAllRules(@Auth DuosUser duosUser) { @Path("{dacId}/rules") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({Resource.ADMIN, Resource.CHAIRPERSON}) - public Response getAvailableRules(@Auth AuthUser authUser, @PathParam("dacId") Integer dacId) { + public Response getAvailableRules(@Auth DuosUser duosUser, @PathParam("dacId") Integer dacId) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); validateAdminOrChairForDAC(user, dacId); if (dacService.findById(dacId) == null) { @@ -78,12 +73,12 @@ public Response getAvailableRules(@Auth AuthUser authUser, @PathParam("dacId") I @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({Resource.ADMIN, Resource.CHAIRPERSON}) public Response getDacRuleAuditRecords( - @Auth AuthUser authUser, + @Auth DuosUser duosUser, @PathParam("dacId") Integer dacId, @QueryParam("page") Integer page, @QueryParam("pageSize") Integer pageSize) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); validateAdminOrChairForDAC(user, dacId); if (dacService.findById(dacId) == null) { @@ -103,11 +98,11 @@ public Response getDacRuleAuditRecords( @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({Resource.CHAIRPERSON}) public Response toggleRule( - @Auth AuthUser authUser, + @Auth DuosUser duosUser, @PathParam("dacId") Integer dacId, @PathParam("ruleId") Integer ruleId) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); validateIsChairOfDAC(user, dacId); if (dacService.findById(dacId) == null) { diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DacResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DacResource.java index 9fa770e3df..56f3f1c350 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DacResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DacResource.java @@ -22,7 +22,6 @@ import java.util.Objects; import java.util.Optional; import org.broadinstitute.consent.http.enumeration.UserRoles; -import org.broadinstitute.consent.http.models.AuthUser; import org.broadinstitute.consent.http.models.Dac; import org.broadinstitute.consent.http.models.DacDatasetExternalizationRequest; import org.broadinstitute.consent.http.models.DacDatasetExternalizationResponse; @@ -51,7 +50,7 @@ public DacResource(DacService dacService, DatasetService datasetService) { @Produces("application/json") @RolesAllowed({ADMIN, MEMBER, CHAIRPERSON, RESEARCHER}) public Response findAll( - @Auth AuthUser authUser, @QueryParam("withUsers") Optional withUsers) { + @Auth DuosUser duosUser, @QueryParam("withUsers") Optional withUsers) { try { final Boolean includeUsers = withUsers.orElse(true); List dacs = dacService.findDacsWithMembersOption(includeUsers); @@ -143,7 +142,7 @@ public Response updateDac(@Auth DuosUser duosUser, String json) { @Path("{dacId}") @Produces("application/json") @RolesAllowed({ADMIN, MEMBER, CHAIRPERSON}) - public Response findDacById(@Auth AuthUser authUser, @PathParam("dacId") Integer dacId) { + public Response findDacById(@Auth DuosUser duosUser, @PathParam("dacId") Integer dacId) { try { Dac dac = findDacOrThrow(dacId); return Response.ok().entity(unmarshal(dac)).build(); @@ -264,7 +263,7 @@ public Response findAllDacDatasets(@Auth DuosUser duosUser, @PathParam("dacId") @Path("users/{term}") @Produces("application/json") @RolesAllowed({ADMIN, MEMBER, CHAIRPERSON}) - public Response filterUsers(@Auth AuthUser authUser, @PathParam("term") String term) { + public Response filterUsers(@Auth DuosUser duosUser, @PathParam("term") String term) { try { List users = dacService.findAllDACUsersBySearchString(term); return Response.ok().entity(users).build(); diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DataAccessRequestResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DataAccessRequestResource.java index f22d335d40..1ab77982bc 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DataAccessRequestResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DataAccessRequestResource.java @@ -41,7 +41,6 @@ import org.broadinstitute.consent.http.enumeration.UserRoles; import org.broadinstitute.consent.http.exceptions.LibraryCardRequiredException; import org.broadinstitute.consent.http.exceptions.SubmittedDARCannotBeEditedException; -import org.broadinstitute.consent.http.models.AuthUser; import org.broadinstitute.consent.http.models.Dac; import org.broadinstitute.consent.http.models.DataAccessAgreement; import org.broadinstitute.consent.http.models.DataAccessRequest; @@ -117,9 +116,9 @@ public Response getDataAccessRequests(@Auth DuosUser duosUser) { @RolesAllowed(RESEARCHER) @Path("/v2") public Response createDataAccessRequest( - @Auth AuthUser authUser, @Context Request request, @Context UriInfo info, String dar) { + @Auth DuosUser duosUser, @Context Request request, @Context UriInfo info, String dar) { try { - User user = findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DataAccessRequest payload = populateDarFromJsonString(user, dar); DataAccessRequest newDar = @@ -205,9 +204,9 @@ public Response getDatasetDaaSnapshotsByReferenceId( @Produces("application/json") @RolesAllowed(RESEARCHER) public Response updateByReferenceId( - @Auth AuthUser authUser, @PathParam("referenceId") String referenceId, String dar) { + @Auth DuosUser duosUser, @PathParam("referenceId") String referenceId, String dar) { try { - User user = findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DataAccessRequest originalDar = dataAccessRequestService.findByReferenceId(referenceId); checkAuthorizedUpdateUser(user, originalDar); DataAccessRequestData data = DataAccessRequestData.fromString(dar); @@ -228,9 +227,9 @@ public Response updateByReferenceId( @Produces("application/json") @Path("/v2/draft") @RolesAllowed(RESEARCHER) - public Response getDraftDataAccessRequests(@Auth AuthUser authUser) { + public Response getDraftDataAccessRequests(@Auth DuosUser duosUser) { try { - User user = findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); List draftDars = dataAccessRequestService.findAllDraftDataAccessRequestsByUser(user.getUserId()); return Response.ok().entity(draftDars).build(); @@ -243,9 +242,9 @@ public Response getDraftDataAccessRequests(@Auth AuthUser authUser) { @Produces("application/json") @Path("/v2/draft/{referenceId}") @RolesAllowed(RESEARCHER) - public Response getDraftDar(@Auth AuthUser authUser, @PathParam("referenceId") String id) { + public Response getDraftDar(@Auth DuosUser duosUser, @PathParam("referenceId") String id) { try { - User user = findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DataAccessRequest dar = dataAccessRequestService.findByReferenceId(id); if (dar.getUserId().equals(user.getUserId())) { return Response.ok().entity(dar).build(); @@ -262,9 +261,9 @@ public Response getDraftDar(@Auth AuthUser authUser, @PathParam("referenceId") S @Path("/v2/draft") @RolesAllowed(RESEARCHER) public Response createDraftDataAccessRequest( - @Auth AuthUser authUser, @Context UriInfo info, String dar) { + @Auth DuosUser duosUser, @Context UriInfo info, String dar) { try { - User user = findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DataAccessRequest newDar = populateDarFromJsonString(user, dar); DataAccessRequest result = dataAccessRequestService.insertDraftDataAccessRequest(user, newDar); @@ -281,9 +280,9 @@ public Response createDraftDataAccessRequest( @Path("/v2/draft/{referenceId}") @RolesAllowed(RESEARCHER) public Response updatePartialDataAccessRequest( - @Auth AuthUser authUser, @PathParam("referenceId") String referenceId, String dar) { + @Auth DuosUser duosUser, @PathParam("referenceId") String referenceId, String dar) { try { - User user = findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DataAccessRequest originalDar = dataAccessRequestService.findByReferenceId(referenceId); checkAuthorizedUpdateUser(user, originalDar); DataAccessRequestData data = DataAccessRequestData.fromString(dar); @@ -333,12 +332,12 @@ public Response getIrbDocument( @Path("/v2/{referenceId}/irbDocument") @RolesAllowed({RESEARCHER}) public Response uploadIrbDocument( - @Auth AuthUser authUser, + @Auth DuosUser duosUser, @PathParam("referenceId") String referenceId, @FormDataParam("file") InputStream uploadInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { try { - User user = findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DataAccessRequest dar = getDarById(referenceId); checkAuthorizedUpdateUser(user, dar); DataAccessRequest updatedDar = @@ -376,7 +375,7 @@ public Response approveCloseout( @Path("/v2/progress_report/{parentReferenceId}") @RolesAllowed({RESEARCHER}) public Response postProgressReport( - @Auth AuthUser authUser, + @Auth DuosUser duosUser, @Context Request request, @PathParam("parentReferenceId") String parentReferenceId, @FormDataParam("dar") String dar, @@ -385,7 +384,7 @@ public Response postProgressReport( @FormDataParam("ethicsApprovalRequiredFile") InputStream ethicsInputStream, @FormDataParam("ethicsApprovalRequiredFile") FormDataContentDisposition ethicsFileDetails) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); // added here because other dataAccessRequestServices calls are invoked that do not normally // require this sequence. hasValidActiveERACredentials will also check for a LC so no // additional LC check needed. @@ -522,12 +521,12 @@ public Response getCollaborationDocument( @Path("/v2/{referenceId}/collaborationDocument") @RolesAllowed({RESEARCHER}) public Response uploadCollaborationDocument( - @Auth AuthUser authUser, + @Auth DuosUser duosUser, @PathParam("referenceId") String referenceId, @FormDataParam("file") InputStream uploadInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { try { - User user = findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DataAccessRequest dar = getDarById(referenceId); checkAuthorizedUpdateUser(user, dar); DataAccessRequest updatedDar = @@ -554,14 +553,6 @@ public Response deleteDar(@Auth DuosUser duosUser, @PathParam("referenceId") Str } } - private User findUserByEmail(String email) { - User user = userService.findUserByEmail(email); - if (user == null) { - throw new NotFoundException("Unable to find User with the provided email: " + email); - } - return user; - } - private DataAccessRequest populateDarFromJsonString(User user, String json) { DataAccessRequest newDar = new DataAccessRequest(); DataAccessRequestData data = DataAccessRequestData.populateDARData(json); diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DatasetResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DatasetResource.java index ab0e812ad6..87c5259bee 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DatasetResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DatasetResource.java @@ -41,7 +41,6 @@ import org.broadinstitute.consent.http.cloudstore.GCSService; import org.broadinstitute.consent.http.enumeration.UserRoles; import org.broadinstitute.consent.http.exceptions.UnprocessableEntityException; -import org.broadinstitute.consent.http.models.AuthUser; import org.broadinstitute.consent.http.models.DataUse; import org.broadinstitute.consent.http.models.Dataset; import org.broadinstitute.consent.http.models.DatasetPatch; @@ -107,7 +106,7 @@ public DatasetResource( * With that object, we can fully create datasets from the provided values. */ public Response createDatasetRegistration( - @Auth AuthUser authUser, FormDataMultiPart multipart, @FormDataParam("dataset") String json) { + @Auth DuosUser duosUser, FormDataMultiPart multipart, @FormDataParam("dataset") String json) { try { if (json == null || json.isEmpty()) { throw new BadRequestException("Dataset is required"); @@ -122,7 +121,7 @@ public Response createDatasetRegistration( DatasetRegistrationSchemaV1 registration = GsonUtil.getInstance().fromJson(json, DatasetRegistrationSchemaV1.class); - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); // key: field name (not file name), value: file body part Map files = extractFilesFromMultiPart(multipart); @@ -408,7 +407,7 @@ public Response delete(@Auth DuosUser duosUser, @PathParam("datasetId") Integer @POST @Path("/index") @RolesAllowed(ADMIN) - public Response indexDatasets(@Auth AuthUser authUser) { + public Response indexDatasets(@Auth DuosUser duosUser) { try { var datasetIds = datasetService.findAllDatasetIds(); StreamingOutput indexResponse = elasticSearchService.indexDatasetIds(datasetIds); @@ -421,7 +420,7 @@ public Response indexDatasets(@Auth AuthUser authUser) { @POST @Path("/index/{datasetId}") @RolesAllowed(ADMIN) - public Response indexDataset(@Auth AuthUser authUser, @PathParam("datasetId") Integer datasetId) { + public Response indexDataset(@Auth DuosUser duosUser, @PathParam("datasetId") Integer datasetId) { try { return elasticSearchService.indexDataset(datasetId); } catch (Exception e) { @@ -433,9 +432,9 @@ public Response indexDataset(@Auth AuthUser authUser, @PathParam("datasetId") In @Path("/index/{datasetId}") @RolesAllowed(ADMIN) public Response deleteDatasetIndex( - @Auth AuthUser authUser, @PathParam("datasetId") Integer datasetId) { + @Auth DuosUser duosUser, @PathParam("datasetId") Integer datasetId) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); return elasticSearchService.deleteIndex(datasetId, user.getUserId()); } catch (Exception e) { return createExceptionResponse(e); @@ -477,9 +476,9 @@ public Response searchDatasetIndexStream(@Auth DuosUser duosUser, String query) @RolesAllowed(ADMIN) @Path("/{id}/datause") public Response updateDatasetDataUse( - @Auth AuthUser authUser, @PathParam("id") Integer id, String dataUseJson) { + @Auth DuosUser duosUser, @PathParam("id") Integer id, String dataUseJson) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); // TODO: Replace new Gson() with GsonUtil.buildGson() — deferred pending Gson configuration // investigation Gson gson = new Gson(); diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DraftResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DraftResource.java index 5d326f9445..b7907efffe 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DraftResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DraftResource.java @@ -28,26 +28,23 @@ import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; -import org.broadinstitute.consent.http.models.AuthUser; import org.broadinstitute.consent.http.models.DraftInterface; import org.broadinstitute.consent.http.models.DraftStudyDataset; import org.broadinstitute.consent.http.models.DraftSummary; +import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.models.FileStorageObject; import org.broadinstitute.consent.http.models.User; import org.broadinstitute.consent.http.service.DraftService; -import org.broadinstitute.consent.http.service.UserService; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.FormDataMultiPart; @Path("api/draft") public class DraftResource extends Resource { - private final UserService userService; private final DraftService draftService; @Inject - public DraftResource(UserService userService, DraftService draftService) { - this.userService = userService; + public DraftResource(DraftService draftService) { this.draftService = draftService; } @@ -55,9 +52,9 @@ public DraftResource(UserService userService, DraftService draftService) { @Produces({MediaType.APPLICATION_JSON}) @Path("/v1") @RolesAllowed({ADMIN, DATASUBMITTER}) - public Response getDrafts(@Auth AuthUser authUser) { + public Response getDrafts(@Auth DuosUser duosUser) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); Collection draftSummaries = draftService.findDraftSummariesForUser(user); return Response.ok().entity(draftSummaries).build(); } catch (Exception e) { @@ -70,9 +67,9 @@ public Response getDrafts(@Auth AuthUser authUser) { @Produces({MediaType.APPLICATION_JSON}) @Path("/v1") @RolesAllowed({ADMIN, DATASUBMITTER}) - public Response createDraftRegistration(@Auth AuthUser authUser, String json) { + public Response createDraftRegistration(@Auth DuosUser duosUser, String json) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DraftInterface draft = new DraftStudyDataset(json, user); draftService.insertDraft(draft); URI uri = getDraftURI(draft); @@ -87,9 +84,9 @@ public Response createDraftRegistration(@Auth AuthUser authUser, String json) { @Path("/v1/{draftUUID}") @RolesAllowed({ADMIN, DATASUBMITTER}) public Response getDraftDocument( - @Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID) { + @Auth DuosUser duosUser, @PathParam("draftUUID") String draftUUID) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); StreamingOutput output = draftService.draftAsJson(draft); return Response.ok().entity(output).build(); @@ -104,9 +101,9 @@ public Response getDraftDocument( @Path("/v1/{draftUUID}") @RolesAllowed({ADMIN, DATASUBMITTER}) public Response updateDraft( - @Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID, String json) { + @Auth DuosUser duosUser, @PathParam("draftUUID") String draftUUID, String json) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); draft.setJson(json); DraftInterface responseDraft = draftService.updateDraft(draft, user); @@ -122,9 +119,9 @@ public Response updateDraft( @Path("/v1/{draftUUID}") @RolesAllowed({ADMIN, DATASUBMITTER}) public Response patchDraftName( - @Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID, String name) { + @Auth DuosUser duosUser, @PathParam("draftUUID") String draftUUID, String name) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); draft.setName(name); DraftInterface responseDraft = draftService.updateDraft(draft, user); @@ -138,9 +135,9 @@ public Response patchDraftName( @Produces(MediaType.APPLICATION_JSON) @Path("/v1/{draftUUID}") @RolesAllowed({ADMIN, DATASUBMITTER}) - public Response deleteDraft(@Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID) { + public Response deleteDraft(@Auth DuosUser duosUser, @PathParam("draftUUID") String draftUUID) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); draftService.deleteDraft(draft, user); } catch (Exception e) { @@ -154,9 +151,9 @@ public Response deleteDraft(@Auth AuthUser authUser, @PathParam("draftUUID") Str @Path("/v1/{draftUUID}/attachments") @RolesAllowed({ADMIN, DATASUBMITTER}) public Response getAttachments( - @Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID) { + @Auth DuosUser duosUser, @PathParam("draftUUID") String draftUUID) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); return Response.ok().entity(draft.getStoredFiles()).build(); } catch (Exception e) { @@ -170,11 +167,11 @@ public Response getAttachments( @Path("/v1/{draftUUID}/attachments") @RolesAllowed({ADMIN, DATASUBMITTER}) public Response addAttachments( - @Auth AuthUser authUser, + @Auth DuosUser duosUser, @PathParam("draftUUID") String draftUUID, FormDataMultiPart multipart) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); Map files = extractFilesFromMultiPart(multipart); List storedFiles = draftService.addAttachments(draft, user, files); @@ -189,11 +186,11 @@ public Response addAttachments( @Path("/v1/{draftUUID}/attachments/{fileId}") @RolesAllowed({ADMIN, DATASUBMITTER}) public Response getAttachment( - @Auth AuthUser authUser, + @Auth DuosUser duosUser, @PathParam("draftUUID") String draftUUID, @PathParam("fileId") Integer fileId) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); Set filteredAttachments = draft.getStoredFiles().stream() @@ -228,11 +225,11 @@ public Response getAttachment( @Path("/v1/{draftUUID}/attachments/{fileId}") @RolesAllowed({ADMIN, DATASUBMITTER}) public Response deleteDraftAttachment( - @Auth AuthUser authUser, + @Auth DuosUser duosUser, @PathParam("draftUUID") String draftUUID, @PathParam("fileId") Integer fileId) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); draftService.deleteDraftAttachment(draft, user, fileId); return Response.ok().build(); diff --git a/src/main/java/org/broadinstitute/consent/http/resources/EmailNotifierResource.java b/src/main/java/org/broadinstitute/consent/http/resources/EmailNotifierResource.java index 8100d4eaba..3436fe0e3a 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/EmailNotifierResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/EmailNotifierResource.java @@ -10,7 +10,7 @@ import jakarta.ws.rs.PathParam; import jakarta.ws.rs.core.Response; import java.util.concurrent.ExecutorService; -import org.broadinstitute.consent.http.models.AuthUser; +import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.service.DataAccessRequestService; import org.broadinstitute.consent.http.service.EmailService; @@ -34,7 +34,7 @@ public EmailNotifierResource( @POST @Path("/reminderMessage/{voteId}") @RolesAllowed({ADMIN, CHAIRPERSON}) - public Response sendReminderMessage(@Auth AuthUser authUser, @PathParam("voteId") String voteId) { + public Response sendReminderMessage(@Auth DuosUser duosUser, @PathParam("voteId") String voteId) { try { dataAccessRequestService.sendReminderMessage(Integer.valueOf(voteId)); return Response.ok().build(); @@ -46,7 +46,7 @@ public Response sendReminderMessage(@Auth AuthUser authUser, @PathParam("voteId" @GET @Path("/dailyMessages") @RolesAllowed({SERVICE_ACCOUNT}) - public Response sendDailyMessages(@Auth AuthUser authUser) { + public Response sendDailyMessages(@Auth DuosUser duosUser) { executor.submit(this::processExpirationNotices); executor.submit(this::processVoteDigestMessages); executor.submit(this::processNewDatasetInDUOSNotifications); diff --git a/src/main/java/org/broadinstitute/consent/http/resources/FeatureFlagResource.java b/src/main/java/org/broadinstitute/consent/http/resources/FeatureFlagResource.java index 5daaa6e022..3b7c78e32f 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/FeatureFlagResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/FeatureFlagResource.java @@ -15,29 +15,26 @@ import jakarta.ws.rs.core.UriInfo; import java.net.URI; import java.util.Map; -import org.broadinstitute.consent.http.models.AuthUser; +import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.models.FeatureFlag; import org.broadinstitute.consent.http.models.User; import org.broadinstitute.consent.http.service.FeatureFlagService; -import org.broadinstitute.consent.http.service.UserService; @Path("api/feature") public class FeatureFlagResource extends Resource { private final FeatureFlagService featureFlagService; - private final UserService userService; @Inject - public FeatureFlagResource(FeatureFlagService featureFlagService, UserService userService) { + public FeatureFlagResource(FeatureFlagService featureFlagService) { this.featureFlagService = featureFlagService; - this.userService = userService; } /** * Create or update a feature flag (admin only) * * @param info URI information - * @param authUser The authenticated user + * @param duosUser The authenticated user * @param id The feature flag id * @param body Request body containing the value * @return The created or updated feature flag @@ -49,7 +46,7 @@ public FeatureFlagResource(FeatureFlagService featureFlagService, UserService us @RolesAllowed({ADMIN}) public Response createOrUpdateFeatureFlag( @Context UriInfo info, - @Auth AuthUser authUser, + @Auth DuosUser duosUser, @PathParam("id") String id, Map body) { try { @@ -60,7 +57,7 @@ public Response createOrUpdateFeatureFlag( .build(); } - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); boolean existed = featureFlagService.exists(id); FeatureFlag flag = featureFlagService.createOrUpdateFeatureFlag(id, value, user.getUserId()); @@ -78,16 +75,16 @@ public Response createOrUpdateFeatureFlag( /** * Delete a feature flag (admin only) * - * @param authUser The authenticated user + * @param duosUser The authenticated user * @param id The feature flag id * @return No content response */ @DELETE @Path("/{id}") @RolesAllowed({ADMIN}) - public Response deleteFeatureFlag(@Auth AuthUser authUser, @PathParam("id") String id) { + public Response deleteFeatureFlag(@Auth DuosUser duosUser, @PathParam("id") String id) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); featureFlagService.deleteFeatureFlag(id, user.getUserId()); return Response.noContent().build(); } catch (Exception e) { diff --git a/src/main/java/org/broadinstitute/consent/http/resources/MailResource.java b/src/main/java/org/broadinstitute/consent/http/resources/MailResource.java index 03037aeaea..a38792421c 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/MailResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/MailResource.java @@ -21,7 +21,7 @@ import java.util.Date; import org.apache.commons.lang3.StringUtils; import org.broadinstitute.consent.http.enumeration.EmailType; -import org.broadinstitute.consent.http.models.AuthUser; +import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.service.EmailService; @Path("api/mail") @@ -39,7 +39,7 @@ public MailResource(EmailService emailService) { @Path("/type/{type}") @RolesAllowed({ADMIN}) public Response getEmailByType( - @Auth AuthUser authUser, + @Auth DuosUser duosUser, @PathParam("type") EmailType emailType, @DefaultValue("20") @QueryParam("limit") Integer limit, @DefaultValue("0") @QueryParam("offset") Integer offset) { @@ -54,7 +54,7 @@ public Response getEmailByType( @Path("/user/{userId}") @RolesAllowed({ADMIN}) public Response getEmailByUser( - @Auth AuthUser authUser, + @Auth DuosUser duosUser, @PathParam("userId") Integer userId, @DefaultValue("20") @QueryParam("limit") Integer limit, @DefaultValue("0") @QueryParam("offset") Integer offset) { @@ -69,7 +69,7 @@ public Response getEmailByUser( @Path("/range") @RolesAllowed({ADMIN}) public Response getEmailByDateRange( - @Auth AuthUser authUser, + @Auth DuosUser duosUser, @QueryParam("start") String start, @QueryParam("end") String end, @DefaultValue("20") @QueryParam("limit") Integer limit, diff --git a/src/main/java/org/broadinstitute/consent/http/resources/MatchResource.java b/src/main/java/org/broadinstitute/consent/http/resources/MatchResource.java index 1a74440e28..5dde4e5a81 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/MatchResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/MatchResource.java @@ -15,7 +15,6 @@ import java.util.List; import java.util.Objects; import java.util.stream.Collectors; -import org.broadinstitute.consent.http.models.AuthUser; import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.models.Match; import org.broadinstitute.consent.http.service.MatchService; @@ -62,7 +61,7 @@ public Response getMatchesForLatestDataAccessElectionsByPurposeIds( @Path("/reprocess/purpose/{purposeId}") @RolesAllowed({Resource.ADMIN}) public Response reprocessPurposeMatches( - @Auth AuthUser authUser, @PathParam("purposeId") String purposeId) { + @Auth DuosUser duosUser, @PathParam("purposeId") String purposeId) { try { service.reprocessMatchesForPurpose(purposeId); List matches = service.findMatchesByPurposeId(purposeId); diff --git a/src/main/java/org/broadinstitute/consent/http/resources/StudyResource.java b/src/main/java/org/broadinstitute/consent/http/resources/StudyResource.java index 88f443427b..e165fd862c 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/StudyResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/StudyResource.java @@ -30,7 +30,6 @@ import java.util.Objects; import org.apache.commons.validator.routines.EmailValidator; import org.broadinstitute.consent.http.enumeration.UserRoles; -import org.broadinstitute.consent.http.models.AuthUser; import org.broadinstitute.consent.http.models.Dataset; import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.models.Study; @@ -45,7 +44,6 @@ import org.broadinstitute.consent.http.service.DatasetRegistrationService; import org.broadinstitute.consent.http.service.DatasetService; import org.broadinstitute.consent.http.service.ElasticSearchService; -import org.broadinstitute.consent.http.service.UserService; import org.broadinstitute.consent.http.util.gson.GsonUtil; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.FormDataMultiPart; @@ -56,7 +54,6 @@ public class StudyResource extends Resource { private final DatasetService datasetService; private final DatasetRegistrationService datasetRegistrationService; - private final UserService userService; private final ElasticSearchService elasticSearchService; private final ObjectMapper objectMapper = new ObjectMapper(); private final StudyUpdateRequestValidator studyUpdateRequestValidator; @@ -64,11 +61,9 @@ public class StudyResource extends Resource { @Inject public StudyResource( DatasetService datasetService, - UserService userService, DatasetRegistrationService datasetRegistrationService, ElasticSearchService elasticSearchService) { this.datasetService = datasetService; - this.userService = userService; this.datasetRegistrationService = datasetRegistrationService; this.elasticSearchService = elasticSearchService; this.studyUpdateRequestValidator = new StudyUpdateRequestValidator(datasetService); @@ -111,9 +106,9 @@ public Response convertToStudy( @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN}) public Response updateCustodians( - @Auth AuthUser authUser, @PathParam("studyId") Integer studyId, String json) { + @Auth DuosUser duosUser, @PathParam("studyId") Integer studyId, String json) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); // TODO: Replace new Gson() with GsonUtil.buildGson() — deferred pending Gson configuration // investigation Gson gson = new Gson(); @@ -175,9 +170,9 @@ public Response patchStudyById( @Path("/{studyId}") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, CHAIRPERSON, DATASUBMITTER}) - public Response deleteStudyById(@Auth AuthUser authUser, @PathParam("studyId") Integer studyId) { + public Response deleteStudyById(@Auth DuosUser duosUser, @PathParam("studyId") Integer studyId) { try { - final User user = userService.findUserByEmail(authUser.getEmail()); + final User user = duosUser.getUser(); Study study = datasetService.getStudyWithDatasetsById(user, studyId); if (Objects.isNull(study)) { @@ -235,12 +230,12 @@ public Response getRegistrationFromStudy( * With that object, we can fully update the study/datasets from the provided values. */ public Response updateStudyByRegistration( - @Auth AuthUser authUser, + @Auth DuosUser duosUser, FormDataMultiPart multipart, @PathParam("studyId") Integer studyId, @FormDataParam("dataset") String json) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); Study existingStudy = datasetRegistrationService.findStudyById(studyId); boolean canUpdateStudy = datasetService.isCreatorCustodianOrAdmin(user, existingStudy); if (!canUpdateStudy) { diff --git a/src/main/java/org/broadinstitute/consent/http/resources/UserResource.java b/src/main/java/org/broadinstitute/consent/http/resources/UserResource.java index da92a5da2e..bec002092a 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/UserResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/UserResource.java @@ -90,9 +90,9 @@ public UserResource( @Produces("application/json") @Path("/role/{roleName}") @RolesAllowed({ADMIN, SIGNINGOFFICIAL}) - public Response getUsers(@Auth AuthUser authUser, @PathParam("roleName") String roleName) { + public Response getUsers(@Auth DuosUser duosUser, @PathParam("roleName") String roleName) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); boolean valid = UserRoles.isValidRole(roleName); if (valid) { // if there is a valid roleName but it is not SO or Admin then throw an exception @@ -157,17 +157,17 @@ private UserStatusInfo getUserStatusInfo(DuosUser duosUser) throws SamAzureB2CEx @Path("/me/dac/datasets") @Produces("application/json") @RolesAllowed({CHAIRPERSON, MEMBER}) - public Response getDatasetsFromUserDacs(@Auth AuthUser authUser) { - return getDatasetsFromUserDacsV2(authUser); + public Response getDatasetsFromUserDacs(@Auth DuosUser duosUser) { + return getDatasetsFromUserDacsV2(duosUser); } @GET @Path("/me/dac/datasets/v2") @Produces("application/json") @RolesAllowed({CHAIRPERSON, MEMBER}) - public Response getDatasetsFromUserDacsV2(@Auth AuthUser authUser) { + public Response getDatasetsFromUserDacsV2(@Auth DuosUser duosUser) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); List dacIds = user.getRoles().stream().map(UserRole::getDacId).filter(Objects::nonNull).toList(); List datasets = @@ -199,7 +199,7 @@ public Response getUserById(@Auth DuosUser duosUser, @PathParam("userId") Intege @Produces("application/json") @RolesAllowed({ADMIN}) public Response getUsersByInstitution( - @Auth AuthUser user, @PathParam("institutionId") Integer institutionId) { + @Auth DuosUser duosUser, @PathParam("institutionId") Integer institutionId) { try { List users = userService.findUsersByInstitutionId(institutionId); return Response.ok().entity(users).build(); @@ -397,9 +397,9 @@ public Response createResearcher(@Context UriInfo info, @Auth AuthUser authUser) @Produces(MediaType.APPLICATION_JSON) @Path("/signing-officials") @RolesAllowed(RESEARCHER) - public Response getSOsForInstitution(@Auth AuthUser authUser) { + public Response getSOsForInstitution(@Auth DuosUser duosUser) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); if (Objects.nonNull(user.getInstitutionId())) { List signingOfficials = userService.findSOsByInstitutionId(user.getInstitutionId()); @@ -416,9 +416,9 @@ public Response getSOsForInstitution(@Auth AuthUser authUser) { @Path("/institution/{institutionId}/signing-officials") @RolesAllowed({ADMIN, CHAIRPERSON, MEMBER, RESEARCHER}) public Response getSigningOfficialsByInstitution( - @Auth AuthUser authUser, @PathParam("institutionId") Integer institutionId) { + @Auth DuosUser duosUser, @PathParam("institutionId") Integer institutionId) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); if (!user.hasUserRole(UserRoles.ADMIN) && !user.hasUserRole(UserRoles.CHAIRPERSON) && !user.hasUserRole(UserRoles.MEMBER) @@ -469,9 +469,9 @@ public Response getUserAcknowledgement(@Auth DuosUser duosUser, @PathParam("key" @Produces(MediaType.APPLICATION_JSON) @Path("/acknowledgements/{key}") @RolesAllowed(ADMIN) - public Response deleteUserAcknowledgement(@Auth AuthUser authUser, @PathParam("key") String key) { + public Response deleteUserAcknowledgement(@Auth DuosUser duosUser, @PathParam("key") String key) { try { - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); Acknowledgement ack = acknowledgementService.findAcknowledgementForUserByKey(user, key); if (Objects.isNull(ack)) { return Response.status(Response.Status.NOT_FOUND).build(); diff --git a/src/main/java/org/broadinstitute/consent/http/resources/VoteResource.java b/src/main/java/org/broadinstitute/consent/http/resources/VoteResource.java index 0d72365ccd..b7a2d4028f 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/VoteResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/VoteResource.java @@ -18,19 +18,17 @@ import java.util.stream.Collectors; import org.broadinstitute.consent.http.enumeration.ElectionType; import org.broadinstitute.consent.http.enumeration.VoteType; -import org.broadinstitute.consent.http.models.AuthUser; +import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.models.Election; import org.broadinstitute.consent.http.models.User; import org.broadinstitute.consent.http.models.Vote; import org.broadinstitute.consent.http.service.ElectionService; -import org.broadinstitute.consent.http.service.UserService; import org.broadinstitute.consent.http.service.VoteService; import org.glassfish.jersey.server.ContainerRequest; @Path("api/votes") public class VoteResource extends Resource { - private final UserService userService; private final VoteService voteService; private final ElectionService electionService; // TODO: Replace new Gson() with GsonUtil.buildGson() — deferred pending Gson configuration @@ -38,9 +36,7 @@ public class VoteResource extends Resource { private final Gson gson = new Gson(); @Inject - public VoteResource( - UserService userService, VoteService voteService, ElectionService electionService) { - this.userService = userService; + public VoteResource(VoteService voteService, ElectionService electionService) { this.voteService = voteService; this.electionService = electionService; } @@ -52,7 +48,7 @@ public VoteResource( *

Error cases are: 1. Vote is null 2. Auth user is not the owner of all votes being updated 3. * No votes match the list of ids provided * - * @param authUser The AuthUser + * @param duosUser The DuosUser * @param request The request * @param json The boolean value to update votes to, string value for all rationales, and list of * vote ids, in json format @@ -62,7 +58,7 @@ public VoteResource( @Consumes("application/json") @Produces("application/json") @RolesAllowed({CHAIRPERSON, MEMBER}) - public Response updateVotes(@Auth AuthUser authUser, @Context Request request, String json) { + public Response updateVotes(@Auth DuosUser duosUser, @Context Request request, String json) { Vote.VoteUpdate voteUpdate; try { voteUpdate = gson.fromJson(json, Vote.VoteUpdate.class); @@ -89,7 +85,7 @@ public Response updateVotes(@Auth AuthUser authUser, @Context Request request, S } // Validate that the user is only updating their own votes: - User user = userService.findUserByEmail(authUser.getEmail()); + User user = duosUser.getUser(); boolean authed = votes.stream().map(Vote::getUserId).allMatch(id -> id.equals(user.getUserId())); if (!authed) { @@ -124,7 +120,7 @@ public Response updateVotes(@Auth AuthUser authUser, @Context Request request, S * This API will update the rationale for a list of vote ids. The Rationale for DataAccess Votes * can only be updated for OPEN elections. In all cases, one can only update their own votes. * - * @param authUser The AuthUser + * @param duosUser The DuosUser * @param json The rationale and vote ids to update * @return Response with results of the update. */ @@ -133,8 +129,8 @@ public Response updateVotes(@Auth AuthUser authUser, @Context Request request, S @Consumes("application/json") @Produces("application/json") @RolesAllowed({CHAIRPERSON, MEMBER}) - public Response updateVoteRationale(@Auth AuthUser authUser, String json) { - User user = userService.findUserByEmail(authUser.getEmail()); + public Response updateVoteRationale(@Auth DuosUser duosUser, String json) { + User user = duosUser.getUser(); Vote.RationaleUpdate update; try { // TODO: Replace new Gson() with GsonUtil.buildGson() — deferred pending Gson configuration diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResourceTest.java index 6098f710d2..4041cd11d7 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResourceTest.java @@ -15,7 +15,6 @@ import org.broadinstitute.consent.http.models.UserRole; import org.broadinstitute.consent.http.service.DACAutomationRuleService; import org.broadinstitute.consent.http.service.DacService; -import org.broadinstitute.consent.http.service.UserService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -28,7 +27,6 @@ class DACAutomationRuleResourceTest extends AbstractTestHelper { @Mock private DACAutomationRuleService ruleService; @Mock private DacService dacService; - @Mock private UserService userService; @Mock private AuthUser authUser; @@ -36,7 +34,7 @@ class DACAutomationRuleResourceTest extends AbstractTestHelper { @BeforeEach void setUp() { - resource = new DACAutomationRuleResource(ruleService, dacService, userService); + resource = new DACAutomationRuleResource(ruleService, dacService); } @Test @@ -50,11 +48,10 @@ void testGetAllRules() { @Test void testGetAvailableRulesAsAdmin() { - when(userService.findUserByEmail(authUser.getEmail())) - .thenReturn(createUserWithRole(UserRoles.Admin())); + User admin = createUserWithRole(UserRoles.Admin()); when(dacService.findById(1)).thenReturn(new Dac()); - try (var response = resource.getAvailableRules(authUser, 1)) { + try (var response = resource.getAvailableRules(new DuosUser(authUser, admin), 1)) { Assertions.assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -63,10 +60,10 @@ void testGetAvailableRulesAsAdmin() { void testGetAvailableRulesAsChair() { UserRole role = UserRoles.Chairperson(); role.setDacId(1); - when(userService.findUserByEmail(authUser.getEmail())).thenReturn(createUserWithRole(role)); + User chairperson = createUserWithRole(role); when(dacService.findById(1)).thenReturn(new Dac()); - try (var response = resource.getAvailableRules(authUser, 1)) { + try (var response = resource.getAvailableRules(new DuosUser(authUser, chairperson), 1)) { Assertions.assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -75,19 +72,18 @@ void testGetAvailableRulesAsChair() { void testGetAvailableRulesAsChairForbidden() { UserRole role = UserRoles.Chairperson(); role.setDacId(2); - when(userService.findUserByEmail(authUser.getEmail())).thenReturn(createUserWithRole(role)); + User chairperson = createUserWithRole(role); - try (var response = resource.getAvailableRules(authUser, 1)) { + try (var response = resource.getAvailableRules(new DuosUser(authUser, chairperson), 1)) { Assertions.assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response.getStatus()); } } @Test void testToggleRuleAsAdmin() { - User chairperson = createUserWithRole(UserRoles.Admin()); - when(userService.findUserByEmail(authUser.getEmail())).thenReturn(chairperson); + User admin = createUserWithRole(UserRoles.Admin()); - try (var response = resource.toggleRule(authUser, 1, 1)) { + try (var response = resource.toggleRule(new DuosUser(authUser, admin), 1, 1)) { Assertions.assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response.getStatus()); } } @@ -97,7 +93,6 @@ void testToggleRuleAsChair() { UserRole role = UserRoles.Chairperson(); role.setDacId(1); User chairperson = createUserWithRole(role); - when(userService.findUserByEmail(authUser.getEmail())).thenReturn(chairperson); when(dacService.findById(1)).thenReturn(new Dac()); when(ruleService.toggleRule(1, 1, chairperson)) .thenReturn( @@ -108,7 +103,7 @@ void testToggleRuleAsChair() { chairperson.getDisplayName(), chairperson.getEmail())); - try (var response = resource.toggleRule(authUser, 1, 1)) { + try (var response = resource.toggleRule(new DuosUser(authUser, chairperson), 1, 1)) { Assertions.assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -118,9 +113,8 @@ void testToggleRuleAsChairForbidden() { UserRole role = UserRoles.Chairperson(); role.setDacId(2); User chairperson = createUserWithRole(role); - when(userService.findUserByEmail(authUser.getEmail())).thenReturn(chairperson); - try (var response = resource.toggleRule(authUser, 1, 1)) { + try (var response = resource.toggleRule(new DuosUser(authUser, chairperson), 1, 1)) { Assertions.assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response.getStatus()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DacResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DacResourceTest.java index 11f4c26aeb..491ae81d76 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DacResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DacResourceTest.java @@ -59,7 +59,8 @@ void setUp() { void testFindAll_success_1() { when(dacService.findDacsWithMembersOption(true)).thenReturn(Collections.emptyList()); - try (Response response = dacResource.findAll(authUser, Optional.of(true))) { + try (Response response = + dacResource.findAll(new DuosUser(authUser, new User()), Optional.of(true))) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); JsonArray dacs = getListFromEntityString(response.getEntity().toString()); assertEquals(0, dacs.size()); @@ -71,7 +72,8 @@ void testFindAll_success_2() { Dac dac = new DacBuilder().setName("name").setDescription("description").build(); when(dacService.findDacsWithMembersOption(true)).thenReturn(Collections.singletonList(dac)); - try (Response response = dacResource.findAll(authUser, Optional.of(true))) { + try (Response response = + dacResource.findAll(new DuosUser(authUser, new User()), Optional.of(true))) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); JsonArray dacs = getListFromEntityString(response.getEntity().toString()); assertEquals(1, dacs.size()); @@ -82,7 +84,8 @@ void testFindAll_success_2() { void testFindAllWithUsers() { when(dacService.findDacsWithMembersOption(false)).thenReturn(Collections.emptyList()); - try (Response response = dacResource.findAll(authUser, Optional.of(false))) { + try (Response response = + dacResource.findAll(new DuosUser(authUser, new User()), Optional.of(false))) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); JsonArray dacs = getListFromEntityString(response.getEntity().toString()); assertEquals(0, dacs.size()); @@ -327,7 +330,8 @@ void testFindById_success() { .build(); when(dacService.findById(1)).thenReturn(dac); - try (Response response = dacResource.findDacById(authUser, dac.getDacId())) { + try (Response response = + dacResource.findDacById(new DuosUser(authUser, new User()), dac.getDacId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -336,11 +340,22 @@ void testFindById_success() { void testFindById_failure() { when(dacService.findById(1)).thenReturn(null); - try (Response response = dacResource.findDacById(authUser, 1)) { + try (Response response = dacResource.findDacById(new DuosUser(authUser, new User()), 1)) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } + @Test + void testFilterUsers_success() { + User user = new User(); + user.setDisplayName("Jane Doe"); + when(dacService.findAllDACUsersBySearchString("Jane")).thenReturn(List.of(user)); + + try (Response response = dacResource.filterUsers(new DuosUser(authUser, new User()), "Jane")) { + assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); + } + } + @Test void testDeleteDac_success() { Dac dac = new DacBuilder().setDacId(1).setName("name").setDescription("description").build(); diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DataAccessRequestResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DataAccessRequestResourceTest.java index df6edeb4c7..5229b2c4bd 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DataAccessRequestResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DataAccessRequestResourceTest.java @@ -139,10 +139,10 @@ void initResource() { @Test void testCreateDataAccessRequest() { + User userWithCards = new User(1, authUser.getEmail(), "Display Name", new Date(), roles); + userWithCards.setLibraryCard(new LibraryCard()); + DuosUser duosUserWithCards = new DuosUser(authUser, userWithCards); try { - User userWithCards = new User(1, authUser.getEmail(), "Display Name", new Date(), roles); - userWithCards.setLibraryCard(new LibraryCard()); - when(userService.findUserByEmail(any())).thenReturn(userWithCards); DataAccessRequest dar = new DataAccessRequest(); dar.setReferenceId(UUID.randomUUID().toString()); dar.setCollectionId(1); @@ -159,7 +159,7 @@ void testCreateDataAccessRequest() { fail("Initialization Exception: " + e.getMessage()); } - try (var response = resource.createDataAccessRequest(authUser, request, info, "")) { + try (var response = resource.createDataAccessRequest(duosUserWithCards, request, info, "")) { assertEquals(Status.CREATED.getStatusCode(), response.getStatus()); } } @@ -168,7 +168,7 @@ void testCreateDataAccessRequest() { void testCreateDataAccessRequestWithSubmittedDAR() { User userWithCards = new User(1, authUser.getEmail(), "Display Name", new Date(), roles); userWithCards.setLibraryCard(new LibraryCard()); - when(userService.findUserByEmail(any())).thenReturn(userWithCards); + DuosUser duosUserWithCards = new DuosUser(authUser, userWithCards); DataAccessRequest dar = new DataAccessRequest(); dar.setReferenceId(UUID.randomUUID().toString()); dar.setCollectionId(1); @@ -180,7 +180,7 @@ void testCreateDataAccessRequestWithSubmittedDAR() { .when(dataAccessRequestService) .createDataAccessRequest(any(), any(), any()); - try (var response = resource.createDataAccessRequest(authUser, request, info, "")) { + try (var response = resource.createDataAccessRequest(duosUserWithCards, request, info, "")) { assertEquals(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY, response.getStatus()); org.broadinstitute.consent.http.models.Error error = (org.broadinstitute.consent.http.models.Error) response.getEntity(); @@ -192,12 +192,12 @@ void testCreateDataAccessRequestWithSubmittedDAR() { void testCreateDataAccessRequestWithoutValidERACommons() { User userWithCards = new User(1, authUser.getEmail(), "Display Name", new Date(), roles); userWithCards.setLibraryCard(new LibraryCard()); - when(userService.findUserByEmail(any())).thenReturn(userWithCards); + DuosUser duosUserWithCards = new DuosUser(authUser, userWithCards); doThrow(new BadRequestException()) .when(dataAccessRequestService) .createDataAccessRequest(eq(user), any(), any()); - try (var response = resource.createDataAccessRequest(authUser, request, info, "")) { + try (var response = resource.createDataAccessRequest(duosUserWithCards, request, info, "")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -274,7 +274,6 @@ void testUpdateByReferenceId() { DataAccessRequest dar = generateDataAccessRequest(); user.setLibraryCard(new LibraryCard()); try { - when(userService.findUserByEmail(any())).thenReturn(user); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); when(dataAccessRequestService.updateByReferenceId(any(), any())).thenReturn(dar); doNothing().when(matchService).reprocessMatchesForPurpose(any()); @@ -282,7 +281,7 @@ void testUpdateByReferenceId() { fail("Initialization Exception: " + e.getMessage()); } - try (var response = resource.updateByReferenceId(authUser, "", "{}")) { + try (var response = resource.updateByReferenceId(duosUser, "", "{}")) { assertEquals(200, response.getStatus()); } } @@ -290,15 +289,15 @@ void testUpdateByReferenceId() { @Test void testUpdateByReferenceIdForbidden() { User invalidUser = new User(1000, authUser.getEmail(), "Display Name", new Date()); + DuosUser invalidDuosUser = new DuosUser(authUser, invalidUser); DataAccessRequest dar = generateDataAccessRequest(); try { - when(userService.findUserByEmail(any())).thenReturn(invalidUser); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); } catch (Exception e) { fail("Initialization Exception: " + e.getMessage()); } - try (var response = resource.updateByReferenceId(authUser, "", "{}")) { + try (var response = resource.updateByReferenceId(invalidDuosUser, "", "{}")) { assertEquals(403, response.getStatus()); } } @@ -307,7 +306,6 @@ void testUpdateByReferenceIdForbidden() { void testCreateDraftDataAccessRequest() { DataAccessRequest dar = generateDataAccessRequest(); try { - when(userService.findUserByEmail(any())).thenReturn(user); when(dataAccessRequestService.insertDraftDataAccessRequest(any(), any())).thenReturn(dar); when(builder.path(anyString())).thenReturn(builder); when(builder.build()).thenReturn(URI.create("https://test.domain.org/some/path")); @@ -316,7 +314,7 @@ void testCreateDraftDataAccessRequest() { fail("Initialization Exception: " + e.getMessage()); } - try (var response = resource.createDraftDataAccessRequest(authUser, info, "")) { + try (var response = resource.createDraftDataAccessRequest(duosUser, info, "")) { assertEquals(201, response.getStatus()); } } @@ -324,11 +322,10 @@ void testCreateDraftDataAccessRequest() { @Test void testUpdatePartialDataAccessRequest() { DataAccessRequest dar = generateDataAccessRequest(); - when(userService.findUserByEmail(any())).thenReturn(user); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); when(dataAccessRequestService.updateByReferenceId(any(), any())).thenReturn(dar); - try (var response = resource.updatePartialDataAccessRequest(authUser, "", "{}")) { + try (var response = resource.updatePartialDataAccessRequest(duosUser, "", "{}")) { assertEquals(200, response.getStatus()); } } @@ -336,11 +333,11 @@ void testUpdatePartialDataAccessRequest() { @Test void testUpdatePartialDataAccessRequestForbidden() { User invalidUser = new User(1000, authUser.getEmail(), "Display Name", new Date()); + DuosUser invalidDuosUser = new DuosUser(authUser, invalidUser); DataAccessRequest dar = generateDataAccessRequest(); - when(userService.findUserByEmail(any())).thenReturn(invalidUser); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); - try (var response = resource.updatePartialDataAccessRequest(authUser, "", "{}")) { + try (var response = resource.updatePartialDataAccessRequest(invalidDuosUser, "", "{}")) { assertEquals(403, response.getStatus()); } } @@ -390,7 +387,6 @@ void testGetIrbDocumentNullOrEmptyValues() { @Test void testUploadIrbDocument() throws Exception { - when(userService.findUserByEmail(any())).thenReturn(user); DataAccessRequest dar = generateDataAccessRequest(); when(dataAccessRequestService.updateByReferenceId(any(), any())).thenReturn(dar); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); @@ -401,24 +397,22 @@ void testUploadIrbDocument() throws Exception { when(formData.getSize()).thenReturn(1L); when(gcsService.storeDocument(any(), any(), any())).thenReturn(BlobId.of("bucket", "name")); - Response response = resource.uploadIrbDocument(authUser, "", uploadInputStream, formData); + Response response = resource.uploadIrbDocument(duosUser, "", uploadInputStream, formData); assertEquals(200, response.getStatus()); } @Test void testUploadIrbDocumentDARNotFound() { - when(userService.findUserByEmail(any())).thenReturn(user); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(null); InputStream uploadInputStream = IOUtils.toInputStream("test", Charset.defaultCharset()); FormDataContentDisposition formData = mock(FormDataContentDisposition.class); - Response response = resource.uploadIrbDocument(authUser, "", uploadInputStream, formData); + Response response = resource.uploadIrbDocument(duosUser, "", uploadInputStream, formData); assertEquals(404, response.getStatus()); } @Test void testUploadIrbDocumentWithPreviousIrbDocument() throws Exception { - when(userService.findUserByEmail(any())).thenReturn(user); DataAccessRequest dar = generateDataAccessRequest(); dar.getData().setIrbDocumentLocation(randomAlphabetic(10)); dar.getData().setIrbDocumentName(randomAlphabetic(10) + ".txt"); @@ -432,7 +426,7 @@ void testUploadIrbDocumentWithPreviousIrbDocument() throws Exception { when(gcsService.storeDocument(any(), any(), any())).thenReturn(BlobId.of("bucket", "name")); when(gcsService.deleteDocument(any())).thenReturn(true); - Response response = resource.uploadIrbDocument(authUser, "", uploadInputStream, formData); + Response response = resource.uploadIrbDocument(duosUser, "", uploadInputStream, formData); assertEquals(200, response.getStatus()); } @@ -444,7 +438,6 @@ private Pair mockFormDataMultiPart(Stri } private void mockProgressReportUserAndParentDar(DataAccessRequest parentDar) { - when(userService.findUserByEmail(any())).thenReturn(user); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(parentDar); } @@ -503,7 +496,6 @@ void testPostProgressReportDifferentUser() { @Test void testPostProgressReportMissingParentDar() { - when(userService.findUserByEmail(any())).thenReturn(user); when(dataAccessRequestService.findByReferenceId(any())).thenThrow(NotFoundException.class); Pair collabFile = mockFormDataMultiPart("collab.txt"); Pair ethicsFile = mockFormDataMultiPart("ethics.txt"); @@ -548,7 +540,6 @@ void testPostProgressReportInvalidJson() { @Test void testPostProgressReportThrowsWhenNoERACommonsID() { - when(userService.findUserByEmail(any())).thenReturn(user); doThrow(BadRequestException.class).when(userService).validateActiveERACredentials(user); try (var response = @@ -933,7 +924,6 @@ void testGetCollaborationDocumentNullOrEmptyValues() { @Test void testUploadCollaborationDocument() throws Exception { - when(userService.findUserByEmail(any())).thenReturn(user); DataAccessRequest dar = generateDataAccessRequest(); when(dataAccessRequestService.updateByReferenceId(any(), any())).thenReturn(dar); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); @@ -945,25 +935,23 @@ void testUploadCollaborationDocument() throws Exception { when(gcsService.storeDocument(any(), any(), any())).thenReturn(BlobId.of("buket", "name")); Response response = - resource.uploadCollaborationDocument(authUser, "", uploadInputStream, formData); + resource.uploadCollaborationDocument(duosUser, "", uploadInputStream, formData); assertEquals(200, response.getStatus()); } @Test void testUploadCollaborationDocumentDARNotFound() { - when(userService.findUserByEmail(any())).thenReturn(user); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(null); InputStream uploadInputStream = IOUtils.toInputStream("test", Charset.defaultCharset()); FormDataContentDisposition formData = mock(FormDataContentDisposition.class); Response response = - resource.uploadCollaborationDocument(authUser, "", uploadInputStream, formData); + resource.uploadCollaborationDocument(duosUser, "", uploadInputStream, formData); assertEquals(404, response.getStatus()); } @Test void testUploadCollaborationDocumentWithPreviousDocument() throws Exception { - when(userService.findUserByEmail(any())).thenReturn(user); DataAccessRequest dar = generateDataAccessRequest(); dar.getData().setCollaborationLetterLocation(randomAlphabetic(10)); dar.getData().setCollaborationLetterName(randomAlphabetic(10) + ".txt"); @@ -978,7 +966,7 @@ void testUploadCollaborationDocumentWithPreviousDocument() throws Exception { when(gcsService.deleteDocument(any())).thenReturn(true); Response response = - resource.uploadCollaborationDocument(authUser, "", uploadInputStream, formData); + resource.uploadCollaborationDocument(duosUser, "", uploadInputStream, formData); assertEquals(200, response.getStatus()); } @@ -1012,48 +1000,33 @@ void getDraftDataAccessRequests() { List list = Collections.emptyList(); User localUser = new User(); localUser.setUserId(1); - when(userService.findUserByEmail(any())).thenReturn(localUser); + DuosUser localDuosUser = new DuosUser(authUser, localUser); when(dataAccessRequestService.findAllDraftDataAccessRequestsByUser(any())).thenReturn(list); - Response res = resource.getDraftDataAccessRequests(authUser); + Response res = resource.getDraftDataAccessRequests(localDuosUser); assertEquals(HttpStatusCodes.STATUS_CODE_OK, res.getStatus()); assertTrue(res.hasEntity()); } - @Test - void getDraftDataAccessRequests_UserNotFound() { - when(userService.findUserByEmail(any())).thenThrow(new NotFoundException()); - resource.getDraftDataAccessRequests(authUser); - Response res = resource.getDraftDataAccessRequests(authUser); - assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, res.getStatus()); - } - @Test void getDraftDar() { User localUser = new User(); localUser.setUserId(10); + DuosUser localDuosUser = new DuosUser(authUser, localUser); DataAccessRequest dar = new DataAccessRequest(); dar.setUserId(10); - when(userService.findUserByEmail(any())).thenReturn(localUser); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); - Response res = resource.getDraftDar(authUser, "id"); + Response res = resource.getDraftDar(localDuosUser, "id"); assertEquals(HttpStatusCodes.STATUS_CODE_OK, res.getStatus()); assertTrue(res.hasEntity()); } - @Test - void getDraftDar_UserNotFound() { - when(userService.findUserByEmail(any())).thenThrow(new NotFoundException()); - Response res = resource.getDraftDar(authUser, "id"); - assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, res.getStatus()); - } - @Test void getDraftDar_DarNotFound() { User localUser = new User(); localUser.setUserId(10); - when(userService.findUserByEmail(any())).thenReturn(localUser); + DuosUser localDuosUser = new DuosUser(authUser, localUser); when(dataAccessRequestService.findByReferenceId(any())).thenThrow(new NotFoundException()); - Response res = resource.getDraftDar(authUser, "id"); + Response res = resource.getDraftDar(localDuosUser, "id"); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, res.getStatus()); } @@ -1061,20 +1034,20 @@ void getDraftDar_DarNotFound() { void getDraftDar_UserNotAllowed() { User localUser = new User(); localUser.setUserId(10); + DuosUser localDuosUser = new DuosUser(authUser, localUser); DataAccessRequest dar = new DataAccessRequest(); dar.setUserId(11); - when(userService.findUserByEmail(any())).thenReturn(localUser); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); - Response res = resource.getDraftDar(authUser, "id"); + Response res = resource.getDraftDar(localDuosUser, "id"); assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, res.getStatus()); } @Test void testCreateDataAccessRequestWithDAARestrictions() { + User userWithCards = new User(1, authUser.getEmail(), "Display Name", new Date(), roles); + userWithCards.setLibraryCard(new LibraryCard()); + DuosUser duosUserWithCards = new DuosUser(authUser, userWithCards); try { - User userWithCards = new User(1, authUser.getEmail(), "Display Name", new Date(), roles); - userWithCards.setLibraryCard(new LibraryCard()); - when(userService.findUserByEmail(any())).thenReturn(userWithCards); DataAccessRequest dar = new DataAccessRequest(); dar.setReferenceId(UUID.randomUUID().toString()); dar.setCollectionId(1); @@ -1089,17 +1062,17 @@ void testCreateDataAccessRequestWithDAARestrictions() { fail("Initialization Exception: " + e.getMessage()); } - try (Response response = resource.createDraftDataAccessRequest(authUser, info, "")) { + try (Response response = resource.createDraftDataAccessRequest(duosUserWithCards, info, "")) { assertEquals(HttpStatusCodes.STATUS_CODE_CREATED, response.getStatus()); } } @Test void testCreateDataAccessRequestWithDAARestrictionsFailure() { + User userWithCards = new User(1, authUser.getEmail(), "Display Name", new Date(), roles); + userWithCards.setLibraryCard(new LibraryCard()); + DuosUser duosUserWithCards = new DuosUser(authUser, userWithCards); try { - User userWithCards = new User(1, authUser.getEmail(), "Display Name", new Date(), roles); - userWithCards.setLibraryCard(new LibraryCard()); - when(userService.findUserByEmail(any())).thenReturn(userWithCards); DataAccessRequest dar = new DataAccessRequest(); dar.setReferenceId(UUID.randomUUID().toString()); dar.setCollectionId(1); @@ -1113,7 +1086,7 @@ void testCreateDataAccessRequestWithDAARestrictionsFailure() { fail("Initialization Exception: " + e.getMessage()); } - try (Response response = resource.createDraftDataAccessRequest(authUser, info, "")) { + try (Response response = resource.createDraftDataAccessRequest(duosUserWithCards, info, "")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DatasetResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DatasetResourceTest.java index 77b686fb77..8c4e04e0b6 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DatasetResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DatasetResourceTest.java @@ -543,7 +543,7 @@ void testIndexDataset() throws IOException { when(mockResponse.getStatus()).thenReturn(HttpStatusCodes.STATUS_CODE_OK); when(elasticSearchService.indexDataset(dataset.getDatasetId())).thenReturn(mockResponse); - try (var response = resource.indexDataset(authUser, dataset.getDatasetId())) { + try (var response = resource.indexDataset(duosUser, dataset.getDatasetId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -552,9 +552,8 @@ void testIndexDataset() throws IOException { void testIndexDelete() throws IOException { when(mockResponse.getStatus()).thenReturn(HttpStatusCodes.STATUS_CODE_OK); when(elasticSearchService.deleteIndex(any(), any())).thenReturn(mockResponse); - when(userService.findUserByEmail(any())).thenReturn(user); - try (var response = resource.deleteDatasetIndex(authUser, 0)) { + try (var response = resource.deleteDatasetIndex(duosUser, 0)) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -701,14 +700,14 @@ void testUpdateDatasetDataUse_OK() { when(datasetService.updateDatasetDataUse(any(), any(), any())).thenReturn(d); String duString = new DataUseBuilder().setGeneralUse(true).build().toString(); - try (var response = resource.updateDatasetDataUse(new AuthUser(), 1, duString)) { + try (var response = resource.updateDatasetDataUse(duosUser, 1, duString)) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @Test void testUpdateDatasetDataUse_BadRequestJson() { - try (var response = resource.updateDatasetDataUse(new AuthUser(), 1, "invalid json")) { + try (var response = resource.updateDatasetDataUse(duosUser, 1, "invalid json")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -721,7 +720,7 @@ void testUpdateDatasetDataUse_BadRequestService() { .thenThrow(new IllegalArgumentException()); String duString = new DataUseBuilder().setGeneralUse(true).build().toString(); - try (var response = resource.updateDatasetDataUse(new AuthUser(), 1, duString)) { + try (var response = resource.updateDatasetDataUse(duosUser, 1, duString)) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -731,7 +730,7 @@ void testUpdateDatasetDataUse_NotFound() { when(datasetService.findDatasetById(any(), any())).thenThrow(new NotFoundException()); String duString = new DataUseBuilder().setGeneralUse(true).build().toString(); - try (var response = resource.updateDatasetDataUse(new AuthUser(), 1, duString)) { + try (var response = resource.updateDatasetDataUse(duosUser, 1, duString)) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } @@ -743,7 +742,7 @@ void testUpdateDatasetDataUse_NotModified() { d.setDataUse(du); when(datasetService.findDatasetById(any(), any())).thenReturn(d); - try (var response = resource.updateDatasetDataUse(new AuthUser(), 1, du.toString())) { + try (var response = resource.updateDatasetDataUse(duosUser, 1, du.toString())) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_MODIFIED, response.getStatus()); } } @@ -759,14 +758,14 @@ void testFindAllDatasetStudySummaries() { @Test void testCreateDatasetRegistration_invalidSchema_case1() { - try (var response = resource.createDatasetRegistration(authUser, null, "")) { + try (var response = resource.createDatasetRegistration(duosUser, null, "")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @Test void testCreateDatasetRegistration_invalidSchema_case2() { - try (var response = resource.createDatasetRegistration(authUser, null, "{}")) { + try (var response = resource.createDatasetRegistration(duosUser, null, "{}")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -776,7 +775,7 @@ void testCreateDatasetRegistration_invalidSchema_case3() { DatasetRegistrationSchemaV1 schemaV1 = new DatasetRegistrationSchemaV1(); String schemaString = new Gson().toJson(schemaV1); - try (var response = resource.createDatasetRegistration(authUser, null, schemaString)) { + try (var response = resource.createDatasetRegistration(duosUser, null, schemaString)) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -791,7 +790,7 @@ void testCreateDatasetRegistration_invalidSchema_errorMessages() { "consentGroups": [] } """; - try (var response = resource.createDatasetRegistration(authUser, null, invalidJson)) { + try (var response = resource.createDatasetRegistration(duosUser, null, invalidJson)) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); String entity = response.getEntity().toString(); @@ -809,7 +808,6 @@ void testCreateDatasetRegistration_invalidSchema_errorMessages() { @Test void testCreateDatasetRegistration_validSchema() throws SQLException, IOException { - when(userService.findUserByEmail(any())).thenReturn(user); user.setUserId(1); Dataset dataset = new Dataset(); Study study = new Study(); @@ -821,14 +819,13 @@ void testCreateDatasetRegistration_validSchema() throws SQLException, IOExceptio when(datasetService.findStudy(anyInt())).thenReturn(study); String schemaV1 = createDatasetRegistrationMock(user); - try (var response = resource.createDatasetRegistration(authUser, null, schemaV1)) { + try (var response = resource.createDatasetRegistration(duosUser, null, schemaV1)) { assertEquals(HttpStatusCodes.STATUS_CODE_CREATED, response.getStatus()); } } @Test void testCreateDatasetRegistration_NoStudyFound() throws SQLException, IOException { - when(userService.findUserByEmail(any())).thenReturn(user); user.setUserId(1); Dataset dataset = new Dataset(); Study study = new Study(); @@ -839,7 +836,7 @@ void testCreateDatasetRegistration_NoStudyFound() throws SQLException, IOExcepti .thenReturn(List.of(dataset)); when(datasetService.findStudy(anyInt())).thenReturn(null); String schemaV1 = createDatasetRegistrationMock(user); - Response response = resource.createDatasetRegistration(authUser, null, schemaV1); + Response response = resource.createDatasetRegistration(duosUser, null, schemaV1); assertEquals(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY, response.getStatus()); } @@ -853,7 +850,6 @@ void testCreateDatasetRegistration_withFile() throws SQLException, IOException { FormDataMultiPart formDataMultiPart = mock(FormDataMultiPart.class); when(formDataMultiPart.getFields()).thenReturn(Map.of("file", List.of(formDataBodyPart))); - when(userService.findUserByEmail(any())).thenReturn(user); user.setUserId(1); Dataset dataset = new Dataset(); Study study = new Study(); @@ -864,7 +860,7 @@ void testCreateDatasetRegistration_withFile() throws SQLException, IOException { .thenReturn(List.of(dataset)); String schemaV1 = createDatasetRegistrationMock(user); when(datasetService.findStudy(anyInt())).thenReturn(study); - Response response = resource.createDatasetRegistration(authUser, formDataMultiPart, schemaV1); + Response response = resource.createDatasetRegistration(duosUser, formDataMultiPart, schemaV1); assertEquals(HttpStatusCodes.STATUS_CODE_CREATED, response.getStatus()); } @@ -894,7 +890,6 @@ void testCreateDatasetRegistration_multipleFiles() throws SQLException, IOExcept "other", List.of(formDataBodyPartOther), "notFile", List.of(formDataBodyPartNotFile))); - when(userService.findUserByEmail(any())).thenReturn(user); user.setUserId(1); Dataset dataset = new Dataset(); Study study = new Study(); @@ -906,7 +901,7 @@ void testCreateDatasetRegistration_multipleFiles() throws SQLException, IOExcept when(datasetService.findStudy(anyInt())).thenReturn(study); String schemaV1 = createDatasetRegistrationMock(user); - Response response = resource.createDatasetRegistration(authUser, formDataMultiPart, schemaV1); + Response response = resource.createDatasetRegistration(duosUser, formDataMultiPart, schemaV1); assertEquals(HttpStatusCodes.STATUS_CODE_CREATED, response.getStatus()); verify(datasetRegistrationService, times(1)) @@ -928,10 +923,9 @@ void testCreateDatasetRegistration_invalidFileName() { FormDataMultiPart formDataMultiPart = mock(FormDataMultiPart.class); when(formDataMultiPart.getFields()).thenReturn(Map.of("file", List.of(formDataBodyPart))); - when(userService.findUserByEmail(any())).thenReturn(user); String schemaV1 = createDatasetRegistrationMock(user); - Response response = resource.createDatasetRegistration(authUser, formDataMultiPart, schemaV1); + Response response = resource.createDatasetRegistration(duosUser, formDataMultiPart, schemaV1); assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java index 6f15d7423f..f788b55588 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java @@ -25,14 +25,13 @@ import java.util.Set; import java.util.UUID; import org.broadinstitute.consent.http.enumeration.DraftType; -import org.broadinstitute.consent.http.models.AuthUser; import org.broadinstitute.consent.http.models.DraftInterface; import org.broadinstitute.consent.http.models.DraftStudyDataset; import org.broadinstitute.consent.http.models.DraftSummary; +import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.models.FileStorageObject; import org.broadinstitute.consent.http.models.User; import org.broadinstitute.consent.http.service.DraftService; -import org.broadinstitute.consent.http.service.UserService; import org.glassfish.jersey.media.multipart.FormDataMultiPart; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -44,26 +43,24 @@ class DraftResourceTest { @Mock private DraftService draftService; - @Mock private AuthUser authUser; + @Mock private DuosUser duosUser; @Mock private User user; @Mock private User user2; - @Mock private UserService userService; - private DraftResource resource; private void initResource() { - resource = new DraftResource(userService, draftService); + resource = new DraftResource(draftService); } @Test void testGetDraftWhenNoneExistForUser() { - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(draftService.findDraftSummariesForUser(any())).thenReturn(Collections.emptySet()); initResource(); - Response response = resource.getDrafts(authUser); + Response response = resource.getDrafts(duosUser); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); assertEquals("[]", response.getEntity().toString()); } @@ -78,10 +75,10 @@ void testGetDraftsWhenOneExistForUser() { new Date(), new Date(), DraftType.STUDY_DATASET_SUBMISSION_V1)); - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(draftService.findDraftSummariesForUser(any())).thenReturn(draftSummaries); initResource(); - Response response = resource.getDrafts(authUser); + Response response = resource.getDrafts(duosUser); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); assertEquals(draftSummaries, response.getEntity()); } @@ -90,7 +87,7 @@ void testGetDraftsWhenOneExistForUser() { void tesCreateDraftRegistration() { String draft = "{}"; initResource(); - Response response = resource.createDraftRegistration(authUser, draft); + Response response = resource.createDraftRegistration(duosUser, draft); assertEquals(HttpStatusCodes.STATUS_CODE_CREATED, response.getStatus()); assertEquals(draft, response.getEntity().toString()); } @@ -102,7 +99,7 @@ void tesCreateDraftRegistrationWithoutJSON() throws SQLException { .insertDraft(any()); String draft = ""; initResource(); - Response response = resource.createDraftRegistration(authUser, draft); + Response response = resource.createDraftRegistration(duosUser, draft); assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } @@ -111,7 +108,7 @@ void testGetDraftDocumentNotFound() { when(draftService.getAuthorizedDraft(any(), any())) .thenThrow(new NotFoundException("Not found exception.")); initResource(); - Response response = resource.getDraftDocument(authUser, UUID.randomUUID().toString()); + Response response = resource.getDraftDocument(duosUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -122,7 +119,7 @@ void testGetDraftDocumentSuccess() throws IOException { StreamingOutput stream = out -> out.write("{}".getBytes()); when(draftService.draftAsJson(any())).thenReturn(stream); initResource(); - Response response = resource.getDraftDocument(authUser, UUID.randomUUID().toString()); + Response response = resource.getDraftDocument(duosUser, UUID.randomUUID().toString()); StreamingOutput entity = (StreamingOutput) response.getEntity(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); entity.write(baos); @@ -135,7 +132,7 @@ void testGetDraftDocumentNotAuthorized() { when(draftService.getAuthorizedDraft(any(), any())) .thenThrow(new NotAuthorizedException("Not authorized.")); initResource(); - Response response = resource.getDraftDocument(authUser, UUID.randomUUID().toString()); + Response response = resource.getDraftDocument(duosUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); } @@ -144,7 +141,7 @@ void testPutDraftDocumentUnauthorized() { when(draftService.getAuthorizedDraft(any(), any())) .thenThrow(new NotAuthorizedException("Not authorized.")); initResource(); - Response response = resource.updateDraft(authUser, UUID.randomUUID().toString(), "{}"); + Response response = resource.updateDraft(duosUser, UUID.randomUUID().toString(), "{}"); assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); } @@ -153,7 +150,7 @@ void testPutDraftDocumentNotFound() { when(draftService.getAuthorizedDraft(any(), any())) .thenThrow(new NotFoundException("Not found exception.")); initResource(); - Response response = resource.updateDraft(authUser, UUID.randomUUID().toString(), "{}"); + Response response = resource.updateDraft(duosUser, UUID.randomUUID().toString(), "{}"); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -165,7 +162,7 @@ void testPutDraftDocumentSuccess() throws IOException { StreamingOutput stream = out -> out.write(updatedJson.getBytes()); when(draftService.draftAsJson(any())).thenReturn(stream); initResource(); - Response response = resource.updateDraft(authUser, UUID.randomUUID().toString(), updatedJson); + Response response = resource.updateDraft(duosUser, UUID.randomUUID().toString(), updatedJson); StreamingOutput entity = (StreamingOutput) response.getEntity(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); entity.write(baos); @@ -177,7 +174,7 @@ void testPutDraftDocumentSuccess() throws IOException { void testDeleteDraftDocumentNotFound() { when(draftService.getAuthorizedDraft(any(), any())).thenThrow(NotFoundException.class); initResource(); - Response response = resource.deleteDraft(authUser, UUID.randomUUID().toString()); + Response response = resource.deleteDraft(duosUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -185,7 +182,7 @@ void testDeleteDraftDocumentNotFound() { void testDeleteDraftDocumentNotAuthorized() { when(draftService.getAuthorizedDraft(any(), any())).thenThrow(NotAuthorizedException.class); initResource(); - Response response = resource.deleteDraft(authUser, UUID.randomUUID().toString()); + Response response = resource.deleteDraft(duosUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); } @@ -194,7 +191,7 @@ void testDeleteDraftDocumentSuccess() { when(draftService.getAuthorizedDraft(any(), any())) .thenReturn(new DraftStudyDataset("{}", user)); initResource(); - Response response = resource.deleteDraft(authUser, UUID.randomUUID().toString()); + Response response = resource.deleteDraft(duosUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -202,7 +199,7 @@ void testDeleteDraftDocumentSuccess() { void testGetDraftAttachmentsNotFound() { when(draftService.getAuthorizedDraft(any(), any())).thenThrow(NotFoundException.class); initResource(); - Response response = resource.getAttachments(authUser, UUID.randomUUID().toString()); + Response response = resource.getAttachments(duosUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -210,7 +207,7 @@ void testGetDraftAttachmentsNotFound() { void testGetDraftAttachmentsNotAuthorized() { when(draftService.getAuthorizedDraft(any(), any())).thenThrow(NotAuthorizedException.class); initResource(); - Response response = resource.getAttachments(authUser, UUID.randomUUID().toString()); + Response response = resource.getAttachments(duosUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); } @@ -220,7 +217,7 @@ void testGetDraftAttachmentsSuccessNoAttachments() { when(draftService.getAuthorizedDraft(any(), any())).thenReturn(draft); when(draft.getStoredFiles()).thenReturn(new HashSet<>()); initResource(); - Response response = resource.getAttachments(authUser, UUID.randomUUID().toString()); + Response response = resource.getAttachments(duosUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); assertEquals("[]", response.getEntity().toString()); } @@ -233,7 +230,7 @@ void testGetDraftAttachmentsSuccessWithAttachments() { FileStorageObject fileStorageObject2 = mock(FileStorageObject.class); when(draft.getStoredFiles()).thenReturn(Set.of(fileStorageObject1, fileStorageObject2)); initResource(); - Response response = resource.getAttachments(authUser, UUID.randomUUID().toString()); + Response response = resource.getAttachments(duosUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); assertTrue(response.getEntity().toString().contains("Mock for FileStorageObject")); } @@ -244,7 +241,7 @@ void testUploadAttachmentNotFound() { initResource(); Response response = resource.addAttachments( - authUser, UUID.randomUUID().toString(), mock(FormDataMultiPart.class)); + duosUser, UUID.randomUUID().toString(), mock(FormDataMultiPart.class)); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -254,7 +251,7 @@ void testUploadAttachmentNotAuthorized() { initResource(); Response response = resource.addAttachments( - authUser, UUID.randomUUID().toString(), mock(FormDataMultiPart.class)); + duosUser, UUID.randomUUID().toString(), mock(FormDataMultiPart.class)); assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); } @@ -269,7 +266,7 @@ void testUploadAttachmentSuccess() throws SQLException { initResource(); Response response = resource.addAttachments( - authUser, UUID.randomUUID().toString(), mock(FormDataMultiPart.class)); + duosUser, UUID.randomUUID().toString(), mock(FormDataMultiPart.class)); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); assertEquals(List.copyOf(draftWithAttachment.getStoredFiles()), response.getEntity()); } @@ -278,7 +275,7 @@ void testUploadAttachmentSuccess() throws SQLException { void testGetAttachmentNotFound() { when(draftService.getAuthorizedDraft(any(), any())).thenThrow(NotFoundException.class); initResource(); - Response response = resource.getAttachment(authUser, UUID.randomUUID().toString(), 1); + Response response = resource.getAttachment(duosUser, UUID.randomUUID().toString(), 1); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -286,7 +283,7 @@ void testGetAttachmentNotFound() { void testGetAttachmentNotAuthorized() { when(draftService.getAuthorizedDraft(any(), any())).thenThrow(NotAuthorizedException.class); initResource(); - Response response = resource.getAttachment(authUser, UUID.randomUUID().toString(), 1); + Response response = resource.getAttachment(duosUser, UUID.randomUUID().toString(), 1); assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); } @@ -301,7 +298,7 @@ void testGetAttachmentSuccess() throws SQLException { when(draftService.getDraftAttachmentStream(fileStorageObject1)) .thenReturn(mock(InputStream.class)); initResource(); - Response response = resource.getAttachment(authUser, UUID.randomUUID().toString(), 1); + Response response = resource.getAttachment(duosUser, UUID.randomUUID().toString(), 1); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); assertTrue( response @@ -320,7 +317,7 @@ void testGetAttachmentMissingFile() throws SQLException { draftWithAttachment.addStoredFile(fileStorageObject3); when(draftService.getAuthorizedDraft(any(), any())).thenReturn(draftWithAttachment); initResource(); - Response response = resource.getAttachment(authUser, UUID.randomUUID().toString(), 2); + Response response = resource.getAttachment(duosUser, UUID.randomUUID().toString(), 2); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -328,7 +325,7 @@ void testGetAttachmentMissingFile() throws SQLException { void testDeleteFileAttachmentNotFound() { when(draftService.getAuthorizedDraft(any(), any())).thenThrow(NotFoundException.class); initResource(); - Response response = resource.deleteDraftAttachment(authUser, UUID.randomUUID().toString(), 1); + Response response = resource.deleteDraftAttachment(duosUser, UUID.randomUUID().toString(), 1); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -336,7 +333,7 @@ void testDeleteFileAttachmentNotFound() { void testDeleteFileAttachmentNotAuthorized() { when(draftService.getAuthorizedDraft(any(), any())).thenThrow(NotAuthorizedException.class); initResource(); - Response response = resource.deleteDraftAttachment(authUser, UUID.randomUUID().toString(), 1); + Response response = resource.deleteDraftAttachment(duosUser, UUID.randomUUID().toString(), 1); assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); } @@ -346,7 +343,7 @@ void testDeleteFileAttachmentSuccess() throws SQLException { .thenReturn(new DraftStudyDataset("{}", user)); doNothing().when(draftService).deleteDraftAttachment(any(), any(), any()); initResource(); - Response response = resource.deleteDraftAttachment(authUser, UUID.randomUUID().toString(), 1); + Response response = resource.deleteDraftAttachment(duosUser, UUID.randomUUID().toString(), 1); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/EmailNotifierResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/EmailNotifierResourceTest.java index 493ce92e8d..953b89efa7 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/EmailNotifierResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/EmailNotifierResourceTest.java @@ -11,7 +11,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.broadinstitute.consent.http.AbstractTestHelper; -import org.broadinstitute.consent.http.models.AuthUser; +import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.service.DataAccessRequestService; import org.broadinstitute.consent.http.service.EmailService; import org.junit.jupiter.api.AfterEach; @@ -26,7 +26,7 @@ class EmailNotifierResourceTest extends AbstractTestHelper { @Mock private DataAccessRequestService dataAccessRequestService; @Mock private EmailService emailService; - @Mock private AuthUser authUser; + @Mock private DuosUser duosUser; private EmailNotifierResource resource; private ExecutorService executorService; @@ -46,21 +46,21 @@ void tearDown() { void testResourceSuccess() throws Exception { doNothing().when(dataAccessRequestService).sendReminderMessage(any()); try (Response response = - resource.sendReminderMessage(authUser, String.valueOf(randomInt(100, 1000)))) { + resource.sendReminderMessage(duosUser, String.valueOf(randomInt(100, 1000)))) { assertEquals(200, response.getStatus()); } } @Test void testResourceFailure() { - try (Response response = resource.sendReminderMessage(authUser, "invalidVoteId")) { + try (Response response = resource.sendReminderMessage(duosUser, "invalidVoteId")) { assertEquals(500, response.getStatus()); } } @Test void testSendDailyMessages() { - try (Response response = resource.sendDailyMessages(authUser)) { + try (Response response = resource.sendDailyMessages(duosUser)) { assertEquals(200, response.getStatus()); } } @@ -70,7 +70,7 @@ void testSendDailyMessages_VoteDigestMessagesThrows() throws InterruptedExceptio doNothing().when(emailService).sendNewDatasetInDUOSNotifications(); doNothing().when(dataAccessRequestService).sendExpirationNotices(); doThrow(new RuntimeException("Exception")).when(emailService).sendVoteDigestMessages(); - try (Response response = resource.sendDailyMessages(authUser)) { + try (Response response = resource.sendDailyMessages(duosUser)) { resource.executor.shutdown(); assertTrue(resource.executor.awaitTermination(1, TimeUnit.SECONDS)); assertEquals(200, response.getStatus()); @@ -84,7 +84,7 @@ void testSendDailyMessages_NewDatasetNotificationsThrows() throws InterruptedExc .sendNewDatasetInDUOSNotifications(); doNothing().when(dataAccessRequestService).sendExpirationNotices(); doNothing().when(emailService).sendVoteDigestMessages(); - try (Response response = resource.sendDailyMessages(authUser)) { + try (Response response = resource.sendDailyMessages(duosUser)) { resource.executor.shutdown(); assertTrue(resource.executor.awaitTermination(1, TimeUnit.SECONDS)); assertEquals(200, response.getStatus()); @@ -97,7 +97,7 @@ void testSendDailyMessages_SendExpirationsThrows() throws InterruptedException { doThrow(new RuntimeException("Exception")) .when(dataAccessRequestService) .sendExpirationNotices(); - try (Response response = resource.sendDailyMessages(authUser)) { + try (Response response = resource.sendDailyMessages(duosUser)) { resource.executor.shutdown(); assertTrue(resource.executor.awaitTermination(1, TimeUnit.SECONDS)); assertEquals(200, response.getStatus()); diff --git a/src/test/java/org/broadinstitute/consent/http/resources/FeatureFlagResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/FeatureFlagResourceTest.java index 11ae757760..b810c1ad05 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/FeatureFlagResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/FeatureFlagResourceTest.java @@ -17,10 +17,10 @@ import java.util.Map; import org.broadinstitute.consent.http.AbstractTestHelper; import org.broadinstitute.consent.http.models.AuthUser; +import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.models.FeatureFlag; import org.broadinstitute.consent.http.models.User; import org.broadinstitute.consent.http.service.FeatureFlagService; -import org.broadinstitute.consent.http.service.UserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -31,15 +31,15 @@ class FeatureFlagResourceTest extends AbstractTestHelper { @Mock private FeatureFlagService featureFlagService; - @Mock private UserService userService; private FeatureFlagResource resource; private final AuthUser authUser = new AuthUser("admin@test.com"); private final User user = new User(1, "admin@test.com", "Admin", new java.util.Date()); + private final DuosUser duosUser = new DuosUser(authUser, user); @BeforeEach void setUp() { - resource = new FeatureFlagResource(featureFlagService, userService); + resource = new FeatureFlagResource(featureFlagService); } @Test @@ -50,18 +50,16 @@ void testCreateOrUpdateFeatureFlag_Create() { when(uriBuilder.path(anyString())).thenReturn(uriBuilder); when(uriBuilder.build()).thenReturn(URI.create("http://localhost/feature/new-feature")); - when(userService.findUserByEmail(authUser.getEmail())).thenReturn(user); FeatureFlag createdFlag = new FeatureFlag("new-feature", "new-value"); when(featureFlagService.exists("new-feature")).thenReturn(false); when(featureFlagService.createOrUpdateFeatureFlag("new-feature", "new-value", user.getUserId())) .thenReturn(createdFlag); Map body = Map.of("value", "new-value"); - Response response = resource.createOrUpdateFeatureFlag(uriInfo, authUser, "new-feature", body); + Response response = resource.createOrUpdateFeatureFlag(uriInfo, duosUser, "new-feature", body); assertEquals(201, response.getStatus()); assertNotNull(response.getEntity()); - verify(userService).findUserByEmail(authUser.getEmail()); verify(featureFlagService).exists("new-feature"); verify(featureFlagService) .createOrUpdateFeatureFlag("new-feature", "new-value", user.getUserId()); @@ -70,7 +68,6 @@ void testCreateOrUpdateFeatureFlag_Create() { @Test void testCreateOrUpdateFeatureFlag_Update() { UriInfo uriInfo = mock(UriInfo.class); - when(userService.findUserByEmail(authUser.getEmail())).thenReturn(user); FeatureFlag updatedFlag = new FeatureFlag("existing-feature", "updated-value"); when(featureFlagService.exists("existing-feature")).thenReturn(true); when(featureFlagService.createOrUpdateFeatureFlag( @@ -79,11 +76,10 @@ void testCreateOrUpdateFeatureFlag_Update() { Map body = Map.of("value", "updated-value"); Response response = - resource.createOrUpdateFeatureFlag(uriInfo, authUser, "existing-feature", body); + resource.createOrUpdateFeatureFlag(uriInfo, duosUser, "existing-feature", body); assertEquals(200, response.getStatus()); assertNotNull(response.getEntity()); - verify(userService).findUserByEmail(authUser.getEmail()); verify(featureFlagService).exists("existing-feature"); verify(featureFlagService) .createOrUpdateFeatureFlag("existing-feature", "updated-value", user.getUserId()); @@ -94,7 +90,7 @@ void testCreateOrUpdateFeatureFlag_MissingValue() { UriInfo uriInfo = mock(UriInfo.class); Map body = Map.of(); - Response response = resource.createOrUpdateFeatureFlag(uriInfo, authUser, "test-id", body); + Response response = resource.createOrUpdateFeatureFlag(uriInfo, duosUser, "test-id", body); assertEquals(400, response.getStatus()); assertNotNull(response.getEntity()); @@ -103,57 +99,49 @@ void testCreateOrUpdateFeatureFlag_MissingValue() { @Test void testCreateOrUpdateFeatureFlag_ServiceError() { UriInfo uriInfo = mock(UriInfo.class); - when(userService.findUserByEmail(authUser.getEmail())).thenReturn(user); when(featureFlagService.exists("test-id")).thenReturn(false); when(featureFlagService.createOrUpdateFeatureFlag("test-id", "value", user.getUserId())) .thenThrow(new RuntimeException("Database error")); Map body = Map.of("value", "value"); - Response response = resource.createOrUpdateFeatureFlag(uriInfo, authUser, "test-id", body); + Response response = resource.createOrUpdateFeatureFlag(uriInfo, duosUser, "test-id", body); assertEquals(500, response.getStatus()); - verify(userService).findUserByEmail(authUser.getEmail()); verify(featureFlagService).exists("test-id"); verify(featureFlagService).createOrUpdateFeatureFlag("test-id", "value", user.getUserId()); } @Test void testDeleteFeatureFlag_Success() { - when(userService.findUserByEmail(authUser.getEmail())).thenReturn(user); doNothing().when(featureFlagService).deleteFeatureFlag("test-id", user.getUserId()); - Response response = resource.deleteFeatureFlag(authUser, "test-id"); + Response response = resource.deleteFeatureFlag(duosUser, "test-id"); assertEquals(204, response.getStatus()); - verify(userService).findUserByEmail(authUser.getEmail()); verify(featureFlagService).deleteFeatureFlag("test-id", user.getUserId()); } @Test void testDeleteFeatureFlag_NotFound() { - when(userService.findUserByEmail(authUser.getEmail())).thenReturn(user); doThrow(new NotFoundException("Feature flag with id 'non-existent' not found")) .when(featureFlagService) .deleteFeatureFlag("non-existent", user.getUserId()); - Response response = resource.deleteFeatureFlag(authUser, "non-existent"); + Response response = resource.deleteFeatureFlag(duosUser, "non-existent"); assertEquals(404, response.getStatus()); - verify(userService).findUserByEmail(authUser.getEmail()); verify(featureFlagService).deleteFeatureFlag("non-existent", user.getUserId()); } @Test void testDeleteFeatureFlag_ServiceError() { - when(userService.findUserByEmail(authUser.getEmail())).thenReturn(user); doThrow(new RuntimeException("Database error")) .when(featureFlagService) .deleteFeatureFlag("test-id", user.getUserId()); - Response response = resource.deleteFeatureFlag(authUser, "test-id"); + Response response = resource.deleteFeatureFlag(duosUser, "test-id"); assertEquals(500, response.getStatus()); - verify(userService).findUserByEmail(authUser.getEmail()); verify(featureFlagService).deleteFeatureFlag("test-id", user.getUserId()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/MailResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/MailResourceTest.java index ce8e19337e..ccbc43aa6d 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/MailResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/MailResourceTest.java @@ -14,6 +14,8 @@ import org.broadinstitute.consent.http.AbstractTestHelper; import org.broadinstitute.consent.http.enumeration.EmailType; import org.broadinstitute.consent.http.models.AuthUser; +import org.broadinstitute.consent.http.models.DuosUser; +import org.broadinstitute.consent.http.models.User; import org.broadinstitute.consent.http.models.mail.MailMessage; import org.broadinstitute.consent.http.service.EmailService; import org.junit.jupiter.api.Test; @@ -26,6 +28,8 @@ class MailResourceTest extends AbstractTestHelper { @Mock private EmailService emailService; private final AuthUser authUser = new AuthUser("test@test.com"); + private final User user = new User(1, authUser.getEmail(), "Display Name", new Date()); + private final DuosUser duosUser = new DuosUser(authUser, user); private MailResource mailResource; @@ -38,7 +42,7 @@ void test_MailResource() { initResource(); when(emailService.fetchEmailMessagesByType(any(), any(), any())) .thenReturn(generateMailMessageList()); - Response response = mailResource.getEmailByType(authUser, EmailType.COLLECT, null, null); + Response response = mailResource.getEmailByType(duosUser, EmailType.COLLECT, null, null); assertEquals(200, response.getStatus()); } @@ -46,7 +50,7 @@ void test_MailResource() { void test_MailResourceEmptyListResponse() { initResource(); when(emailService.fetchEmailMessagesByType(any(), any(), any())).thenReturn(new ArrayList<>()); - Response response = mailResource.getEmailByType(authUser, EmailType.COLLECT, null, null); + Response response = mailResource.getEmailByType(duosUser, EmailType.COLLECT, null, null); assertEquals(200, response.getStatus()); } @@ -55,7 +59,7 @@ void test_MailResourceByUser() { initResource(); when(emailService.fetchEmailMessagesByUserId(any(), any(), any())) .thenReturn(generateMailMessageList()); - Response response = mailResource.getEmailByUser(authUser, 1, null, null); + Response response = mailResource.getEmailByUser(duosUser, 1, null, null); assertEquals(200, response.getStatus()); } @@ -64,7 +68,7 @@ void test_MailResourceByUserEmptyListResponse() { initResource(); when(emailService.fetchEmailMessagesByUserId(any(), any(), any())) .thenReturn(new ArrayList<>()); - Response response = mailResource.getEmailByUser(authUser, 1, null, null); + Response response = mailResource.getEmailByUser(duosUser, 1, null, null); assertEquals(200, response.getStatus()); } @@ -74,7 +78,7 @@ void test_MailResource_date_range_EmptyListResponse() { when(emailService.fetchEmailMessagesByCreateDate(any(), any(), any(), any())) .thenReturn(new ArrayList<>()); Response response = - mailResource.getEmailByDateRange(authUser, "05/11/2021", "05/11/2022", null, null); + mailResource.getEmailByDateRange(duosUser, "05/11/2021", "05/11/2022", null, null); assertEquals(200, response.getStatus()); } @@ -84,7 +88,7 @@ void test_MailResource_date_range_ListResponse() { when(emailService.fetchEmailMessagesByCreateDate(any(), any(), any(), any())) .thenReturn(generateMailMessageList()); Response response = - mailResource.getEmailByDateRange(authUser, "05/11/2021", "05/11/2022", null, null); + mailResource.getEmailByDateRange(duosUser, "05/11/2021", "05/11/2022", null, null); assertEquals(200, response.getStatus()); } @@ -94,7 +98,7 @@ void test_MailResource_date_range_invalid_limit() { assertThrows( BadRequestException.class, () -> { - mailResource.getEmailByDateRange(authUser, "05/11/2021", "05/11/2022", -5, null); + mailResource.getEmailByDateRange(duosUser, "05/11/2021", "05/11/2022", -5, null); }); } @@ -104,7 +108,7 @@ void test_MailResource_date_range_invalid_offset() { assertThrows( BadRequestException.class, () -> { - mailResource.getEmailByDateRange(authUser, "05/11/2021", "05/11/2022", null, -1); + mailResource.getEmailByDateRange(duosUser, "05/11/2021", "05/11/2022", null, -1); }); } @@ -112,7 +116,7 @@ void test_MailResource_date_range_invalid_offset() { void test_MailResource_invalid_start_date() { initResource(); Response response = - mailResource.getEmailByDateRange(authUser, "55/11/2021", "05/11/2022", null, null); + mailResource.getEmailByDateRange(duosUser, "55/11/2021", "05/11/2022", null, null); assertEquals(400, response.getStatus()); } @@ -120,7 +124,7 @@ void test_MailResource_invalid_start_date() { void test_MailResource_invalid_end_date() { initResource(); Response response = - mailResource.getEmailByDateRange(authUser, "05/11/2021", "65/98/20229", null, null); + mailResource.getEmailByDateRange(duosUser, "05/11/2021", "65/98/20229", null, null); assertEquals(400, response.getStatus()); } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/MatchResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/MatchResourceTest.java index 35c50312e1..1ac5eb582f 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/MatchResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/MatchResourceTest.java @@ -85,7 +85,7 @@ void testReprocessPurposeMatches() { when(service.findMatchesByPurposeId(any())).thenReturn(Collections.singletonList(new Match())); initResource(); - Response response = resource.reprocessPurposeMatches(authUser, UUID.randomUUID().toString()); + Response response = resource.reprocessPurposeMatches(duosUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java index e26d922517..facedd12a0 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java @@ -33,7 +33,6 @@ import org.broadinstitute.consent.http.service.DatasetRegistrationService; import org.broadinstitute.consent.http.service.DatasetService; import org.broadinstitute.consent.http.service.ElasticSearchService; -import org.broadinstitute.consent.http.service.UserService; import org.broadinstitute.consent.http.util.gson.GsonUtil; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -50,8 +49,6 @@ class StudyResourceTest extends AbstractTestHelper { @Mock private DatasetRegistrationService datasetRegistrationService; - @Mock private UserService userService; - @Mock private ElasticSearchService elasticSearchService; @Mock private AuthUser authUser; @@ -64,22 +61,20 @@ class StudyResourceTest extends AbstractTestHelper { @BeforeEach void setUp() { - resource = - new StudyResource( - datasetService, userService, datasetRegistrationService, elasticSearchService); + resource = new StudyResource(datasetService, datasetRegistrationService, elasticSearchService); } @Test void testUpdateCustodiansSuccess() { try (var response = - resource.updateCustodians(authUser, 1, "[\"user_1@test.com\", \"user_2@test.com\"]")) { + resource.updateCustodians(duosUser, 1, "[\"user_1@test.com\", \"user_2@test.com\"]")) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @Test void testUpdateCustodiansInvalidEmails() { - try (var response = resource.updateCustodians(authUser, 1, "[\"user_1\", \"@test.com\"]")) { + try (var response = resource.updateCustodians(duosUser, 1, "[\"user_1\", \"@test.com\"]")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -90,7 +85,7 @@ void testUpdateCustodiansNotFound() { .thenThrow(new NotFoundException("Study not found")); try (var response = - resource.updateCustodians(authUser, 1, "[\"user_1@test.com\", \"user_2@test.com\"]")) { + resource.updateCustodians(duosUser, 1, "[\"user_1@test.com\", \"user_2@test.com\"]")) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } @@ -269,17 +264,15 @@ void testUpdateStudyByRegistrationInvalidInput(String input) { schemaV1.getConsentGroups().stream().map(ConsentGroup::getDatasetId).toList(); study.addDatasetIds(Set.of(datasetIds.getFirst() + 1)); } - when(userService.findUserByEmail(any())).thenReturn(user); User createUser = new User(); createUser.setUserId(study.getCreateUserId()); createUser.setEmail("creator@test.com"); - when(authUser.getEmail()).thenReturn(createUser.getEmail()); - when(userService.findUserByEmail(createUser.getEmail())).thenReturn(createUser); + when(duosUser.getUser()).thenReturn(createUser); when(datasetRegistrationService.findStudyById(study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); try (var response = - resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { + resource.updateStudyByRegistration(duosUser, null, study.getStudyId(), input)) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -300,13 +293,12 @@ void testUpdateStudyByRegistrationCreatorOrCustodian() { User createUser = new User(); createUser.setUserId(study.getCreateUserId()); createUser.setEmail("creator@test.com"); - when(authUser.getEmail()).thenReturn(createUser.getEmail()); - when(userService.findUserByEmail(createUser.getEmail())).thenReturn(createUser); + when(duosUser.getUser()).thenReturn(createUser); when(datasetRegistrationService.findStudyById(study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); try (var response = - resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { + resource.updateStudyByRegistration(duosUser, null, study.getStudyId(), input)) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -328,13 +320,12 @@ void testUpdateStudyByRegistrationAdmin() { createUser.setUserId(study.getCreateUserId()); createUser.setEmail("creator@test.com"); createUser.addRole(UserRoles.Admin()); - when(authUser.getEmail()).thenReturn(createUser.getEmail()); - when(userService.findUserByEmail(createUser.getEmail())).thenReturn(createUser); + when(duosUser.getUser()).thenReturn(createUser); when(datasetRegistrationService.findStudyById(study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); try (var response = - resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { + resource.updateStudyByRegistration(duosUser, null, study.getStudyId(), input)) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -356,13 +347,12 @@ void testUpdateStudyByRegistrationNotCreatorOrAdmin() { createUser.setUserId(study.getCreateUserId() + 100); createUser.setEmail("chair@test.com"); createUser.addRole(UserRoles.Chairperson()); - when(authUser.getEmail()).thenReturn(createUser.getEmail()); - when(userService.findUserByEmail(createUser.getEmail())).thenReturn(createUser); + when(duosUser.getUser()).thenReturn(createUser); when(datasetRegistrationService.findStudyById(study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(false); try (var response = - resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { + resource.updateStudyByRegistration(duosUser, null, study.getStudyId(), input)) { assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response.getStatus()); } } @@ -375,9 +365,9 @@ void testDeleteStudyById() throws Exception { admin.setAdminRole(); admin.setUserId(study.getCreateUserId()); when(datasetService.getStudyWithDatasetsById(admin, study.getStudyId())).thenReturn(study); - when(userService.findUserByEmail(any())).thenReturn(admin); + when(duosUser.getUser()).thenReturn(admin); - try (var response = resource.deleteStudyById(authUser, study.getStudyId())) { + try (var response = resource.deleteStudyById(duosUser, study.getStudyId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); verify(datasetService).deleteStudy(study, admin); verify(elasticSearchService, never()).deleteIndex(any(), any()); @@ -388,7 +378,7 @@ void testDeleteStudyById() throws Exception { void testDeleteStudyByIdNotFound() throws Exception { Study study = createMockStudy(); - try (var response = resource.deleteStudyById(authUser, study.getStudyId())) { + try (var response = resource.deleteStudyById(duosUser, study.getStudyId())) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); verify(datasetService, never()).deleteStudy(any(), any()); } @@ -402,9 +392,9 @@ void testDeleteStudyByIdNonCreatorNonAdmin() throws Exception { chair.setChairpersonRole(); chair.setUserId(study.getCreateUserId() + 1); when(datasetService.getStudyWithDatasetsById(chair, study.getStudyId())).thenReturn(study); - when(userService.findUserByEmail(any())).thenReturn(chair); + when(duosUser.getUser()).thenReturn(chair); - try (var response = resource.deleteStudyById(authUser, study.getStudyId())) { + try (var response = resource.deleteStudyById(duosUser, study.getStudyId())) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); verify(datasetService, never()).deleteStudy(any(), any()); } @@ -418,9 +408,9 @@ void testDeleteStudyByIdNotDeletable() throws Exception { admin.setAdminRole(); admin.setUserId(study.getCreateUserId()); when(datasetService.getStudyWithDatasetsById(admin, study.getStudyId())).thenReturn(study); - when(userService.findUserByEmail(any())).thenReturn(admin); + when(duosUser.getUser()).thenReturn(admin); - try (var response = resource.deleteStudyById(authUser, study.getStudyId())) { + try (var response = resource.deleteStudyById(duosUser, study.getStudyId())) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); verify(datasetService, never()).deleteStudy(any(), any()); } @@ -434,9 +424,9 @@ void testDeleteStudyByIdNullDatasets() throws Exception { admin.setAdminRole(); admin.setUserId(study.getCreateUserId()); when(datasetService.getStudyWithDatasetsById(admin, study.getStudyId())).thenReturn(study); - when(userService.findUserByEmail(any())).thenReturn(admin); + when(duosUser.getUser()).thenReturn(admin); - try (var response = resource.deleteStudyById(authUser, study.getStudyId())) { + try (var response = resource.deleteStudyById(duosUser, study.getStudyId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); verify(datasetService).deleteStudy(study, admin); } @@ -451,9 +441,9 @@ void testDeleteStudyByIdNoDatasets() throws Exception { admin.setAdminRole(); admin.setUserId(study.getCreateUserId()); when(datasetService.getStudyWithDatasetsById(admin, study.getStudyId())).thenReturn(study); - when(userService.findUserByEmail(any())).thenReturn(admin); + when(duosUser.getUser()).thenReturn(admin); - try (var response = resource.deleteStudyById(authUser, study.getStudyId())) { + try (var response = resource.deleteStudyById(duosUser, study.getStudyId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); verify(datasetService).deleteStudy(study, admin); } @@ -467,10 +457,10 @@ void testDeleteStudyByIdDeleteFailure() throws Exception { admin.setAdminRole(); admin.setUserId(study.getCreateUserId()); when(datasetService.getStudyWithDatasetsById(admin, study.getStudyId())).thenReturn(study); - when(userService.findUserByEmail(any())).thenReturn(admin); + when(duosUser.getUser()).thenReturn(admin); doThrow(new RuntimeException()).when(datasetService).deleteStudy(study, admin); - try (var response = resource.deleteStudyById(authUser, study.getStudyId())) { + try (var response = resource.deleteStudyById(duosUser, study.getStudyId())) { assertEquals(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, response.getStatus()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/UserResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/UserResourceTest.java index ec3d057e9a..842881abfb 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/UserResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/UserResourceTest.java @@ -219,20 +219,20 @@ void testGetUserByIdNotFound() { void testGetUsers_SO() { User user = createUserWithRole(); user.setSigningOfficialRole(); - when(userService.findUserByEmail(any())).thenReturn(user); + DuosUser du = new DuosUser(authUser, user); when(userService.getUsersAsRole(user, "SigningOfficial")) .thenReturn(Arrays.asList(new User(), new User())); - Response response = userResource.getUsers(authUser, "SigningOfficial"); + Response response = userResource.getUsers(du, "SigningOfficial"); assertEquals(Status.OK.getStatusCode(), response.getStatus()); } @Test void testGetUsers_SO_NoRole() { User user = createUserWithRole(); - when(userService.findUserByEmail(any())).thenReturn(user); + DuosUser du = new DuosUser(authUser, user); - Response response = userResource.getUsers(authUser, "SigningOfficial"); + Response response = userResource.getUsers(du, "SigningOfficial"); assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); } @@ -240,49 +240,41 @@ void testGetUsers_SO_NoRole() { void testGetUsers_Admin() { User user = createUserWithRole(); user.setAdminRole(); - when(userService.findUserByEmail(any())).thenReturn(user); + DuosUser du = new DuosUser(authUser, user); when(userService.getUsersAsRole(user, "Admin")) .thenReturn(Arrays.asList(new User(), new User())); - Response response = userResource.getUsers(authUser, "Admin"); + Response response = userResource.getUsers(du, "Admin"); assertEquals(Status.OK.getStatusCode(), response.getStatus()); } @Test void testGetUsers_Admin_NoRole() { User user = createUserWithRole(); - when(userService.findUserByEmail(any())).thenReturn(user); + DuosUser du = new DuosUser(authUser, user); - Response response = userResource.getUsers(authUser, "Admin"); + Response response = userResource.getUsers(du, "Admin"); assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); } @Test void testGetUsers_UnsupportedRole() { User user = createUserWithRole(); - when(userService.findUserByEmail(any())).thenReturn(user); + DuosUser du = new DuosUser(authUser, user); - Response response = userResource.getUsers(authUser, "Researcher"); + Response response = userResource.getUsers(du, "Researcher"); assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } @Test void testGetUsers_InvalidRole() { User user = createUserWithRole(); - when(userService.findUserByEmail(any())).thenReturn(user); + DuosUser du = new DuosUser(authUser, user); - Response response = userResource.getUsers(authUser, "BadRequest"); + Response response = userResource.getUsers(du, "BadRequest"); assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } - @Test - void testGetUsers_UserNotFound() { - when(userService.findUserByEmail(any())).thenThrow(new NotFoundException()); - - Response response = userResource.getUsers(authUser, "Admin"); - assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); - } - @Test void testCreateExistingUser() { User user = new User(); @@ -477,12 +469,12 @@ void testAddRoleToUserBySoWithPermittedRoles() { void testGetSOsForInstitution() { User user = createUserWithInstitution(); User so = createUserWithRole(); - when(userService.findUserByEmail(any())).thenReturn(user); + DuosUser du = new DuosUser(authUser, user); when(userService.findSOsByInstitutionId(any())) .thenReturn( Arrays.asList(new UserService.SimplifiedUser(so), new UserService.SimplifiedUser(so))); - Response response = userResource.getSOsForInstitution(authUser); + Response response = userResource.getSOsForInstitution(du); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); var body = (List) response.getEntity(); assertFalse(body.isEmpty()); @@ -493,22 +485,14 @@ void testGetSOsForInstitution() { @Test void testGetSOsForInstitution_NoInstitution() { User user = createUserWithRole(); - when(userService.findUserByEmail(any())).thenReturn(user); + DuosUser du = new DuosUser(authUser, user); - Response response = userResource.getSOsForInstitution(authUser); + Response response = userResource.getSOsForInstitution(du); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); var body = (List) response.getEntity(); assertTrue(body.isEmpty()); } - @Test - void testGetSOsForInstitution_UserNotFound() { - when(userService.findUserByEmail(any())).thenThrow(new NotFoundException()); - - Response response = userResource.getSOsForInstitution(authUser); - assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); - } - @Test @SuppressWarnings("unchecked") void testGetSigningOfficialsByInstitution_AsAdmin_DifferentInstitution() { @@ -522,11 +506,10 @@ void testGetSigningOfficialsByInstitution_AsAdmin_DifferentInstitution() { so.setEmail("so@test.com"); so.setInstitutionId(queriedInstitutionId); so.setUserData(Map.of("department", "biology")); - when(userService.findUserByEmail(any())).thenReturn(admin); + DuosUser du = new DuosUser(authUser, admin); when(userService.findSOsWithDataByInstitutionId(queriedInstitutionId)).thenReturn(List.of(so)); - Response response = - userResource.getSigningOfficialsByInstitution(authUser, queriedInstitutionId); + Response response = userResource.getSigningOfficialsByInstitution(du, queriedInstitutionId); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); List body = (List) response.getEntity(); @@ -551,11 +534,10 @@ void testGetSigningOfficialsByInstitution_AsChairperson_DifferentInstitution() { so.setDisplayName("SO User"); so.setEmail("so@test.com"); so.setInstitutionId(queriedInstitutionId); - when(userService.findUserByEmail(any())).thenReturn(chair); + DuosUser du = new DuosUser(authUser, chair); when(userService.findSOsWithDataByInstitutionId(queriedInstitutionId)).thenReturn(List.of(so)); - Response response = - userResource.getSigningOfficialsByInstitution(authUser, queriedInstitutionId); + Response response = userResource.getSigningOfficialsByInstitution(du, queriedInstitutionId); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); List body = (List) response.getEntity(); @@ -578,11 +560,10 @@ void testGetSigningOfficialsByInstitution_AsMember_DifferentInstitution() { so.setDisplayName("SO User"); so.setEmail("so@test.com"); so.setInstitutionId(queriedInstitutionId); - when(userService.findUserByEmail(any())).thenReturn(member); + DuosUser du = new DuosUser(authUser, member); when(userService.findSOsWithDataByInstitutionId(queriedInstitutionId)).thenReturn(List.of(so)); - Response response = - userResource.getSigningOfficialsByInstitution(authUser, queriedInstitutionId); + Response response = userResource.getSigningOfficialsByInstitution(du, queriedInstitutionId); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); List body = (List) response.getEntity(); @@ -601,10 +582,10 @@ void testGetSigningOfficialsByInstitution_AsResearcher_OwnInstitution() { so.setDisplayName("SO User"); so.setEmail("so@test.com"); so.setInstitutionId(institutionId); - when(userService.findUserByEmail(any())).thenReturn(researcher); + DuosUser du = new DuosUser(authUser, researcher); when(userService.findSOsWithDataByInstitutionId(institutionId)).thenReturn(List.of(so)); - Response response = userResource.getSigningOfficialsByInstitution(authUser, institutionId); + Response response = userResource.getSigningOfficialsByInstitution(du, institutionId); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); List body = (List) response.getEntity(); @@ -615,9 +596,9 @@ void testGetSigningOfficialsByInstitution_AsResearcher_OwnInstitution() { void testGetSigningOfficialsByInstitution_AsResearcher_DifferentInstitution() { User researcher = createUserWithRole(); researcher.setInstitutionId(1); - when(userService.findUserByEmail(any())).thenReturn(researcher); + DuosUser du = new DuosUser(authUser, researcher); - Response response = userResource.getSigningOfficialsByInstitution(authUser, 99); + Response response = userResource.getSigningOfficialsByInstitution(du, 99); assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response.getStatus()); } @@ -625,9 +606,9 @@ void testGetSigningOfficialsByInstitution_AsResearcher_DifferentInstitution() { void testGetSigningOfficialsByInstitution_AsResearcher_NullInstitution() { // Researcher with no institution set — Objects.equals(null, anyId) is false → 403 User researcher = createUserWithRole(); // institutionId is null - when(userService.findUserByEmail(any())).thenReturn(researcher); + DuosUser du = new DuosUser(authUser, researcher); - Response response = userResource.getSigningOfficialsByInstitution(authUser, 5); + Response response = userResource.getSigningOfficialsByInstitution(du, 5); assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response.getStatus()); } @@ -635,28 +616,20 @@ void testGetSigningOfficialsByInstitution_AsResearcher_NullInstitution() { void testGetSigningOfficialsByInstitution_ServiceThrows() { User admin = createUserWithRole(); admin.addRole(UserRoles.Admin()); - when(userService.findUserByEmail(any())).thenReturn(admin); + DuosUser du = new DuosUser(authUser, admin); when(userService.findSOsWithDataByInstitutionId(any())) .thenThrow(new RuntimeException("DB error")); - Response response = userResource.getSigningOfficialsByInstitution(authUser, 1); + Response response = userResource.getSigningOfficialsByInstitution(du, 1); assertEquals(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, response.getStatus()); } - @Test - void testGetSigningOfficialsByInstitution_UserNotFound() { - when(userService.findUserByEmail(any())).thenThrow(new NotFoundException()); - - Response response = userResource.getSigningOfficialsByInstitution(authUser, 1); - assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); - } - @Test void testGetUsersByInstitutionNoInstitution() { Integer institutionId = 1; doThrow(new NotFoundException()).when(userService).findUsersByInstitutionId(institutionId); - Response response = userResource.getUsersByInstitution(authUser, institutionId); + Response response = userResource.getUsersByInstitution(duosUser, institutionId); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -664,7 +637,7 @@ void testGetUsersByInstitutionNoInstitution() { void testGetUsersByInstitutionNullInstitution() { doThrow(new IllegalArgumentException()).when(userService).findUsersByInstitutionId(null); - Response response = userResource.getUsersByInstitution(authUser, null); + Response response = userResource.getUsersByInstitution(duosUser, null); assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } @@ -672,7 +645,7 @@ void testGetUsersByInstitutionNullInstitution() { void testGetUsersByInstitutionSuccess() { when(userService.findUsersByInstitutionId(any())).thenReturn(Collections.emptyList()); - Response response = userResource.getUsersByInstitution(authUser, 1); + Response response = userResource.getUsersByInstitution(duosUser, 1); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -987,10 +960,10 @@ void testDeleteRoleFromUser_UserNotFound() { void testGetDatasetsFromUserDacsV2() { User user = createUserWithRole(); user.setChairpersonRoleWithDAC(1); + DuosUser du = new DuosUser(authUser, user); when(datasetService.findDatasetListByDacIds(anyList())).thenReturn(List.of(new Dataset())); - when(userService.findUserByEmail(anyString())).thenReturn(user); - Response response = userResource.getDatasetsFromUserDacsV2(authUser); + Response response = userResource.getDatasetsFromUserDacsV2(du); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -998,19 +971,10 @@ void testGetDatasetsFromUserDacsV2() { void testGetDatasetsFromUserDacsV2DatasetsNotFound() { User user = createUserWithRole(); user.setChairpersonRoleWithDAC(1); + DuosUser du = new DuosUser(authUser, user); when(datasetService.findDatasetListByDacIds(anyList())).thenReturn(List.of()); - when(userService.findUserByEmail(anyString())).thenReturn(user); - - Response response = userResource.getDatasetsFromUserDacsV2(authUser); - assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); - } - - @Test - void testGetDatasetsFromUserDacsV2UserNotFound() { - when(userService.findUserByEmail(anyString())) - .thenThrow(new NotFoundException("User not found")); - Response response = userResource.getDatasetsFromUserDacsV2(authUser); + Response response = userResource.getDatasetsFromUserDacsV2(du); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -1162,7 +1126,7 @@ void testDeleteAcknowledgementForUser() { when(acknowledgementService.findAcknowledgementForUserByKey(any(), any())) .thenReturn(acknowledgementMap.get(acknowledgementKey)); - try (Response response = userResource.deleteUserAcknowledgement(authUser, acknowledgementKey)) { + try (Response response = userResource.deleteUserAcknowledgement(duosUser, acknowledgementKey)) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } } @@ -1172,7 +1136,7 @@ void testDeleteMissingAcknowledgementForUser() { createUserWithRole(); when(acknowledgementService.findAcknowledgementForUserByKey(any(), any())).thenReturn(null); - try (Response response = userResource.deleteUserAcknowledgement(authUser, "key")) { + try (Response response = userResource.deleteUserAcknowledgement(duosUser, "key")) { assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/VoteResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/VoteResourceTest.java index b064f12eb8..540e6ce2d6 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/VoteResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/VoteResourceTest.java @@ -14,12 +14,11 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.broadinstitute.consent.http.models.AuthUser; +import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.models.Election; import org.broadinstitute.consent.http.models.User; import org.broadinstitute.consent.http.models.Vote; import org.broadinstitute.consent.http.service.ElectionService; -import org.broadinstitute.consent.http.service.UserService; import org.broadinstitute.consent.http.service.VoteService; import org.glassfish.jersey.server.ContainerRequest; import org.junit.jupiter.api.Test; @@ -32,13 +31,11 @@ class VoteResourceTest { @Mock private ContainerRequest request; - @Mock private UserService userService; - @Mock private VoteService voteService; @Mock private ElectionService electionService; - @Mock private AuthUser authUser; + @Mock private DuosUser duosUser; private final User user = new User(); @@ -49,13 +46,13 @@ class VoteResourceTest { private final Gson gson = new Gson(); private void initResource() { - resource = new VoteResource(userService, voteService, electionService); + resource = new VoteResource(voteService, electionService); } @Test void testUpdateVotes_invalidJson() { initResource(); - try (var response = resource.updateVotes(authUser, request, "{\"vote\": true, \"ID\":12345}")) { + try (var response = resource.updateVotes(duosUser, request, "{\"vote\": true, \"ID\":12345}")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -68,7 +65,7 @@ void testUpdateVotes_nullIds() { voteUpdate.setRationale("example"); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -78,7 +75,7 @@ void testUpdateVotes_noIds() { initResource(); Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(true, "example", new ArrayList<>()); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -90,7 +87,7 @@ void testUpdateVotes_noVotesForIds() { Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(true, "example", List.of(1)); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } @@ -104,7 +101,7 @@ void testUpdateVotes_noVoteValue() { voteUpdate.setVoteIds(List.of(1, 2, 3)); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -113,13 +110,13 @@ void testUpdateVotes_noVoteValue() { void testUpdateVotes_invalidUser() { user.setUserId(1); vote.setUserId(2); - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(voteService.findVotesByIds(any())).thenReturn(List.of(vote)); initResource(); Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(true, "example", List.of(1, 2, 3)); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } @@ -133,7 +130,7 @@ void testUpdateVotes_closedElection() { Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(true, "example", List.of(1, 2, 3)); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -150,13 +147,13 @@ void testUpdateVotes_allMemberVotes() { voteTwo.setUserId(1); Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(true, "example", List.of(1, 2, 3)); when(voteService.findVotesByIds(anyList())).thenReturn(List.of(vote, voteTwo)); - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(voteService.updateVotesWithValue(anyList(), anyBoolean(), anyString(), any())) .thenReturn(List.of(vote)); initResource(); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } } @@ -173,14 +170,14 @@ void testUpdateVotes_allYes_allRP() { voteTwo.setUserId(1); Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(true, "example", List.of(1, 2, 3)); when(voteService.findVotesByIds(anyList())).thenReturn(List.of(vote, voteTwo)); - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(voteService.updateVotesWithValue(anyList(), anyBoolean(), anyString(), any())) .thenReturn(List.of(vote)); initResource(); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } } @@ -197,13 +194,13 @@ void testUpdateVotes_allNo_allRP() { voteTwo.setUserId(1); Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(false, "example", List.of(1, 2, 3)); when(voteService.findVotesByIds(anyList())).thenReturn(List.of(vote, voteTwo)); - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(voteService.updateVotesWithValue(anyList(), anyBoolean(), anyString(), any())) .thenReturn(List.of(vote)); initResource(); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } } @@ -224,7 +221,7 @@ void testUpdateVotes_allYes_allDataAccess_AllCards() { election.setElectionId(1); Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(true, "example", List.of(1, 2, 3)); when(voteService.findVotesByIds(anyList())).thenReturn(List.of(vote, voteTwo)); - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(voteService.updateVotesWithValue(anyList(), anyBoolean(), anyString(), any())) .thenReturn(List.of(vote, voteTwo)); when(electionService.findElectionsByVoteIdsAndType(anyList(), anyString())) @@ -235,7 +232,7 @@ void testUpdateVotes_allYes_allDataAccess_AllCards() { initResource(); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } } @@ -254,13 +251,13 @@ void testUpdateVotes_allNo_allDataAccess_AllCards() { voteTwo.setVote(false); Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(false, "example", List.of(1, 2, 3)); when(voteService.findVotesByIds(anyList())).thenReturn(List.of(vote, voteTwo)); - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(voteService.updateVotesWithValue(anyList(), anyBoolean(), anyString(), any())) .thenReturn(List.of(vote, voteTwo)); initResource(); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } } @@ -283,7 +280,7 @@ void testUpdateVotes_allYes_allDataAccess_NotAllCards() { election.setElectionId(2); Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(true, "example", List.of(1, 2, 3)); when(voteService.findVotesByIds(anyList())).thenReturn(List.of(vote, voteTwo)); - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(electionService.findElectionsByVoteIdsAndType(anyList(), anyString())) .thenReturn(List.of(election, electionTwo)); when(electionService.findElectionsWithCardHoldingUsersByElectionIds(anyList())) @@ -291,7 +288,7 @@ void testUpdateVotes_allYes_allDataAccess_NotAllCards() { initResource(); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } } @@ -300,7 +297,7 @@ void testUpdateVotes_allYes_allDataAccess_NotAllCards() { void testUpdateVotes_noRationale() { user.setUserId(1); vote.setUserId(1); - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(voteService.findVotesByIds(any())).thenReturn(List.of(vote)); initResource(); @@ -309,7 +306,7 @@ void testUpdateVotes_noRationale() { voteUpdate.setVoteIds(List.of(1, 2, 3)); try (var response = - resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + resource.updateVotes(duosUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -319,7 +316,7 @@ void testUpdateVoteRationale_InvalidJson() { String invalidJson = "[]"; initResource(); - try (var response = resource.updateVoteRationale(authUser, invalidJson)) { + try (var response = resource.updateVoteRationale(duosUser, invalidJson)) { assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } } @@ -330,7 +327,7 @@ void testUpdateVoteRationale_EmptyVoteIds() { update.setRationale("Rationale"); initResource(); - try (var response = resource.updateVoteRationale(authUser, new Gson().toJson(update))) { + try (var response = resource.updateVoteRationale(duosUser, new Gson().toJson(update))) { assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } } @@ -338,14 +335,14 @@ void testUpdateVoteRationale_EmptyVoteIds() { @Test void testUpdateVoteRationale_NoVotesFound() { user.setUserId(1); - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(voteService.findVotesByIds(any())).thenReturn(List.of()); Vote.RationaleUpdate update = new Vote.RationaleUpdate(); update.setVoteIds(List.of(1)); update.setRationale("Rationale"); initResource(); - try (var response = resource.updateVoteRationale(authUser, new Gson().toJson(update))) { + try (var response = resource.updateVoteRationale(duosUser, new Gson().toJson(update))) { assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); } } @@ -354,14 +351,14 @@ void testUpdateVoteRationale_NoVotesFound() { void testUpdateVoteRationale_UserNotOwnerOfVotes() { user.setUserId(1); vote.setUserId(2); - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(voteService.findVotesByIds(any())).thenReturn(List.of(vote)); Vote.RationaleUpdate update = new Vote.RationaleUpdate(); update.setVoteIds(List.of(1)); update.setRationale("Rationale"); initResource(); - try (var response = resource.updateVoteRationale(authUser, new Gson().toJson(update))) { + try (var response = resource.updateVoteRationale(duosUser, new Gson().toJson(update))) { assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); } } @@ -370,7 +367,7 @@ void testUpdateVoteRationale_UserNotOwnerOfVotes() { void testUpdateVoteRationale_Success() { user.setUserId(1); vote.setUserId(1); - when(userService.findUserByEmail(any())).thenReturn(user); + when(duosUser.getUser()).thenReturn(user); when(voteService.findVotesByIds(any())).thenReturn(List.of(vote)); when(voteService.updateRationaleByVoteIds(any(), any())).thenReturn(List.of(vote)); Vote.RationaleUpdate update = new Vote.RationaleUpdate(); @@ -378,7 +375,7 @@ void testUpdateVoteRationale_Success() { update.setRationale("Rationale"); initResource(); - try (var response = resource.updateVoteRationale(authUser, new Gson().toJson(update))) { + try (var response = resource.updateVoteRationale(duosUser, new Gson().toJson(update))) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } } From c0bbff62df577b92df9d076d1af92127aae9babf Mon Sep 17 00:00:00 2001 From: Gregory Rushton Date: Fri, 17 Jul 2026 11:35:42 -0400 Subject: [PATCH 2/9] doc: update to include 401s --- src/main/resources/assets/api-docs.yaml | 23 ++++++++++++++++++- .../assets/paths/adminFeatureById.yaml | 4 ++++ src/main/resources/assets/paths/dac.yaml | 2 ++ src/main/resources/assets/paths/dacById.yaml | 2 ++ src/main/resources/assets/paths/darV2.yaml | 2 ++ .../assets/paths/darV2ByReferenceId.yaml | 2 ++ .../assets/paths/datasetByIdDataUse.yaml | 2 ++ .../resources/assets/paths/datasetIndex.yaml | 2 ++ .../assets/paths/datasetIndexById.yaml | 4 ++++ .../resources/assets/paths/datasetV3.yaml | 2 ++ .../assets/paths/getDatasetsFromUserDacs.yaml | 2 ++ .../paths/getDatasetsFromUserDacsV2.yaml | 2 ++ .../assets/paths/progressReport.yaml | 2 ++ .../resources/assets/paths/studyById.yaml | 4 ++++ .../assets/paths/studyByIdCustodians.yaml | 2 ++ .../paths/userInstitutionByInstitutionId.yaml | 2 ++ .../userInstitutionSigningOfficials.yaml | 2 ++ src/main/resources/assets/paths/votes.yaml | 2 ++ .../assets/paths/votesRationale.yaml | 2 ++ 19 files changed, 64 insertions(+), 1 deletion(-) diff --git a/src/main/resources/assets/api-docs.yaml b/src/main/resources/assets/api-docs.yaml index 8d8a1f590d..03c1ae3fdd 100644 --- a/src/main/resources/assets/api-docs.yaml +++ b/src/main/resources/assets/api-docs.yaml @@ -255,6 +255,8 @@ paths: type: array items: $ref: '#/components/schemas/User' + 401: + description: Unauthorized. 429: description: Too Many Requests - rate limit exceeded content: @@ -295,6 +297,8 @@ paths: responses: 201: description: Returns the created draft Data Access Request. + 401: + description: Unauthorized. 429: description: Too Many Requests - rate limit exceeded content: @@ -318,6 +322,8 @@ paths: type: array items: $ref: './schemas/DataAccessRequest.yaml' + 401: + description: Unauthorized. 429: description: Too Many Requests - rate limit exceeded content: @@ -354,6 +360,8 @@ paths: responses: 201: description: Returns the updated draft Data Access Request. + 401: + description: Unauthorized. 403: description: Updates are restricted to the create user. 429: @@ -384,6 +392,8 @@ paths: application/json: schema: $ref: './schemas/DataAccessRequest.yaml' + 401: + description: Unauthorized. 429: description: Too Many Requests - rate limit exceeded content: @@ -454,6 +464,8 @@ paths: application/json: schema: $ref: './schemas/DataAccessRequest.yaml' + 401: + description: Unauthorized. 429: description: Too Many Requests - rate limit exceeded content: @@ -520,7 +532,8 @@ paths: application/json: schema: $ref: './schemas/DataAccessRequest.yaml' - + 401: + description: Unauthorized. 429: description: Too Many Requests - rate limit exceeded content: @@ -639,6 +652,8 @@ paths: responses: 200: description: Email successfully sent + 401: + description: Unauthorized. 429: description: Too Many Requests - rate limit exceeded content: @@ -850,6 +865,8 @@ paths: type: array items: $ref: '#/components/schemas/MatchResult' + 401: + description: Unauthorized. 429: description: Too Many Requests - rate limit exceeded content: @@ -916,6 +933,8 @@ paths: type: array items: $ref: '#/components/schemas/SimplifiedUser' + 401: + description: Unauthorized. 404: description: User not found 429: @@ -954,6 +973,8 @@ paths: $ref: '#/components/schemas/User' 400: description: Unsupported or Invalid role name + 401: + description: Unauthorized. 404: description: The user does not have the given role, or role is SO and the user does not have an Institution 429: diff --git a/src/main/resources/assets/paths/adminFeatureById.yaml b/src/main/resources/assets/paths/adminFeatureById.yaml index f725c6e8a1..37c868c7cb 100644 --- a/src/main/resources/assets/paths/adminFeatureById.yaml +++ b/src/main/resources/assets/paths/adminFeatureById.yaml @@ -59,6 +59,8 @@ post: application/json: schema: $ref: '../schemas/ErrorResponse.yaml' + 401: + description: Unauthorized. 403: description: Forbidden - Admin role required content: @@ -96,6 +98,8 @@ delete: responses: 204: description: Feature flag deleted successfully + 401: + description: Unauthorized. 403: description: Forbidden - Admin role required content: diff --git a/src/main/resources/assets/paths/dac.yaml b/src/main/resources/assets/paths/dac.yaml index aaadc6ad59..af483b1802 100644 --- a/src/main/resources/assets/paths/dac.yaml +++ b/src/main/resources/assets/paths/dac.yaml @@ -83,6 +83,8 @@ get: type: array items: $ref: '../schemas/Dac.yaml' + 401: + description: Unauthorized. 429: description: Too Many Requests - rate limit exceeded content: diff --git a/src/main/resources/assets/paths/dacById.yaml b/src/main/resources/assets/paths/dacById.yaml index e28c4016da..30de23be91 100644 --- a/src/main/resources/assets/paths/dacById.yaml +++ b/src/main/resources/assets/paths/dacById.yaml @@ -18,6 +18,8 @@ get: application/json: schema: $ref: '../schemas/Dac.yaml' + 401: + description: Unauthorized. 404: description: No DAC found with the given ID 429: diff --git a/src/main/resources/assets/paths/darV2.yaml b/src/main/resources/assets/paths/darV2.yaml index 73eea61703..d7961c5714 100644 --- a/src/main/resources/assets/paths/darV2.yaml +++ b/src/main/resources/assets/paths/darV2.yaml @@ -23,6 +23,8 @@ post: type: array items: $ref: '../schemas/DataAccessRequest.yaml' + 401: + description: Unauthorized. 429: description: Too Many Requests - rate limit exceeded content: diff --git a/src/main/resources/assets/paths/darV2ByReferenceId.yaml b/src/main/resources/assets/paths/darV2ByReferenceId.yaml index fdfa13dcd1..7cb2895cae 100644 --- a/src/main/resources/assets/paths/darV2ByReferenceId.yaml +++ b/src/main/resources/assets/paths/darV2ByReferenceId.yaml @@ -57,6 +57,8 @@ put: application/json: schema: $ref: '../schemas/DataAccessRequest.yaml' + 401: + description: Unauthorized. 403: description: Updates are restricted to the create user. 429: diff --git a/src/main/resources/assets/paths/datasetByIdDataUse.yaml b/src/main/resources/assets/paths/datasetByIdDataUse.yaml index b471452fc7..358fc07013 100644 --- a/src/main/resources/assets/paths/datasetByIdDataUse.yaml +++ b/src/main/resources/assets/paths/datasetByIdDataUse.yaml @@ -35,6 +35,8 @@ put: description: Not modified 400: description: Bad Request (invalid input) + 401: + description: Unauthorized. 404: description: Not Found 429: diff --git a/src/main/resources/assets/paths/datasetIndex.yaml b/src/main/resources/assets/paths/datasetIndex.yaml index af3811d7b0..8eccbbfbc0 100644 --- a/src/main/resources/assets/paths/datasetIndex.yaml +++ b/src/main/resources/assets/paths/datasetIndex.yaml @@ -8,6 +8,8 @@ post: responses: 200: description: All datasets have been indexed + 401: + description: Unauthorized. 404: description: No datasets found to index 429: diff --git a/src/main/resources/assets/paths/datasetIndexById.yaml b/src/main/resources/assets/paths/datasetIndexById.yaml index 3775d87b20..48b3a77f5a 100644 --- a/src/main/resources/assets/paths/datasetIndexById.yaml +++ b/src/main/resources/assets/paths/datasetIndexById.yaml @@ -15,6 +15,8 @@ post: responses: 200: description: The dataset has been indexed + 401: + description: Unauthorized. 404: description: Dataset not found 429: @@ -40,6 +42,8 @@ delete: responses: 200: description: The dataset index has been deleted + 401: + description: Unauthorized. 429: description: Too Many Requests - rate limit exceeded content: diff --git a/src/main/resources/assets/paths/datasetV3.yaml b/src/main/resources/assets/paths/datasetV3.yaml index 72745ecc2f..0f6849966f 100644 --- a/src/main/resources/assets/paths/datasetV3.yaml +++ b/src/main/resources/assets/paths/datasetV3.yaml @@ -58,6 +58,8 @@ post: $ref: '../schemas/Dataset.yaml' 400: description: Bad Request (invalid input) + 401: + description: Unauthorized. 409: description: Dataset Name given is already in use by another dataset 429: diff --git a/src/main/resources/assets/paths/getDatasetsFromUserDacs.yaml b/src/main/resources/assets/paths/getDatasetsFromUserDacs.yaml index 336fce37a4..d4acde5abf 100644 --- a/src/main/resources/assets/paths/getDatasetsFromUserDacs.yaml +++ b/src/main/resources/assets/paths/getDatasetsFromUserDacs.yaml @@ -14,6 +14,8 @@ get: type: array items: $ref: '../schemas/Dataset.yaml' + 401: + description: Unauthorized. 404: description: User not found 429: diff --git a/src/main/resources/assets/paths/getDatasetsFromUserDacsV2.yaml b/src/main/resources/assets/paths/getDatasetsFromUserDacsV2.yaml index c95589e293..89a3162002 100644 --- a/src/main/resources/assets/paths/getDatasetsFromUserDacsV2.yaml +++ b/src/main/resources/assets/paths/getDatasetsFromUserDacsV2.yaml @@ -16,6 +16,8 @@ get: type: array items: $ref: '../schemas/Dataset.yaml' + 401: + description: Unauthorized. 404: description: User not found or no datasets found for user 429: diff --git a/src/main/resources/assets/paths/progressReport.yaml b/src/main/resources/assets/paths/progressReport.yaml index fd6a880e0d..1ef3bddfbc 100644 --- a/src/main/resources/assets/paths/progressReport.yaml +++ b/src/main/resources/assets/paths/progressReport.yaml @@ -45,6 +45,8 @@ post: application/json: schema: $ref: '../schemas/ErrorResponse.yaml' + 401: + description: Unauthorized. 403: description: Forbidden content: diff --git a/src/main/resources/assets/paths/studyById.yaml b/src/main/resources/assets/paths/studyById.yaml index 97f0960c47..76b9973123 100644 --- a/src/main/resources/assets/paths/studyById.yaml +++ b/src/main/resources/assets/paths/studyById.yaml @@ -85,6 +85,8 @@ put: $ref: '../schemas/Study.yaml' 400: description: Bad Request when schema is invalid or the required consent groups are not provided. + 401: + description: Unauthorized. 403: description: Forbidden 404: @@ -118,6 +120,8 @@ delete: description: The Study was successfully deleted 400: description: Study is in use and cannot be deleted + 401: + description: Unauthorized. 404: description: Not Found 429: diff --git a/src/main/resources/assets/paths/studyByIdCustodians.yaml b/src/main/resources/assets/paths/studyByIdCustodians.yaml index ccab14602d..c16fda3a42 100644 --- a/src/main/resources/assets/paths/studyByIdCustodians.yaml +++ b/src/main/resources/assets/paths/studyByIdCustodians.yaml @@ -31,6 +31,8 @@ put: description: | Bad Request when schema is invalid or the required custodian values are not valid email addresses + 401: + description: Unauthorized. 403: description: User is not authorized 404: diff --git a/src/main/resources/assets/paths/userInstitutionByInstitutionId.yaml b/src/main/resources/assets/paths/userInstitutionByInstitutionId.yaml index 5483a5e7b8..22542dda78 100644 --- a/src/main/resources/assets/paths/userInstitutionByInstitutionId.yaml +++ b/src/main/resources/assets/paths/userInstitutionByInstitutionId.yaml @@ -23,6 +23,8 @@ get: $ref: '../schemas/User.yaml' 400: description: Bad Request + 401: + description: Unauthorized. 404: description: Not Found 429: diff --git a/src/main/resources/assets/paths/userInstitutionSigningOfficials.yaml b/src/main/resources/assets/paths/userInstitutionSigningOfficials.yaml index 8e4d6cd796..58dc567736 100644 --- a/src/main/resources/assets/paths/userInstitutionSigningOfficials.yaml +++ b/src/main/resources/assets/paths/userInstitutionSigningOfficials.yaml @@ -35,6 +35,8 @@ get: type: array items: $ref: '../schemas/SigningOfficialUser.yaml' + 401: + description: Unauthorized. 403: description: > Forbidden — the authenticated user is a Researcher who requested an institution diff --git a/src/main/resources/assets/paths/votes.yaml b/src/main/resources/assets/paths/votes.yaml index 94d4110eaa..8eb3f4184c 100644 --- a/src/main/resources/assets/paths/votes.yaml +++ b/src/main/resources/assets/paths/votes.yaml @@ -46,6 +46,8 @@ put: description: Successfully updated votes 400: description: Bad Request (invalid input) + 401: + description: Unauthorized. 404: description: Not Found 409: diff --git a/src/main/resources/assets/paths/votesRationale.yaml b/src/main/resources/assets/paths/votesRationale.yaml index 51743fa879..09a4536387 100644 --- a/src/main/resources/assets/paths/votesRationale.yaml +++ b/src/main/resources/assets/paths/votesRationale.yaml @@ -33,6 +33,8 @@ put: description: Successfully updated votes 400: description: Bad Request (invalid input) + 401: + description: Unauthorized. 404: description: Not Found 409: From 349a53c85cb4a72afb50baf515299c3d390dca6c Mon Sep 17 00:00:00 2001 From: Gregory Rushton Date: Fri, 17 Jul 2026 13:33:11 -0400 Subject: [PATCH 3/9] fix: stub DuosUser.getUser() by default in Draft/Study resource tests Addresses Copilot review feedback on PR #2979: tests were passing a mocked DuosUser without stubbing getUser(), defaulting to null and making the tests less representative of production callers. DraftResource always dereferences duosUser.getUser() as the first statement in every method, so the default is added once in initResource() and used by every test. StudyResource's patchStudyById/getStudyById short-circuit before touching the user on some not-found paths, so a blanket default there would trip Mockito's strict-stubbing check; only the three updateCustodians tests (which unconditionally consume the user) got an explicit stub. Co-Authored-By: Claude Sonnet 5 --- .../consent/http/resources/DraftResourceTest.java | 5 +++-- .../consent/http/resources/StudyResourceTest.java | 3 +++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java index f788b55588..852e15bba8 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java @@ -53,11 +53,13 @@ class DraftResourceTest { private void initResource() { resource = new DraftResource(draftService); + // Default to a non-null user so tests are representative of production DuosUser principals; + // individual tests override this stub when they need a different User. + when(duosUser.getUser()).thenReturn(user); } @Test void testGetDraftWhenNoneExistForUser() { - when(duosUser.getUser()).thenReturn(user); when(draftService.findDraftSummariesForUser(any())).thenReturn(Collections.emptySet()); initResource(); Response response = resource.getDrafts(duosUser); @@ -75,7 +77,6 @@ void testGetDraftsWhenOneExistForUser() { new Date(), new Date(), DraftType.STUDY_DATASET_SUBMISSION_V1)); - when(duosUser.getUser()).thenReturn(user); when(draftService.findDraftSummariesForUser(any())).thenReturn(draftSummaries); initResource(); Response response = resource.getDrafts(duosUser); diff --git a/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java index facedd12a0..572247488f 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java @@ -66,6 +66,7 @@ void setUp() { @Test void testUpdateCustodiansSuccess() { + when(duosUser.getUser()).thenReturn(user); try (var response = resource.updateCustodians(duosUser, 1, "[\"user_1@test.com\", \"user_2@test.com\"]")) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); @@ -74,6 +75,7 @@ void testUpdateCustodiansSuccess() { @Test void testUpdateCustodiansInvalidEmails() { + when(duosUser.getUser()).thenReturn(user); try (var response = resource.updateCustodians(duosUser, 1, "[\"user_1\", \"@test.com\"]")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } @@ -81,6 +83,7 @@ void testUpdateCustodiansInvalidEmails() { @Test void testUpdateCustodiansNotFound() { + when(duosUser.getUser()).thenReturn(user); when(datasetService.updateStudyCustodians(any(), any(), any())) .thenThrow(new NotFoundException("Study not found")); From 3d9700bb2034a0913f4153c53c6fe4f2fb6edfe4 Mon Sep 17 00:00:00 2001 From: Gregory Rushton Date: Fri, 17 Jul 2026 13:45:59 -0400 Subject: [PATCH 4/9] test: merge fixes --- .../consent/http/resources/StudyResourceTest.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java index 2872962ee2..31b3a18bc8 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java @@ -324,13 +324,11 @@ void testUpdateStudyByRegistrationRejectsConsentGroupRename() { User createUser = new User(); createUser.setUserId(study.getCreateUserId()); createUser.setEmail("creator@test.com"); - when(authUser.getEmail()).thenReturn(createUser.getEmail()); - when(userService.findUserByEmail(createUser.getEmail())).thenReturn(createUser); when(datasetService.getStudyWithDatasetsById(createUser, study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); try (var response = - resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { + resource.updateStudyByRegistration(duosUser, null, study.getStudyId(), input)) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -353,7 +351,6 @@ void testUpdateStudyByRegistrationAdmin() { createUser.setEmail("creator@test.com"); createUser.addRole(UserRoles.Admin()); when(duosUser.getUser()).thenReturn(createUser); - when(datasetRegistrationService.findStudyById(study.getStudyId())).thenReturn(study); when(datasetService.getStudyWithDatasetsById(createUser, study.getStudyId())).thenReturn(study); when(datasetService.getStudyWithDatasetsById(createUser, study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); @@ -382,7 +379,6 @@ void testUpdateStudyByRegistrationNotCreatorOrAdmin() { createUser.setEmail("chair@test.com"); createUser.addRole(UserRoles.Chairperson()); when(duosUser.getUser()).thenReturn(createUser); - when(datasetRegistrationService.findStudyById(study.getStudyId())).thenReturn(study); when(datasetService.getStudyWithDatasetsById(createUser, study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(false); From 0af8885ed56897ec261c269b2b45f18e207b7bef Mon Sep 17 00:00:00 2001 From: Gregory Rushton Date: Fri, 17 Jul 2026 14:05:05 -0400 Subject: [PATCH 5/9] fix: update StudyResourceTest for updateStudyByRegistration signature change The develop merge (DT-3595/3596/3597) switched updateStudyByRegistration to fetch the existing study via datasetService.getStudyWithDatasetsById instead of datasetRegistrationService.findStudyById. Three tests were still stubbing the old lookup method, and one was missing the duosUser.getUser() stub entirely, causing Mockito strict-stubbing argument-mismatch exceptions (surfaced as unexpected 500s). Co-Authored-By: Claude Sonnet 5 --- .../consent/http/resources/StudyResourceTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java index 31b3a18bc8..367690f3bc 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java @@ -271,7 +271,7 @@ void testUpdateStudyByRegistrationInvalidInput(String input) { createUser.setUserId(study.getCreateUserId()); createUser.setEmail("creator@test.com"); when(duosUser.getUser()).thenReturn(createUser); - when(datasetRegistrationService.findStudyById(study.getStudyId())).thenReturn(study); + when(datasetService.getStudyWithDatasetsById(createUser, study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); try (var response = @@ -297,7 +297,7 @@ void testUpdateStudyByRegistrationCreatorOrCustodian() { createUser.setUserId(study.getCreateUserId()); createUser.setEmail("creator@test.com"); when(duosUser.getUser()).thenReturn(createUser); - when(datasetRegistrationService.findStudyById(study.getStudyId())).thenReturn(study); + when(datasetService.getStudyWithDatasetsById(createUser, study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); try (var response = @@ -324,6 +324,7 @@ void testUpdateStudyByRegistrationRejectsConsentGroupRename() { User createUser = new User(); createUser.setUserId(study.getCreateUserId()); createUser.setEmail("creator@test.com"); + when(duosUser.getUser()).thenReturn(createUser); when(datasetService.getStudyWithDatasetsById(createUser, study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); From 00c74586ff359b4896e57fe91d119ad4d7e2a5e3 Mon Sep 17 00:00:00 2001 From: Gregory Rushton Date: Fri, 17 Jul 2026 14:48:30 -0400 Subject: [PATCH 6/9] fix: address sonar warning --- .../broadinstitute/consent/http/resources/DatasetResource.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DatasetResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DatasetResource.java index f8418fa274..f0c4715611 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DatasetResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DatasetResource.java @@ -119,8 +119,6 @@ public Response createDatasetRegistration( throw new BadRequestException("Please correct the following fields:\n" + errorMessage); } - DatasetRegistrationSchemaV1 registration = - GsonUtil.getInstance().fromJson(json, DatasetRegistrationSchemaV1.class); User user = duosUser.getUser(); // key: field name (not file name), value: file body part From 7043b016fd0fa97d516c59eace6b1b7e07c4f4be Mon Sep 17 00:00:00 2001 From: Gregory Rushton Date: Fri, 17 Jul 2026 14:49:45 -0400 Subject: [PATCH 7/9] doc: address sonar warning --- .../consent/http/resources/DraftResourceTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java index 852e15bba8..0d5185a2f7 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java @@ -53,8 +53,7 @@ class DraftResourceTest { private void initResource() { resource = new DraftResource(draftService); - // Default to a non-null user so tests are representative of production DuosUser principals; - // individual tests override this stub when they need a different User. + // Individual tests override this stub when they need a different User. when(duosUser.getUser()).thenReturn(user); } From a6ab13b865037cffce4f556595167b239bb6ef0b Mon Sep 17 00:00:00 2001 From: Gregory Rushton Date: Mon, 20 Jul 2026 13:06:58 -0400 Subject: [PATCH 8/9] test: add missing test coverage --- .../DuosUserAuthenticatorTest.java | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 src/test/java/org/broadinstitute/consent/http/authentication/DuosUserAuthenticatorTest.java diff --git a/src/test/java/org/broadinstitute/consent/http/authentication/DuosUserAuthenticatorTest.java b/src/test/java/org/broadinstitute/consent/http/authentication/DuosUserAuthenticatorTest.java new file mode 100644 index 0000000000..4dc9a3639c --- /dev/null +++ b/src/test/java/org/broadinstitute/consent/http/authentication/DuosUserAuthenticatorTest.java @@ -0,0 +1,145 @@ +package org.broadinstitute.consent.http.authentication; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import jakarta.ws.rs.NotAuthorizedException; +import jakarta.ws.rs.NotFoundException; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; +import java.util.List; +import java.util.Optional; +import org.broadinstitute.consent.http.AbstractTestHelper; +import org.broadinstitute.consent.http.filters.ClaimsCache; +import org.broadinstitute.consent.http.models.DuosUser; +import org.broadinstitute.consent.http.models.User; +import org.broadinstitute.consent.http.models.sam.UserStatusInfo; +import org.broadinstitute.consent.http.service.UserService; +import org.broadinstitute.consent.http.service.sam.SamService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class DuosUserAuthenticatorTest extends AbstractTestHelper { + + @Mock private SamService samService; + @Mock private UserService userService; + + private DuosUserAuthenticator authenticator; + private final ClaimsCache claimsCache = new ClaimsCache(); + private final String bearerToken = randomAlphabetic(100); + private final MultivaluedMap headerMap = new MultivaluedHashMap<>(); + + @BeforeEach + void setUp() { + AuthorizationHelper authorizationHelper = + new AuthorizationHelper(samService, userService, claimsCache); + authenticator = new DuosUserAuthenticator(authorizationHelper); + claimsCache.cache.invalidateAll(); + } + + /** When the bearer token has no cache entry, authenticate returns empty and logs an error. */ + @Test + void testAuthenticateTokenNotInCache() { + Optional result = authenticator.authenticate(bearerToken); + + assertFalse(result.isPresent()); + } + + /** When headers are cached and the user is found, authenticate returns a populated DuosUser. */ + @Test + void testAuthenticateUserFound() { + headerMap.put(ClaimsCache.OAUTH2_CLAIM_access_token, List.of(bearerToken)); + headerMap.put(ClaimsCache.OAUTH2_CLAIM_email, List.of("test@example.com")); + headerMap.put(ClaimsCache.OAUTH2_CLAIM_name, List.of("Test User")); + claimsCache.loadCache(bearerToken, headerMap); + + User user = new User(); + user.setEmail("test@example.com"); + when(userService.findUserByEmail("test@example.com")).thenReturn(user); + + Optional result = authenticator.authenticate(bearerToken); + + assertTrue(result.isPresent()); + assertNotNull(result.get().getEmail()); + } + + /** When the user is not found in the local store, authenticate returns empty. */ + @Test + void testAuthenticateUserNotFound() { + headerMap.put(ClaimsCache.OAUTH2_CLAIM_email, List.of("unknown@example.com")); + claimsCache.loadCache(bearerToken, headerMap); + + doThrow(NotFoundException.class).when(userService).findUserByEmail(anyString()); + + Optional result = authenticator.authenticate(bearerToken); + + assertFalse(result.isPresent()); + } + + /** + * When the email claim is absent from the cached headers, buildAuthUserFromHeaders throws + * NotAuthorizedException, which propagates out of authenticate. + */ + @Test + void testAuthenticateMissingEmailThrows() { + headerMap.put(ClaimsCache.OAUTH2_CLAIM_access_token, List.of(bearerToken)); + // No email header — intentionally omitted + claimsCache.loadCache(bearerToken, headerMap); + + assertThrows(NotAuthorizedException.class, () -> authenticator.authenticate(bearerToken)); + } + + /** + * When Sam returns user status info, the resulting DuosUser carries that status info. + */ + @Test + void testAuthenticateSetsUserStatusInfo() throws Exception { + headerMap.put(ClaimsCache.OAUTH2_CLAIM_access_token, List.of(bearerToken)); + headerMap.put(ClaimsCache.OAUTH2_CLAIM_email, List.of("status@example.com")); + claimsCache.loadCache(bearerToken, headerMap); + + UserStatusInfo statusInfo = + new UserStatusInfo().setUserEmail("status@example.com").setUserSubjectId("sub-001"); + when(samService.getCombinedUserStatusInfo(any())).thenReturn(statusInfo); + + User user = new User(); + user.setEmail("status@example.com"); + when(userService.findUserByEmail("status@example.com")).thenReturn(user); + + Optional result = authenticator.authenticate(bearerToken); + + assertTrue(result.isPresent()); + assertNotNull(result.get().getUserStatusInfo()); + verify(samService).getCombinedUserStatusInfo(any()); + } + + /** + * When only the required email header is cached (no token or name), authenticate still + * succeeds and returns a DuosUser. + */ + @Test + void testAuthenticateWithMinimalHeaders() { + headerMap.put(ClaimsCache.OAUTH2_CLAIM_email, List.of("minimal@example.com")); + claimsCache.loadCache(bearerToken, headerMap); + + User user = new User(); + user.setEmail("minimal@example.com"); + when(userService.findUserByEmail("minimal@example.com")).thenReturn(user); + + Optional result = authenticator.authenticate(bearerToken); + + assertTrue(result.isPresent()); + } +} + From 4d9997497e553c36aa7628895b788e3e59f576d0 Mon Sep 17 00:00:00 2001 From: Gregory Rushton Date: Mon, 20 Jul 2026 13:08:56 -0400 Subject: [PATCH 9/9] chore: spotless --- .../http/authentication/DuosUserAuthenticatorTest.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/test/java/org/broadinstitute/consent/http/authentication/DuosUserAuthenticatorTest.java b/src/test/java/org/broadinstitute/consent/http/authentication/DuosUserAuthenticatorTest.java index 4dc9a3639c..9305593da0 100644 --- a/src/test/java/org/broadinstitute/consent/http/authentication/DuosUserAuthenticatorTest.java +++ b/src/test/java/org/broadinstitute/consent/http/authentication/DuosUserAuthenticatorTest.java @@ -100,9 +100,7 @@ void testAuthenticateMissingEmailThrows() { assertThrows(NotAuthorizedException.class, () -> authenticator.authenticate(bearerToken)); } - /** - * When Sam returns user status info, the resulting DuosUser carries that status info. - */ + /** When Sam returns user status info, the resulting DuosUser carries that status info. */ @Test void testAuthenticateSetsUserStatusInfo() throws Exception { headerMap.put(ClaimsCache.OAUTH2_CLAIM_access_token, List.of(bearerToken)); @@ -125,8 +123,8 @@ void testAuthenticateSetsUserStatusInfo() throws Exception { } /** - * When only the required email header is cached (no token or name), authenticate still - * succeeds and returns a DuosUser. + * When only the required email header is cached (no token or name), authenticate still succeeds + * and returns a DuosUser. */ @Test void testAuthenticateWithMinimalHeaders() { @@ -142,4 +140,3 @@ void testAuthenticateWithMinimalHeaders() { assertTrue(result.isPresent()); } } -