Skip to content

Commit

Permalink
Merge pull request #34 from virtualidentityag/staging
Browse files Browse the repository at this point in the history
Staging
  • Loading branch information
tkuzynow authored Sep 4, 2024
2 parents 663078d + c050331 commit c8f8db8
Show file tree
Hide file tree
Showing 11 changed files with 158 additions and 82 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ public class RocketChatService implements MessageClient {
"Could not get users list from Rocket.Chat";
private static final String USER_LIST_GET_FIELD_SELECTION = "{\"_id\":1}";
private static final Integer PAGE_SIZE = 100;
private static final String ERROR_ROOM_NOT_FOUND = "error-room-not-found";
private final LocalDateTime localDateTime1900 = LocalDateTime.of(1900, 1, 1, 0, 0);

private final LocalDateTime localDateTimeFuture = nowInUtc().plusYears(1L);
Expand Down Expand Up @@ -652,13 +653,7 @@ public void removeUserFromGroup(String rcUserId, String rcGroupId)

GroupResponseDTO response;
try {
RocketChatCredentials technicalUser = rcCredentialHelper.getTechnicalUser();
var header = getStandardHttpHeaders(technicalUser);
var body = new GroupRemoveUserBodyDTO(rcUserId, rcGroupId);
HttpEntity<GroupRemoveUserBodyDTO> request = new HttpEntity<>(body, header);

var url = rocketChatConfig.getApiUrl(ENDPOINT_GROUP_KICK);
response = restTemplate.postForObject(url, request, GroupResponseDTO.class);
response = tryRemoveUserFromGroup(rcUserId, rcGroupId);

} catch (Exception ex) {
log.error(
Expand All @@ -677,6 +672,19 @@ public void removeUserFromGroup(String rcUserId, String rcGroupId)
}
}

private GroupResponseDTO tryRemoveUserFromGroup(String rcUserId, String rcGroupId)
throws RocketChatUserNotInitializedException {
GroupResponseDTO response;
RocketChatCredentials technicalUser = rcCredentialHelper.getTechnicalUser();
var header = getStandardHttpHeaders(technicalUser);
var body = new GroupRemoveUserBodyDTO(rcUserId, rcGroupId);
HttpEntity<GroupRemoveUserBodyDTO> request = new HttpEntity<>(body, header);

var url = rocketChatConfig.getApiUrl(ENDPOINT_GROUP_KICK);
response = restTemplate.postForObject(url, request, GroupResponseDTO.class);
return response;
}

public boolean removeUserFromSession(String chatUserId, String chatId) {
try {
addTechnicalUserToGroup(chatId);
Expand Down Expand Up @@ -1340,4 +1348,31 @@ public boolean saveRoomSettings(String chatId, boolean encrypted) {
return false;
}
}

public void removeUserFromGroupIgnoreGroupNotFound(String rcUserId, String rcGroupId)
throws RocketChatRemoveUserFromGroupException {
{
GroupResponseDTO response;
try {
response = tryRemoveUserFromGroup(rcUserId, rcGroupId);
} catch (Exception ex) {
if (ex.getMessage().contains(ERROR_ROOM_NOT_FOUND)) {
return;
}
log.error(
"Rocket.Chat Error: Could not remove user {} from Rocket.Chat group with id {}. Reason: ",
rcUserId,
rcGroupId,
ex);
throw new RocketChatRemoveUserFromGroupException(
String.format(
"Could not remove user %s from Rocket.Chat group with id %s", rcUserId, rcGroupId));
}

if (response != null && !response.isSuccess()) {
var error = "Could not remove user %s from Rocket.Chat group with id %s";
throw new RocketChatRemoveUserFromGroupException(String.format(error, rcUserId, rcGroupId));
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import de.caritas.cob.userservice.api.port.out.IdentityClient;
import de.caritas.cob.userservice.api.service.LogService;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import lombok.NonNull;
Expand Down Expand Up @@ -54,16 +55,27 @@ String resolveTypeOfSession(Session session) {
}

void removeConsultantsFromSessionGroups(Session session, List<Consultant> consultants) {
removeConsultantsFromRocketChatGroup(session.getGroupId(), consultants);
removeConsultantsFromRocketChatGroup(session.getFeedbackGroupId(), consultants);
removeConsultantsFromRocketChatGroup(
session.getGroupId(), consultants, rocketChatFacade::removeUserFromGroup);
removeConsultantsFromRocketChatGroup(
session.getFeedbackGroupId(), consultants, rocketChatFacade::removeUserFromGroup);
}

void removeConsultantsFromSessionGroup(String rcGroupId, List<Consultant> consultants) {
removeConsultantsFromRocketChatGroup(rcGroupId, consultants);
removeConsultantsFromRocketChatGroup(
rcGroupId, consultants, rocketChatFacade::removeUserFromGroup);
}

private void removeConsultantsFromRocketChatGroup(
void removeConsultantsFromSessionGroupAndIgnoreGroupNotFound(
String rcGroupId, List<Consultant> consultants) {
removeConsultantsFromRocketChatGroup(
rcGroupId, consultants, rocketChatFacade::removeUserFromGroupIgnoreGroupNotFound);
}

private void removeConsultantsFromRocketChatGroup(
String rcGroupId,
List<Consultant> consultants,
BiConsumer<String, String> removeFromRocketchatGroupMethod) {
if (rcGroupId == null) {
return;
}
Expand All @@ -73,7 +85,7 @@ private void removeConsultantsFromRocketChatGroup(
consultants.stream()
.map(Consultant::getRocketChatId)
.filter(groupMemberList::contains)
.forEach(rcUserId -> rocketChatFacade.removeUserFromGroup(rcUserId, rcGroupId));
.forEach(rcUserId -> removeFromRocketchatGroupMethod.accept(rcUserId, rcGroupId));
rocketChatFacade.leaveFromGroupAsTechnicalUser(rcGroupId);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,11 @@ private void performGroupsRemove(Session session, List<Consultant> consultants)
}

/** Removes the given consultant from Rocket.Chat group of given session. */
public void removeFromGroup() {
public void removeFromGroupAndIgnoreGroupNotFound() {
this.consultantsToRemoveFromSessions.forEach(
((session, consultants) ->
removeConsultantsFromSessionGroup(session.getGroupId(), consultants)));
removeConsultantsFromSessionGroupAndIgnoreGroupNotFound(
session.getGroupId(), consultants)));
}

/**
Expand All @@ -104,7 +105,7 @@ public void removeFromFeedbackGroupOrRollbackOnFailure() {

private void performGroupRemove(Session session, List<Consultant> consultants) {
try {
removeConsultantsFromSessionGroup(session.getGroupId(), consultants);
removeConsultantsFromSessionGroupAndIgnoreGroupNotFound(session.getGroupId(), consultants);
} catch (Exception e) {
rollback();
throw new InternalServerErrorException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ protected void configure(HttpSecurity http) throws Exception {
.antMatchers("/userstatistics", "/userstatistics/**")
.permitAll()
.antMatchers(HttpMethod.DELETE, "/useradmin/consultants/{consultantId:[0-9]+}/delete")
.hasAuthority(USER_ADMIN)
.hasAnyAuthority(USER_ADMIN, RESTRICTED_AGENCY_ADMIN)
.antMatchers(HttpMethod.GET, "/actuator/health")
.permitAll()
.antMatchers(HttpMethod.GET, "/actuator/health/*")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,17 @@ public void removeUserFromGroup(String rcUserId, String groupId) {
}
}

public void removeUserFromGroupIgnoreGroupNotFound(String rcUserId, String groupId) {
try {
this.rocketChatService.removeUserFromGroupIgnoreGroupNotFound(rcUserId, groupId);
} catch (RocketChatRemoveUserFromGroupException e) {
var message =
String.format(
"Could not remove user with id %s from Rocket.Chat group id %s", rcUserId, groupId);
throw new InternalServerErrorException(message, LogService::logInternalServerError);
}
}

/**
* Get all standard members (all users except system user and technical user) of a rocket chat
* group.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ private void removeUnauthorizedMembers(
.onSessionConsultants(Map.of(session, consultantsToRemoveFromRocketChat));

if (rcGroupId.equalsIgnoreCase(session.getGroupId())) {
rocketChatRemoveFromGroupOperationService.removeFromGroup();
rocketChatRemoveFromGroupOperationService.removeFromGroupAndIgnoreGroupNotFound();
}
if (rcGroupId.equalsIgnoreCase(session.getFeedbackGroupId())) {
rocketChatRemoveFromGroupOperationService.removeFromFeedbackGroup();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
package de.caritas.cob.userservice.api.workflow.delete.service;

import static de.caritas.cob.userservice.api.helper.CustomLocalDateTime.nowInUtc;
import static de.caritas.cob.userservice.api.workflow.delete.model.DeletionSourceType.ASKER;
import static de.caritas.cob.userservice.api.workflow.delete.model.DeletionTargetType.ALL;
import static org.apache.commons.collections4.CollectionUtils.isNotEmpty;

import de.caritas.cob.userservice.api.model.Session;
Expand Down Expand Up @@ -86,14 +83,8 @@ private List<DeletionWorkflowError> performDeletionWorkflow(
user.ifPresentOrElse(
u -> workflowErrors.addAll(deleteInactiveGroupsOrUser(userInactiveGroupEntry, u)),
() ->
workflowErrors.add(
DeletionWorkflowError.builder()
.deletionSourceType(ASKER)
.deletionTargetType(ALL)
.identifier(userInactiveGroupEntry.getKey())
.reason(USER_NOT_FOUND_REASON)
.timestamp(nowInUtc())
.build()));
workflowErrors.addAll(
performUserSessionDeletionForNonExistingUser(userInactiveGroupEntry.getValue())));

return workflowErrors;
}
Expand All @@ -102,11 +93,14 @@ private List<DeletionWorkflowError> deleteInactiveGroupsOrUser(
Entry<String, List<String>> userInactiveGroupEntry, User user) {

List<Session> userSessionList = sessionRepository.findByUser(user);

if (allSessionsOfUserAreInactive(userInactiveGroupEntry, userSessionList)) {
return deleteUserAccountService.performUserDeletion(user);
}
return perfomUserSessionDeletion(userInactiveGroupEntry, userSessionList);
}

private List<DeletionWorkflowError> perfomUserSessionDeletion(
Entry<String, List<String>> userInactiveGroupEntry, List<Session> userSessionList) {
return userInactiveGroupEntry.getValue().stream()
.map(rcGroupId -> performSessionDeletion(rcGroupId, userSessionList))
.flatMap(Collection::stream)
Expand All @@ -120,28 +114,34 @@ private boolean allSessionsOfUserAreInactive(

private List<DeletionWorkflowError> performSessionDeletion(
String rcGroupId, List<Session> userSessionList) {

List<DeletionWorkflowError> workflowErrors = new ArrayList<>();

Optional<Session> session = findSessionInUserSessionList(rcGroupId, userSessionList);
session.ifPresent(s -> workflowErrors.addAll(deleteSessionService.performSessionDeletion(s)));
return workflowErrors;
}

session.ifPresentOrElse(
s -> workflowErrors.addAll(deleteSessionService.performSessionDeletion(s)),
() ->
workflowErrors.add(
DeletionWorkflowError.builder()
.deletionSourceType(ASKER)
.deletionTargetType(ALL)
.identifier(rcGroupId)
.reason(RC_SESSION_GROUP_NOT_FOUND_REASON)
.timestamp(nowInUtc())
.build()));
private List<DeletionWorkflowError> performUserSessionDeletionForNonExistingUser(
List<String> rcGroupIds) {
List<DeletionWorkflowError> workflowErrors = new ArrayList<>();
rcGroupIds.forEach(
rcGroupId ->
workflowErrors.addAll(performUserSessionDeletionForNonExistingUser(rcGroupId)));
return workflowErrors;
}

private Collection<? extends DeletionWorkflowError> performUserSessionDeletionForNonExistingUser(
String rcGroupId) {
List<DeletionWorkflowError> workflowErrors = new ArrayList<>();
Optional<Session> session = sessionRepository.findByGroupId(rcGroupId);
session.ifPresent(s -> workflowErrors.addAll(deleteSessionService.performSessionDeletion(s)));
return workflowErrors;
}

private Optional<Session> findSessionInUserSessionList(
String rcGroupId, List<Session> userSessionList) {
return userSessionList.stream().filter(s -> s.getGroupId().equals(rcGroupId)).findFirst();

return userSessionList.stream()
.filter(s -> s.getGroupId() != null && s.getGroupId().equals(rcGroupId))
.findFirst();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public void removeFromGroupOrRollbackOnFailure_Should_executeRemoveForRocketChat

this.removeService.removeFromGroupOrRollbackOnFailure();

verify(this.rocketChatFacade, times(1)).removeUserFromGroup("rcId", "group");
verify(this.rocketChatFacade, times(1)).removeUserFromGroupIgnoreGroupNotFound("rcId", "group");
verify(this.rocketChatFacade, never()).removeUserFromGroup("rcId", "feedback");
}

Expand All @@ -149,7 +149,7 @@ public void removeFromGroupOrRollbackOnFailure_Should_executeRemoveForRocketChat
.thenReturn(singletonList(groupMemberDTO));
doThrow(new RuntimeException(""))
.when(this.rocketChatFacade)
.removeUserFromGroup(anyString(), anyString());
.removeUserFromGroupIgnoreGroupNotFound(anyString(), anyString());
doThrow(new RuntimeException(""))
.when(this.rocketChatFacade)
.addUserToRocketChatGroup(anyString(), anyString());
Expand All @@ -172,7 +172,9 @@ public void removeFromGroupOrRollbackOnFailure_Should_executeRemoveForRocketChat
groupMemberDTO.set_id(this.consultant.getRocketChatId());
when(this.rocketChatFacade.retrieveRocketChatMembers(any()))
.thenReturn(singletonList(groupMemberDTO));
doThrow(new RuntimeException("")).when(this.rocketChatFacade).removeUserFromGroup(any(), any());
doThrow(new RuntimeException(""))
.when(this.rocketChatFacade)
.removeUserFromGroupIgnoreGroupNotFound(any(), any());

try {
this.removeService.removeFromGroupOrRollbackOnFailure();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,8 @@ void assignEnquiry_Should_removeAllUnauthorizedMembers_When_sessionIsNotATeamSes
verifyAsync(
(a) ->
verify(this.rocketChatFacade, times(1))
.removeUserFromGroup(consultantToRemove.getRocketChatId(), session.getGroupId()));
.removeUserFromGroupIgnoreGroupNotFound(
consultantToRemove.getRocketChatId(), session.getGroupId()));
verifyAsync(
(a) ->
verify(this.rocketChatFacade, times(1))
Expand Down Expand Up @@ -424,7 +425,8 @@ void assignEnquiry_ShouldNot_removeTeamMembers_When_sessionIsTeamSession() {
verifyAsync(
(a) ->
verify(this.rocketChatFacade, atLeastOnce())
.removeUserFromGroup(consultantToRemove.getRocketChatId(), session.getGroupId()));
.removeUserFromGroupIgnoreGroupNotFound(
consultantToRemove.getRocketChatId(), session.getGroupId()));
verifyAsync(
(a) ->
verify(this.rocketChatFacade, atLeastOnce())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,13 @@ public void assignSession_Should_removeAllUnauthorizedMembers_When_sessionIsNotA
verifyAsync(
a ->
verify(this.rocketChatFacade, atLeastOnce())
.removeUserFromGroup(consultantToRemove.getRocketChatId(), session.getGroupId()));
.removeUserFromGroupIgnoreGroupNotFound(
consultantToRemove.getRocketChatId(), session.getGroupId()));
verifyAsync(
a ->
verify(this.rocketChatFacade, atLeastOnce())
.removeUserFromGroup(consultantToRemove.getRocketChatId(), session.getGroupId()));
.removeUserFromGroupIgnoreGroupNotFound(
consultantToRemove.getRocketChatId(), session.getGroupId()));
verify(this.emailNotificationFacade, times(1))
.sendAssignEnquiryEmailNotification(any(), any(), any(), any());
}
Expand Down Expand Up @@ -281,23 +283,28 @@ public void assignSession_ShouldNot_removeTeamMembers_When_sessionIsTeamSession(
verifyAsync(
a ->
verify(this.rocketChatFacade, atLeastOnce())
.removeUserFromGroup(consultantToRemove.getRocketChatId(), session.getGroupId()));
.removeUserFromGroupIgnoreGroupNotFound(
consultantToRemove.getRocketChatId(), session.getGroupId()));
verifyAsync(
a ->
verify(this.rocketChatFacade, never())
.removeUserFromGroup("teamConsultantRcId", session.getGroupId()));
.removeUserFromGroupIgnoreGroupNotFound(
"teamConsultantRcId", session.getGroupId()));
verifyAsync(
a ->
verify(this.rocketChatFacade, never())
.removeUserFromGroup("teamConsultantRcId", session.getFeedbackGroupId()));
.removeUserFromGroupIgnoreGroupNotFound(
"teamConsultantRcId", session.getFeedbackGroupId()));
verifyAsync(
a ->
verify(this.rocketChatFacade, never())
.removeUserFromGroup("teamConsultantRcId2", session.getGroupId()));
.removeUserFromGroupIgnoreGroupNotFound(
"teamConsultantRcId2", session.getGroupId()));
verifyAsync(
a ->
verify(this.rocketChatFacade, never())
.removeUserFromGroup("teamConsultantRcId2", session.getFeedbackGroupId()));
.removeUserFromGroupIgnoreGroupNotFound(
"teamConsultantRcId2", session.getFeedbackGroupId()));
verifyAsync(
a ->
verify(this.emailNotificationFacade, times(1))
Expand Down
Loading

0 comments on commit c8f8db8

Please sign in to comment.