Skip to content

Commit

Permalink
HELLODATA-1881 - sync users
Browse files Browse the repository at this point in the history
  • Loading branch information
Slawomir Wieczorek committed Dec 12, 2024
1 parent a51980e commit 394c584
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 14 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package ch.bedag.dap.hellodata.sidecars.sftpgo.listener;

import ch.bedag.dap.hellodata.commons.SlugifyUtil;
import ch.bedag.dap.hellodata.commons.nats.annotation.JetStreamSubscribe;
import ch.bedag.dap.hellodata.commons.sidecars.context.role.HdRoleName;
import ch.bedag.dap.hellodata.commons.sidecars.resources.v1.user.data.UserContextRoleUpdate;
import ch.bedag.dap.hellodata.sidecars.sftpgo.client.model.GroupMapping;
import ch.bedag.dap.hellodata.sidecars.sftpgo.client.model.User;
import ch.bedag.dap.hellodata.sidecars.sftpgo.service.SftpGoService;
import ch.bedag.dap.hellodata.sidecars.sftpgo.service.resource.SftpGoUserResourceProviderService;
Expand All @@ -10,44 +13,75 @@
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClientResponseException;

import java.util.Optional;
import java.util.UUID;

import static ch.bedag.dap.hellodata.commons.sidecars.events.HDEvent.UPDATE_USER_CONTEXT_ROLE;
import static ch.bedag.dap.hellodata.sidecars.sftpgo.service.SftpGoService.ADMIN_GROUP_NAME;

@Log4j2
@Service
@AllArgsConstructor
public class SftpGoUpdateUserContextRoleConsumer {

private final SftpGoService sftpgoService;
private final SftpGoService sftpGoService;
private final SftpGoUserResourceProviderService sftpGoUserResourceProviderService;

@SuppressWarnings("unused")
@JetStreamSubscribe(event = UPDATE_USER_CONTEXT_ROLE)
public void processContextRoleUpdate(UserContextRoleUpdate userContextRoleUpdate) {
log.info("-=-=-=-= RECEIVED USER CONTEXT ROLES UPDATE: payload: {}", userContextRoleUpdate);
User user = fetchUser(userContextRoleUpdate);
checkBusinessContextRole(userContextRoleUpdate, user);
checkDataDomainRoles(userContextRoleUpdate, user);
sftpGoService.updateUser(user);
log.info("Updated user {}", user);
if (userContextRoleUpdate.isSendBackUsersList()) {
sftpGoUserResourceProviderService.publishUsers();
}
}

private void checkDataDomainRoles(UserContextRoleUpdate userContextRoleUpdate, User user) {
userContextRoleUpdate.getContextRoles().stream()
.filter(contextRole -> contextRole.getParentContextKey() != null).forEach(userContextRole -> {
String groupName = SlugifyUtil.slugify(userContextRole.getContextKey(), "");
switch (userContextRole.getRoleName()) {
case NONE ->
user.setGroups(user.getGroups().stream().filter(groupMapping -> groupMapping.getName().equalsIgnoreCase(groupName)).toList());
case DATA_DOMAIN_ADMIN, DATA_DOMAIN_EDITOR, DATA_DOMAIN_VIEWER -> { //TODO ACL based on permission level
GroupMapping groupMapping = new GroupMapping();
groupMapping.type(GroupMapping.TypeEnum.NUMBER_2);
groupMapping.name(groupName);
user.addGroupsItem(groupMapping);
}
}
});
}

// Optional<UserContextRoleUpdate.ContextRole> businessDomainRole = userContextRoleUpdate.getContextRoles().stream()
// .filter(contextRole -> contextRole.getParentContextKey() == null).findFirst();
// businessDomainRole.ifPresent(businessDomainRoleContext -> {
// HdRoleName roleName = businessDomainRoleContext.getRoleName();
// if (roleName != HdRoleName.NONE) {
//
// }
// })

private void checkBusinessContextRole(UserContextRoleUpdate userContextRoleUpdate, User user) {
Optional<UserContextRoleUpdate.ContextRole> businessDomainRole = userContextRoleUpdate.getContextRoles().stream()
.filter(contextRole -> contextRole.getParentContextKey() == null).findFirst();
businessDomainRole.ifPresent(businessDomainRoleContext -> {
HdRoleName roleName = businessDomainRoleContext.getRoleName();
if (roleName != HdRoleName.NONE) {
GroupMapping groupMapping = new GroupMapping();
groupMapping.type(GroupMapping.TypeEnum.NUMBER_1);
groupMapping.name(ADMIN_GROUP_NAME);
user.addGroupsItem(groupMapping);
} else {
user.setGroups(user.getGroups().stream().filter(groupMapping -> groupMapping.getName().equalsIgnoreCase(ADMIN_GROUP_NAME)).toList());
}
});
}

private User fetchUser(UserContextRoleUpdate userContextRoleUpdate) {
User user = null;
try {
user = sftpgoService.getUser(userContextRoleUpdate.getUsername());
user = sftpGoService.getUser(userContextRoleUpdate.getUsername());
log.info("User {} already created", user);
} catch (WebClientResponseException.NotFound notFound) {
log.debug("", notFound);
user = sftpgoService.createUser(userContextRoleUpdate.getEmail(), userContextRoleUpdate.getUsername(), UUID.randomUUID().toString());
user = sftpGoService.createUser(userContextRoleUpdate.getEmail(), userContextRoleUpdate.getUsername(), UUID.randomUUID().toString());
} catch (Exception e) {
log.error("Could not create user {}", userContextRoleUpdate.getEmail(), e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.List;

import static org.springframework.web.reactive.function.client.WebClientResponseException.Conflict;
Expand All @@ -25,7 +27,7 @@
@Service
@RequiredArgsConstructor
public class SftpGoService {
private static final String ADMIN_GROUP_NAME = "Admin";
public static final String ADMIN_GROUP_NAME = "Admin";
private final ApiClient apiClient;
private final S3ConnectionsConfig s3ConnectionsConfig;

Expand All @@ -36,6 +38,8 @@ public class SftpGoService {
@Value("${hello-data.admin-virtual-folder}")
private String adminVirtualFolder;

private OffsetDateTime lastRefreshTime;

@PostConstruct
public void initAdminGroup() {
refreshToken();
Expand Down Expand Up @@ -63,14 +67,23 @@ public User getUser(String username) {
}

public void disableUser(String username) {
refreshToken();
User user = getUser(username);
user.setStatus(User.StatusEnum.NUMBER_0);
UsersApi usersApi = new UsersApi(apiClient);
usersApi.updateUser(username, user, 1).block();
log.info("User {} disabled", username);
}

public void updateUser(User user) {
refreshToken();
UsersApi usersApi = new UsersApi(apiClient);
usersApi.updateUser(user.getUsername(), user, 1).block();
log.info("User {} updated", user.getUsername());
}

public void enableUser(String username) {
refreshToken();
User user = getUser(username);
user.setStatus(User.StatusEnum.NUMBER_1);
UsersApi usersApi = new UsersApi(apiClient);
Expand Down Expand Up @@ -113,6 +126,7 @@ public void createGroup(String dataDomainKey, String dataDomainName) {
}

private void createAdminGroup(GroupsApi groupsApi) {
refreshToken();
BaseVirtualFolder baseVirtualFolder = new BaseVirtualFolder();
baseVirtualFolder.setName(ADMIN_GROUP_NAME);
baseVirtualFolder.setMappedPath(adminVirtualFolder);
Expand All @@ -133,6 +147,7 @@ private void createAdminGroup(GroupsApi groupsApi) {
}

private VirtualFolder createVirtualFolder(String dataDomainKey, String dataDomainName, String groupName) {
refreshToken();
S3ConnectionsConfig.S3Connection s3Connection = s3ConnectionsConfig.getS3Connection(dataDomainKey);
S3Config s3Config = new S3Config();
s3Config.setAccessKey(s3Connection.getAccessKey());
Expand Down Expand Up @@ -173,14 +188,30 @@ private VirtualFolder createVirtualFolder(String dataDomainKey, String dataDomai
return vf;
}

/**
* If the lastRefreshTime is set, check if 20 minutes have passed
*/
private void refreshToken() {
if (lastRefreshTime != null) {
Duration timeSinceLastRefresh = Duration.between(lastRefreshTime, OffsetDateTime.now());
if (timeSinceLastRefresh.toMinutes() < 25) {
log.info("Token refresh skipped. Last refresh was {} minutes ago.", timeSinceLastRefresh.toMinutes());
return;
}
}

HttpBasicAuth basicAuth = (HttpBasicAuth) apiClient.getAuthentication("BasicAuth");
basicAuth.setUsername(sftpGoAdminUsername);
basicAuth.setPassword(sftpGoAdminPassword);

TokenApi tokenApi = new TokenApi(apiClient);
Token token = tokenApi.getToken(null).block();

HttpBearerAuth BearerAuth = (HttpBearerAuth) apiClient.getAuthentication("BearerAuth");
BearerAuth.setBearerToken(token.getAccessToken());

lastRefreshTime = OffsetDateTime.now();
log.info("Token refreshed successfully. Next refresh allowed after 20 minutes.");
}
}

}

0 comments on commit 394c584

Please sign in to comment.