From 1bbd98795816c8585b760cc9e3e3fc46dae177a9 Mon Sep 17 00:00:00 2001 From: gitCarrot Date: Tue, 18 Jun 2024 10:51:55 -1000 Subject: [PATCH] Refactoring the logic related to the button to update active user profiles in ootb Implement loadAvailableProfiles in general.controller.js and getAvailableOotbActiveProfiles in groupingsService to call api in ui and store the available data in .availableProfiles Add ootb.active.user.profiles.json that contains multiple profiles information Apply ng-repeat with the values from scope.availableProfiles that contains the profiles from api call Add isOotb() function to check current spring boot active profile and apply to the menubar.html Add tests for loadAvailableProfiles and getAvailableOotbActiveProfiles in general.controller.test.js and groupings.service.test.js Enhance the Builder class functions in the User class (access folder) Refactor the file inputstream function in OotbActiveUserProfileService Implement getAvailableProfiles function test in the controller test, add @Mockbean OotbActiveUserProfileService and mock the map that contains the ootb active profiles Complete adding multiple ootb active profiles into the users map dynamically from json file with null safe and wrong path of file error Fix cadacy code style Fix general controller test to check gs.getAvailableOotbActiveProfiles Modify the functions to initiate default active user by mapping JSON data to OotbActiveProfile with JsonUtil.asList() function Modify the end-point to get available profiles from OotbActiveUserProfileService Redesign the specification of JSON data for mapping to OotbActiveProfile Change the strategy to set property of Json file and the way to inject the file in the service layer Modify the tests for controller and service with dynamic active profile from JSON data Modify raw type of exception --- .../api/controller/OotbRestController.java | 10 ++- .../edu/hawaii/its/groupings/access/User.java | 23 +++++- .../configuration/OotbSecurityConfig.java | 16 +++- .../its/groupings/configuration/Realm.java | 2 + .../service/OotbActiveUserProfileService.java | 76 ++++++++++++------- .../its/groupings/type/OotbActiveProfile.java | 43 +++++++++++ .../hawaii/its/groupings/util/JsonUtil.java | 28 +++++++ .../resources/application-ootb.properties | 4 +- .../resources/ootb.active.user.profiles.json | 32 ++++++++ .../resources/ootb.active.user.profiles2.json | 32 ++++++++ .../javascript/mainApp/general.controller.js | 15 ++++ .../javascript/mainApp/groupings.service.js | 8 ++ src/main/resources/templates/menubar.html | 9 +-- .../controller/OotbRestControllerTest.java | 65 +++++++++++++--- .../OotbActiveUserProfileServiceTest.java | 36 ++------- .../javascript/general.controller.test.js | 34 +++++++++ src/test/javascript/groupings.service.test.js | 14 ++++ 17 files changed, 359 insertions(+), 88 deletions(-) create mode 100644 src/main/java/edu/hawaii/its/groupings/type/OotbActiveProfile.java create mode 100644 src/main/resources/ootb.active.user.profiles.json create mode 100644 src/main/resources/ootb.active.user.profiles2.json diff --git a/src/main/java/edu/hawaii/its/api/controller/OotbRestController.java b/src/main/java/edu/hawaii/its/api/controller/OotbRestController.java index 1b2b0429d..d2eebdb49 100644 --- a/src/main/java/edu/hawaii/its/api/controller/OotbRestController.java +++ b/src/main/java/edu/hawaii/its/api/controller/OotbRestController.java @@ -13,12 +13,10 @@ import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.security.core.GrantedAuthority; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; @@ -27,7 +25,6 @@ import edu.hawaii.its.groupings.access.UserContextService; import edu.hawaii.its.groupings.configuration.OotbStaticUserAuthenticationFilter; import edu.hawaii.its.groupings.service.OotbActiveUserProfileService; -import edu.hawaii.its.groupings.util.JsonUtil; @RestController @RequestMapping("/api/groupings/ootb") @@ -60,6 +57,11 @@ public OotbRestController() { * the overrides file. Gets the active profiles and only runs the tests the * active profile relies on the API. */ + @GetMapping("/availableProfiles") + public ResponseEntity> getAvailableProfiles() { + List profiles = ootbActiveUserProfileService.getAvailableProfiles(); + return ResponseEntity.ok(profiles); + } @PostMapping(value = "/{activeProfile}") public ResponseEntity updateActiveDefaultUser(@PathVariable String activeProfile) { diff --git a/src/main/java/edu/hawaii/its/groupings/access/User.java b/src/main/java/edu/hawaii/its/groupings/access/User.java index 9a2be9377..5b2761ee3 100755 --- a/src/main/java/edu/hawaii/its/groupings/access/User.java +++ b/src/main/java/edu/hawaii/its/groupings/access/User.java @@ -1,9 +1,12 @@ package edu.hawaii.its.groupings.access; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; @@ -13,6 +16,10 @@ public class User extends org.springframework.security.core.userdetails.User { private String uhUuid; private UhAttributes attributes; + public User(){ + super("", "", null); + } + public User(String uid, String uhUuid, Collection authorities) { super(uid, "", authorities); setUhUuid(uhUuid); @@ -22,7 +29,7 @@ public User(String uid, Collection authorities) { super(uid, "", authorities); } - private User(Builder builder) { + public User(Builder builder) { super(builder.uid, "", builder.authorities); this.uhUuid = builder.uhUuid; this.attributes = new UhAttributes(builder.attributes); @@ -74,7 +81,7 @@ public String toString() { public static class Builder { private final String uid; private String uhUuid; - private Collection authorities; + private final Collection authorities = new ArrayList<>(); private final Map attributes = new HashMap<>(); public Builder(String uid) { @@ -86,8 +93,16 @@ public Builder uhUuid(String uhUuid) { return this; } - public Builder authorities(Collection authorities) { - this.authorities = authorities; + public Builder addAuthorities(String authority) { + this.authorities.add(new SimpleGrantedAuthority(authority)); + return this; + } + + public Builder addAuthorities(List authorities) { + List grantedAuthorities = authorities.stream() + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + this.authorities.addAll(grantedAuthorities); return this; } diff --git a/src/main/java/edu/hawaii/its/groupings/configuration/OotbSecurityConfig.java b/src/main/java/edu/hawaii/its/groupings/configuration/OotbSecurityConfig.java index 4e18710fe..86aa3d840 100644 --- a/src/main/java/edu/hawaii/its/groupings/configuration/OotbSecurityConfig.java +++ b/src/main/java/edu/hawaii/its/groupings/configuration/OotbSecurityConfig.java @@ -34,10 +34,11 @@ public class OotbSecurityConfig { private static final Log logger = LogFactory.getLog(OotbSecurityConfig.class); - - @Value("${ootb.active.user.profile}") private String userProfile; + @Value("${ootb.profiles.filename}") + private String profilesFileName; + @Value("${url.base}") private String appUrlBase; @@ -108,6 +109,15 @@ public OotbStaticUserAuthenticationFilter ootbStaticUserAuthenticationFilter() { @Bean public UserDetailsService userDetailsService() { - return new OotbActiveUserProfileService(); + // Make Profile Service with JSON file that user sets in the properties file + OotbActiveUserProfileService ootbActiveUserProfileService = new OotbActiveUserProfileService(profilesFileName); + + // Set the default profile to admin + setUserProfile(ootbActiveUserProfileService.findGivenNameForAdminRole()); + return ootbActiveUserProfileService; + } + + public void setUserProfile(String userProfile) { + this.userProfile = userProfile; } } diff --git a/src/main/java/edu/hawaii/its/groupings/configuration/Realm.java b/src/main/java/edu/hawaii/its/groupings/configuration/Realm.java index 08e01c80c..53154726c 100644 --- a/src/main/java/edu/hawaii/its/groupings/configuration/Realm.java +++ b/src/main/java/edu/hawaii/its/groupings/configuration/Realm.java @@ -65,4 +65,6 @@ public boolean isDefault() { return isProfileActive("default"); } + public boolean isOotb() { return isProfileActive("ootb"); } + } diff --git a/src/main/java/edu/hawaii/its/groupings/service/OotbActiveUserProfileService.java b/src/main/java/edu/hawaii/its/groupings/service/OotbActiveUserProfileService.java index 56beea1a0..8ecdd7b59 100644 --- a/src/main/java/edu/hawaii/its/groupings/service/OotbActiveUserProfileService.java +++ b/src/main/java/edu/hawaii/its/groupings/service/OotbActiveUserProfileService.java @@ -1,51 +1,65 @@ package edu.hawaii.its.groupings.service; -import java.util.HashMap; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; +import java.util.Optional; -import org.springframework.security.core.authority.AuthorityUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; +import edu.hawaii.its.groupings.access.Role; import edu.hawaii.its.groupings.access.User; +import edu.hawaii.its.groupings.type.OotbActiveProfile; +import edu.hawaii.its.groupings.util.JsonUtil; @Service public class OotbActiveUserProfileService implements UserDetailsService { - private final Map users = new HashMap<>(); + private static final Log logger = LogFactory.getLog(OotbActiveUserProfileService.class); + private final Map users = new LinkedHashMap<>(); + + // Default JSON file for active profiles + private String profilesFileName = "ootb.active.user.profiles.json"; public OotbActiveUserProfileService() { initUsers(); } + public OotbActiveUserProfileService(String profilesFileName) { + this.profilesFileName = profilesFileName; + initUsers(); + } + private void initUsers() { - // Initialize member with uid "member0123" - users.put("MEMBER", new User.Builder("member0123") // UID is clearly the first parameter in the constructor - .uhUuid("11111111") - .authorities(AuthorityUtils.createAuthorityList("ROLE_UH", "ROLE_OOTB")) - .addAttribute("cn", "MEMBER") - .addAttribute("mail", "member@hawaii.edu") - .addAttribute("givenName", "DefaultMember") - .build()); - - // Initialize owner with uid "owner0123" - users.put("OWNER", new User.Builder("owner0123") - .uhUuid("22222222") - .authorities(AuthorityUtils.createAuthorityList("ROLE_UH", "ROLE_OWNER", "ROLE_OOTB")) - .addAttribute("cn", "OWNER") - .addAttribute("mail", "owner@hawaii.edu") - .addAttribute("givenName", "OwnerUser") - .build()); - - // Initialize admin with uid "admin0123" - users.put("ADMIN", new User.Builder("admin0123") - .uhUuid("33333333") - .authorities(AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_UH", "ROLE_OWNER", "ROLE_OOTB")) - .addAttribute("cn", "ADMIN") - .addAttribute("mail", "admin@hawaii.edu") - .addAttribute("givenName", "AdminUser") - .build()); + List ootbActiveProfiles = + JsonUtil.asList(JsonUtil.readJsonFileToString(profilesFileName), OotbActiveProfile.class); + ootbActiveProfiles.forEach(profile -> { + users.put(profile.getAttributes().get("givenName"), createUserFromProfile(profile)); + }); + } + + private User createUserFromProfile(OotbActiveProfile profile) { + User.Builder builder = new User.Builder(profile.getUid()) + .uhUuid(profile.getUhUuid()) + .addAuthorities(profile.getAuthorities()); + + profile.getAttributes().forEach(builder::addAttribute); + + return builder.build(); + } + + public String findGivenNameForAdminRole() { + Optional givenName = users.values().stream() + .filter(user -> user.hasRole(Role.ADMIN)) + .map(User::getGivenName) + .findFirst(); + + return givenName.orElse(null); } @Override @@ -56,6 +70,10 @@ public UserDetails loadUserByUsername(String userProfile) throws UsernameNotFoun return users.get(userProfile); } + public List getAvailableProfiles() { + return new ArrayList<>(getUsers().keySet()); + } + public Map getUsers() { return users; } diff --git a/src/main/java/edu/hawaii/its/groupings/type/OotbActiveProfile.java b/src/main/java/edu/hawaii/its/groupings/type/OotbActiveProfile.java new file mode 100644 index 000000000..813254233 --- /dev/null +++ b/src/main/java/edu/hawaii/its/groupings/type/OotbActiveProfile.java @@ -0,0 +1,43 @@ +package edu.hawaii.its.groupings.type; + +import java.util.List; +import java.util.Map; + +public class OotbActiveProfile { + private String uid; + private String uhUuid; + private List authorities; + private Map attributes; + + public String getUid() { + return uid; + } + + public void setUid(String uid) { + this.uid = uid; + } + + public String getUhUuid() { + return uhUuid; + } + + public void setUhUuid(String uhUuid) { + this.uhUuid = uhUuid; + } + + public List getAuthorities() { + return authorities; + } + + public void setAuthorities(List authorities) { + this.authorities = authorities; + } + + public Map getAttributes() { + return attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes; + } +} diff --git a/src/main/java/edu/hawaii/its/groupings/util/JsonUtil.java b/src/main/java/edu/hawaii/its/groupings/util/JsonUtil.java index 81b34a575..704fcd1d3 100644 --- a/src/main/java/edu/hawaii/its/groupings/util/JsonUtil.java +++ b/src/main/java/edu/hawaii/its/groupings/util/JsonUtil.java @@ -1,7 +1,12 @@ package edu.hawaii.its.groupings.util; +import java.nio.file.Files; +import java.util.List; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; import com.fasterxml.jackson.databind.ObjectMapper; @@ -35,6 +40,28 @@ public static T asObject(final String json, Class type) { return result; } + public static List asList(final String json, Class type) { + List result = null; + try { + ObjectMapper mapper = new ObjectMapper(); + result = mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, type)); + } catch (Exception e) { + logger.error("Error: " + e); + } + return result; + } + + public static String readJsonFileToString(String filePath) { + String result = null; + try { + Resource resource = new ClassPathResource(filePath); + result = Files.readString(resource.getFile().toPath()); + } catch (Exception e) { + logger.error("Error: " + e); + } + return result; + } + public static void printJson(Object obj) { ObjectMapper objectMapper = new ObjectMapper(); try { @@ -44,6 +71,7 @@ public static void printJson(Object obj) { logger.error("Error: " + e); } } + public static void prettyPrint(Object object) { try { String json = new ObjectMapper() diff --git a/src/main/resources/application-ootb.properties b/src/main/resources/application-ootb.properties index 104e8db53..21bd2df85 100644 --- a/src/main/resources/application-ootb.properties +++ b/src/main/resources/application-ootb.properties @@ -7,8 +7,8 @@ app.api.handshake.enabled=false # There are two options: GROUPER, OOTB : "GROUPER" is a real grouper api service while "OOTB" is a ootb grouper api service. grouping.api.server.type=OOTB -# User Type : USER, OWNER, ADMIN -ootb.active.user.profile=ADMIN +# Profiles file +ootb.profiles.filename=ootb.active.user.profiles.json # ========================================================================= app.environment=ootb diff --git a/src/main/resources/ootb.active.user.profiles.json b/src/main/resources/ootb.active.user.profiles.json new file mode 100644 index 000000000..81c631e61 --- /dev/null +++ b/src/main/resources/ootb.active.user.profiles.json @@ -0,0 +1,32 @@ +[ + { + "uid": "member0123", + "uhUuid": "11111111", + "authorities": ["ROLE_UH"], + "attributes": { + "cn": "MEMBER", + "mail": "member@hawaii.edu", + "givenName": "DefaultMember" + } + }, + { + "uid": "owner0123", + "uhUuid": "22222222", + "authorities": ["ROLE_UH", "ROLE_OWNER"], + "attributes": { + "cn": "OWNER", + "mail": "owner@hawaii.edu", + "givenName": "OwnerUser" + } + }, + { + "uid": "admin0123", + "uhUuid": "33333333", + "authorities": ["ROLE_ADMIN", "ROLE_UH", "ROLE_OWNER"], + "attributes": { + "cn": "ADMIN", + "mail": "admin@hawaii.edu", + "givenName": "AdminUser" + } + } +] \ No newline at end of file diff --git a/src/main/resources/ootb.active.user.profiles2.json b/src/main/resources/ootb.active.user.profiles2.json new file mode 100644 index 000000000..4b10317c2 --- /dev/null +++ b/src/main/resources/ootb.active.user.profiles2.json @@ -0,0 +1,32 @@ +{ + "JAMES": { + "uid": "james0123", + "uhUuid": "11111111", + "authorities": ["ROLE_UH"], + "attributes": { + "cn": "MEMBER", + "mail": "member@hawaii.edu", + "givenName": "UH James" + } + }, + "EDDY": { + "uid": "eddy0123", + "uhUuid": "22222222", + "authorities": ["ROLE_UH", "ROLE_OWNER"], + "attributes": { + "cn": "OWNER", + "mail": "owner@hawaii.edu", + "givenName": "Eddy Jeon" + } + }, + "JSON": { + "uid": "json0123", + "uhUuid": "33333333", + "authorities": ["ROLE_ADMIN", "ROLE_UH", "ROLE_OWNER"], + "attributes": { + "cn": "ADMIN", + "mail": "json@hawaii.edu", + "givenName": "UH Json" + } + } +} diff --git a/src/main/resources/static/javascript/mainApp/general.controller.js b/src/main/resources/static/javascript/mainApp/general.controller.js index 728aab0ea..031c49fb0 100755 --- a/src/main/resources/static/javascript/mainApp/general.controller.js +++ b/src/main/resources/static/javascript/mainApp/general.controller.js @@ -28,6 +28,7 @@ $scope.showGroupingPathColumn = JSON.parse(localStorage.getItem("showPathColumn") ?? false); $scope.ootbActiveUser = ""; + $scope.availableProfiles = []; angular.extend(this, $controller("TableJsController", { $scope })); @@ -268,6 +269,20 @@ $("[data-content='copy']").popover(); }; + /** + * Get available ootb active profiles that defined in ootb.active.user.profiles.json + */ + $scope.loadAvailableProfiles = () => { + groupingsService.getAvailableOotbActiveProfiles( + (data) => { + $scope.availableProfiles = data; + }, + (res) => { + $scope.resStatus = res.status; + } + ); + }; + /** * Updates the active user profile, clears cache by reloading the page with a cache-busting URL. * @param profile - the type of profile to switch to ('MEMBER', 'OWNER', 'ADMIN') diff --git a/src/main/resources/static/javascript/mainApp/groupings.service.js b/src/main/resources/static/javascript/mainApp/groupings.service.js index f7f9847f2..fe10a4320 100644 --- a/src/main/resources/static/javascript/mainApp/groupings.service.js +++ b/src/main/resources/static/javascript/mainApp/groupings.service.js @@ -119,6 +119,14 @@ dataProvider.loadData(endpoint, onSuccess, onError); }, + /** + * Get a list of available ootb active profiles. + */ + getAvailableOotbActiveProfiles(onSuccess, onError) { + let endpoint = BASE_URL + "ootb/availableProfiles"; + dataProvider.loadData(endpoint, onSuccess, onError); + }, + /** * Update data harness bean with OotbActiveProfile * @param profile {String} diff --git a/src/main/resources/templates/menubar.html b/src/main/resources/templates/menubar.html index 429625d35..dd9c2ab0c 100755 --- a/src/main/resources/templates/menubar.html +++ b/src/main/resources/templates/menubar.html @@ -50,7 +50,7 @@ - - diff --git a/src/test/java/edu/hawaii/its/api/controller/OotbRestControllerTest.java b/src/test/java/edu/hawaii/its/api/controller/OotbRestControllerTest.java index ecfbd6545..eafb5e9b2 100644 --- a/src/test/java/edu/hawaii/its/api/controller/OotbRestControllerTest.java +++ b/src/test/java/edu/hawaii/its/api/controller/OotbRestControllerTest.java @@ -6,41 +6,52 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.times; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentMatchers; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; import org.springframework.web.context.WebApplicationContext; +import com.nimbusds.jose.shaded.gson.JsonIOException; + import edu.hawaii.its.api.service.HttpRequestService; +import edu.hawaii.its.groupings.access.User; import edu.hawaii.its.groupings.configuration.SpringBootWebApplication; +import edu.hawaii.its.groupings.service.OotbActiveUserProfileService; @ActiveProfiles("ootb") @SpringBootTest(classes = { SpringBootWebApplication.class }) public class OotbRestControllerTest { private static final String REST_CONTROLLER_BASE = "/api/groupings/ootb"; - private static final String ADMIN_UID = "admin0123"; + private static final String ADMIN_GIVEN_NAME = "AdminUser"; - @Autowired - GroupingsRestController groupingsRestController; + @MockBean + OotbRestController ootbRestController; @MockBean private HttpRequestService httpRequestService; @@ -48,6 +59,9 @@ public class OotbRestControllerTest { @Autowired private WebApplicationContext context; + @MockBean + private OotbActiveUserProfileService ootbActiveUserProfileService; + private MockMvc mockMvc; @BeforeEach @@ -58,19 +72,48 @@ public void setUp() { when(httpRequestService.makeApiRequestWithBody(anyString(), anyString(), anyList(), any(HttpMethod.class))) .thenReturn(new ResponseEntity(HttpStatus.OK)); + when(ootbActiveUserProfileService.findGivenNameForAdminRole()).thenReturn(ADMIN_GIVEN_NAME); + } + + @Test + public void testGetAvailableProfiles() throws Exception { + String uri = REST_CONTROLLER_BASE + "/availableProfiles"; + List expectedProfiles = ootbActiveUserProfileService.getAvailableProfiles(); + Map orderedUsers = new LinkedHashMap<>(); + expectedProfiles.forEach(profile -> orderedUsers.put(profile, mock(User.class))); + + when(ootbActiveUserProfileService.getUsers()).thenReturn(orderedUsers); + + ResultActions resultActions = mockMvc.perform(get(uri).contentType(MediaType.APPLICATION_JSON)); + + IntStream.range(0, expectedProfiles.size()).forEach(index -> { + try { + resultActions.andExpect(jsonPath("$[" + index + "]").value(expectedProfiles.get(index))); + } catch (Exception e) { + throw new JsonIOException(e); + } + }); + + verify(ootbRestController).getAvailableProfiles(); } @Test public void updateActiveProfileTest() throws Exception { - String uri = REST_CONTROLLER_BASE + "/ADMIN"; - given(httpRequestService.makeApiRequestWithBody(eq(ADMIN_UID), anyString(), anyList(), eq(HttpMethod.POST))) - .willReturn(new ResponseEntity(HttpStatus.OK)); + Map orderedUsers = new LinkedHashMap<>(); + String adminGivenName = ootbActiveUserProfileService.findGivenNameForAdminRole(); + orderedUsers.put(adminGivenName, mock(User.class)); + + String uri = REST_CONTROLLER_BASE + "/" + adminGivenName; + + when(ootbActiveUserProfileService.getUsers()).thenReturn(orderedUsers); + given(httpRequestService.makeApiRequestWithBody(eq(ADMIN_GIVEN_NAME), anyString(), anyList(), + eq(HttpMethod.POST))) + .willReturn(new ResponseEntity<>(HttpStatus.OK)); assertNotNull(mockMvc.perform(post(uri).with(csrf())) .andExpect(status().isOk()) .andReturn()); - verify(httpRequestService, times(1)) - .makeApiRequestWithBody(eq(ADMIN_UID), anyString(), anyList(), eq(HttpMethod.POST)); + verify(ootbRestController).updateActiveDefaultUser(ADMIN_GIVEN_NAME); } } diff --git a/src/test/java/edu/hawaii/its/groupings/service/OotbActiveUserProfileServiceTest.java b/src/test/java/edu/hawaii/its/groupings/service/OotbActiveUserProfileServiceTest.java index 3b53d76c4..b3053a940 100644 --- a/src/test/java/edu/hawaii/its/groupings/service/OotbActiveUserProfileServiceTest.java +++ b/src/test/java/edu/hawaii/its/groupings/service/OotbActiveUserProfileServiceTest.java @@ -18,54 +18,30 @@ @ActiveProfiles("ootb") class OotbActiveUserProfileServiceTest { - private OotbActiveUserProfileService manager; + private OotbActiveUserProfileService ootbActiveUserProfileService; @BeforeEach public void setUp() { - manager = new OotbActiveUserProfileService(); - } - - @Test - public void testUserUserDetails() { - UserDetails userDetails = manager.loadUserByUsername("MEMBER"); - assertNotNull(userDetails, "UserDetails should not be null"); - - User user = manager.getUsers().get("MEMBER"); - assertNotNull(user, "Member should not be null"); - assertEquals("member0123", user.getUid(), "Username should match"); - assertEquals("11111111", user.getUhUuid(), "UhUuid should match"); - assertEquals(2, user.getAuthorities().size(), "Should have 1 authority"); - } - - @Test - public void testOwnerUserDetails() { - UserDetails userDetails = manager.loadUserByUsername("OWNER"); - assertNotNull(userDetails, "UserDetails should not be null"); - - User user = manager.getUsers().get("OWNER"); - assertNotNull(user, "User should not be null"); - assertEquals("owner0123", user.getUid(), "Username should match"); - assertEquals("22222222", user.getUhUuid(), "UhUuid should match"); - assertEquals(3, user.getAuthorities().size(), "Should have 2 authorities"); + ootbActiveUserProfileService = new OotbActiveUserProfileService("ootb.active.user.profiles.json"); } @Test public void testAdminUserDetails() { - UserDetails userDetails = manager.loadUserByUsername("ADMIN"); + User user = ootbActiveUserProfileService.getUsers().get(ootbActiveUserProfileService.findGivenNameForAdminRole()); + UserDetails userDetails = ootbActiveUserProfileService.loadUserByUsername(user.getGivenName()); assertNotNull(userDetails, "UserDetails should not be null"); - User user = manager.getUsers().get("ADMIN"); assertNotNull(user, "User should not be null"); assertEquals("admin0123", user.getUid(), "Username should match"); assertEquals("33333333", user.getUhUuid(), "UhUuid should match"); - assertEquals(4, user.getAuthorities().size(), "Should have 3 authorities"); + assertEquals(3, user.getAuthorities().size(), "Should have 3 authorities"); } @Test public void testLoadUserWithNonExistentUser() { // Test for non-existent user profile assertThrows(UsernameNotFoundException.class, () -> { - manager.loadUserByUsername("NON_EXISTENT"); + ootbActiveUserProfileService.loadUserByUsername("NON_EXISTENT"); }, "Expected UsernameNotFoundException for non-existent user profile"); } } \ No newline at end of file diff --git a/src/test/javascript/general.controller.test.js b/src/test/javascript/general.controller.test.js index 498fddcbb..78288740b 100755 --- a/src/test/javascript/general.controller.test.js +++ b/src/test/javascript/general.controller.test.js @@ -506,4 +506,38 @@ describe("GeneralController", () => { }); }); + describe('$scope.loadAvailableProfiles', () => { + let successResponse = [ "ADMIN", "OWNER", "MEMBER" ]; + let errorResponse = { status: 404 }; + beforeEach(() => { + spyOn(gs, "getAvailableOotbActiveProfiles").and.callFake((onSuccess, onError) => { + onSuccess(successResponse); + onError(errorResponse); + }); + httpBackend.whenGET("currentUser").passThrough(); + }); + + it('should load available profiles successfully', () => { + const expectedProfiles = [ "ADMIN", "OWNER", "MEMBER" ]; + httpBackend.expectGET(BASE_URL + 'ootb/availableProfiles').respond(200, expectedProfiles); + + spyOn(console, 'error'); + scope.loadAvailableProfiles(); + + expect(scope.availableProfiles).toEqual(expectedProfiles); + expect(gs.getAvailableOotbActiveProfiles).toHaveBeenCalledWith(jasmine.any(Function), jasmine.any(Function)); + }); + + it('should handle errors when loading available profiles fails', () => { + const errorResponse = { status: 404, message: 'Not found' }; + httpBackend.expectGET(BASE_URL + 'ootb/availableProfiles').respond(404, errorResponse); + + spyOn(console, 'error'); + scope.loadAvailableProfiles(); + + expect(scope.resStatus).toBe(errorResponse.status); + }); + }); + + }); diff --git a/src/test/javascript/groupings.service.test.js b/src/test/javascript/groupings.service.test.js index 38afd2130..15cbefbaa 100644 --- a/src/test/javascript/groupings.service.test.js +++ b/src/test/javascript/groupings.service.test.js @@ -231,6 +231,20 @@ describe("GroupingsService", () => { }); }); + describe("getAvailableOotbActiveProfiles", () => { + it("should call dataProvider.loadData", () => { + spyOn(dp, "loadData"); + gs.getAvailableOotbActiveProfiles(onSuccess, onError); + expect(dp.loadData).toHaveBeenCalled(); + }); + + it("should use the correct path", () => { + gs.getAvailableOotbActiveProfiles(onSuccess, onError); + httpBackend.expectGET(BASE_URL + "ootb/availableProfiles").respond(200); + expect(httpBackend.flush).not.toThrow(); + }); + }); + describe("updateOotbActiveProfile", () => { let profile = "testProfile"; // Example profile for testing