Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Diakonie 224 create agency admin #10

Merged
merged 3 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,20 @@ List<UserRole> getDefaultRoles(Admin.AdminType adminType) {

private void setTenantId(CreateAdminDTO createAdminDTO) {
if (multiTenancyEnabled) {
if (authenticatedUser.isTenantSuperAdmin()) {
notNull(createAdminDTO.getTenantId());
} else {
createAdminDTO.setTenantId(TenantContext.getCurrentTenant().intValue());
}
setTenantIdForMultiTenancy(createAdminDTO);
} else {
createAdminDTO.setTenantId(null);
}
}

private void setTenantIdForMultiTenancy(CreateAdminDTO createAdminDTO) {
if (authenticatedUser.isTenantSuperAdmin()) {
notNull(createAdminDTO.getTenantId());
} else {
createAdminDTO.setTenantId(TenantContext.getCurrentTenant().intValue());
}
}

private ArrayList<UserRole> getUserRolesForTenantAdmin() {
if (multitenancyWithSingleDomain) {
return Lists.newArrayList(
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/application-testing.properties
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,5 @@ appointments.delete-job-enabled=true

feature.topics.enabled=false
agency.service.api.url=${app.base.url}/service

multitenancy.enabled=false
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,6 @@ private String givenNewConsultantIsCreated() throws Exception {
// given
CreateConsultantDTO createAdminDTO = new EasyRandom().nextObject(CreateConsultantDTO.class);
createAdminDTO.setEmail("[email protected]");

// when
MvcResult mvcResult =
this.mockMvc
Expand Down Expand Up @@ -219,6 +218,7 @@ private String givenNewAgencyAdminIsCreated() throws Exception {
// given
CreateAdminDTO createAdminDTO = new EasyRandom().nextObject(CreateAdminDTO.class);
createAdminDTO.setEmail("[email protected]");
createAdminDTO.setTenantId(95);

// when

Expand All @@ -235,6 +235,7 @@ private String givenNewAgencyAdminIsCreated() throws Exception {
.andExpect(jsonPath("_embedded.username", notNullValue()))
.andExpect(jsonPath("_embedded.lastname", notNullValue()))
.andExpect(jsonPath("_embedded.email", is("[email protected]")))
.andExpect(jsonPath("_embedded.tenantId", is("null")))
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
return JsonPath.read(content, "_embedded.id");
Expand Down

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just because I'm not sure, you need all the mocks and the stuff in the setUp-method?

Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package de.caritas.cob.userservice.api.adapters.web.controller;

import static de.caritas.cob.userservice.api.adapters.web.controller.UserAdminControllerIT.AGENCY_ADMIN_PATH;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.when;
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 com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
import de.caritas.cob.userservice.api.adapters.keycloak.dto.KeycloakCreateUserResponseDTO;
import de.caritas.cob.userservice.api.adapters.web.dto.CreateAdminDTO;
import de.caritas.cob.userservice.api.admin.service.tenant.TenantService;
import de.caritas.cob.userservice.api.config.apiclient.AgencyServiceApiControllerFactory;
import de.caritas.cob.userservice.api.config.auth.Authority.AuthorityValue;
import de.caritas.cob.userservice.api.config.auth.IdentityConfig;
import de.caritas.cob.userservice.api.helper.AuthenticatedUser;
import de.caritas.cob.userservice.api.port.out.IdentityClient;
import de.caritas.cob.userservice.api.tenant.TenantResolverService;
import de.caritas.cob.userservice.tenantservice.generated.web.model.RestrictedTenantDTO;
import javax.servlet.http.Cookie;
import org.jeasy.random.EasyRandom;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.transaction.annotation.Transactional;

@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("testing")
@AutoConfigureTestDatabase
@TestPropertySource(properties = {"multitenancy.enabled=true"})
@Transactional
class UserAdminControllerMultiTenancyTrueE2EIT {

private static final String CSRF_HEADER = "csrfHeader";
private static final String CSRF_VALUE = "test";
private static final Cookie CSRF_COOKIE = new Cookie("csrfCookie", CSRF_VALUE);
@Autowired private MockMvc mockMvc;

@Autowired private ObjectMapper objectMapper;

@Autowired private IdentityConfig identityConfig;

@MockBean AgencyServiceApiControllerFactory agencyServiceApiControllerFactory;

@MockBean IdentityClient identityClient;

@MockBean TenantService tenantService;

@MockBean TenantResolverService tenantResolverService;

@MockBean AuthenticatedUser authenticatedUser;

@AfterEach
void reset() {
identityConfig.setDisplayNameAllowedForConsultants(false);
}

@BeforeEach
public void setUp() {

KeycloakCreateUserResponseDTO keycloakResponse = new KeycloakCreateUserResponseDTO();
keycloakResponse.setUserId(new EasyRandom().nextObject(String.class));
when(identityClient.createKeycloakUser(Mockito.any(), Mockito.anyString(), Mockito.anyString()))
.thenReturn(keycloakResponse);
}

@Test
@WithMockUser(authorities = {AuthorityValue.USER_ADMIN})
void createNewAgencyAdmin_Should_returnOk_When_requiredCreateAgencyAdminIsGiven()
throws Exception {
// given
CreateAdminDTO createAdminDTO = new EasyRandom().nextObject(CreateAdminDTO.class);
createAdminDTO.setEmail("[email protected]");
createAdminDTO.setTenantId(95);
givenTenant();
givenTenantSuperAdmin();

// when

MvcResult mvcResult =
this.mockMvc
.perform(
post(AGENCY_ADMIN_PATH)
.cookie(CSRF_COOKIE)
.header(CSRF_HEADER, CSRF_VALUE)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(createAdminDTO)))
.andExpect(status().isOk())
.andExpect(jsonPath("_embedded.id", notNullValue()))
.andExpect(jsonPath("_embedded.username", notNullValue()))
.andExpect(jsonPath("_embedded.lastname", notNullValue()))
.andExpect(jsonPath("_embedded.email", is("[email protected]")))
.andExpect(jsonPath("_embedded.tenantId", is("95")))
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
JsonPath.read(content, "_embedded.id");
}

@Test
@WithMockUser(authorities = {AuthorityValue.USER_ADMIN})
void createNewAgencyAdmin_Should_return500_When_superAdminHasNullTenantID() throws Exception {
// given
CreateAdminDTO createAdminDTO = new EasyRandom().nextObject(CreateAdminDTO.class);
createAdminDTO.setEmail("[email protected]");
createAdminDTO.setTenantId(null);
givenTenant();
givenTenantSuperAdmin();

// when

this.mockMvc
.perform(
post(AGENCY_ADMIN_PATH)
.cookie(CSRF_COOKIE)
.header(CSRF_HEADER, CSRF_VALUE)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(createAdminDTO)))
.andExpect(status().isInternalServerError())
.andReturn();
}

private void givenTenantSuperAdmin() {
when(authenticatedUser.isTenantSuperAdmin()).thenReturn(true);
}

private void givenTenant() {
when(tenantResolverService.resolve(any())).thenReturn(95L);
when(tenantService.getRestrictedTenantData(anyLong()))
.thenReturn(new RestrictedTenantDTO().subdomain("subdomain"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,39 @@ public void afterTests() {
assertThat(admin.getId()).isNotNull();
}

@Test
public void
createNewAdminAgency_Should_returnExpectedCreatedAdmin_When_userIsSuperAdminAndInputDataIsCorrectAndMultitenancyDisabled() {
// given
ReflectionTestUtils.setField(createAdminService, "multiTenancyEnabled", false);
TenantContext.setCurrentTenant(0L);
when(authenticatedUser.isTenantSuperAdmin()).thenReturn(true);
when(identityClient.createKeycloakUser(any(), anyString(), any()))
.thenReturn(easyRandom.nextObject(KeycloakCreateUserResponseDTO.class));
when(identityClient.createKeycloakUser(any(), anyString(), any()))
.thenReturn(easyRandom.nextObject(KeycloakCreateUserResponseDTO.class));
CreateAdminDTO createAdminDTO = this.easyRandom.nextObject(CreateAdminDTO.class);
createAdminDTO.setTenantId(1);
createAdminDTO.setUsername(VALID_USERNAME);
createAdminDTO.setEmail(VALID_EMAIL_ADDRESS);

// when
Admin admin = this.createAdminService.createNewAgencyAdmin(createAdminDTO);

// then
verify(identityClient)
.createKeycloakUser(userDTOArgumentCaptor.capture(), anyString(), anyString());
assertNull(userDTOArgumentCaptor.getValue().getTenantId());

verify(identityClient).updatePassword(anyString(), anyString());
verify(identityClient).updateRole(anyString(), eq(RESTRICTED_AGENCY_ADMIN));
verify(identityClient).updateRole(anyString(), eq(USER_ADMIN));

assertThat(admin).isNotNull();
assertThat(admin.getTenantId()).isNull();
assertThat(admin.getId()).isNotNull();
}

@Test
public void getUserRolesForTenantAdmin_ShouldGetProperDefaultRoles_ForSingleDomainMultitenancy() {
Whitebox.setInternalState(createAdminService, "multitenancyWithSingleDomain", true);
Expand Down
Loading