You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airavata.apache.org by la...@apache.org on 2024/09/06 19:40:46 UTC
(airavata-custos) 01/03: initial commit to refactor the code base changing the architecture
This is an automated email from the ASF dual-hosted git repository.
lahirujayathilake pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit 1e51fbd898cb3f6b75b616ee593c30f5604f84d9
Author: lahiruj <la...@gmail.com>
AuthorDate: Wed Aug 28 03:31:01 2024 -0400
initial commit to refactor the code base changing the architecture
---
.../custos-integration-services => api}/pom.xml | 35 +-
.../org/apache/custos/api/CustosAppController.java | 18 +
.../apache/custos/api/GlobalExceptionHandler.java | 85 +
.../api/ProtobufJsonHttpMessageConverter.java | 67 +
.../api/exception/ProtobufConversionException.java | 9 +-
.../api/group/GroupManagementController.java | 1053 ++++++
.../api/identity/IdentityManagementController.java | 606 ++++
.../api/tenant/TenantManagementController.java | 428 +++
.../custos/api/user/UserManagementController.java | 799 +++++
.../apache/custos/api/util/ProtobufJsonUtil.java | 64 +
.../pom.xml | 71 +-
.../java/org/apache/custos/CustosApplication.java | 13 +
.../java/org/apache/custos/config/CacheConfig.java | 49 +
.../org/apache/custos/config/OpenAPIConfig.java | 71 +
.../custos/config/ProtobufJsonOpenAPIConfig.java | 66 +-
.../config/ProtobufMessageConverterConfig.java | 35 +-
.../custos/config/ProtobufPropertiesModule.java | 187 +
.../java/org/apache/custos/config/WebConfig.java | 24 +
application/src/main/resources/application.yml | 91 +
application/src/main/resources/keys/public_key.pem | 9 +
application/src/main/resources/logback-spring.xml | 37 +
.../pom.xml | 51 +-
.../apache/custos/core}/commons/StatusUpdater.java | 20 +-
.../apache/custos/core/constants}/Constants.java | 41 +-
.../core/exception}/UnauthorizedException.java | 8 +-
.../core}/identity/authzcache/AuthzCache.java | 5 +-
.../core}/identity/authzcache/AuthzCacheEntry.java | 6 +-
.../core}/identity/authzcache/AuthzCacheIndex.java | 35 +-
.../identity/authzcache/AuthzCacheManager.java | 81 +
.../identity/authzcache/AuthzCachedStatus.java | 6 +-
.../authzcache/DefaultAuthzCacheManager.java | 10 +-
.../identity/exceptions/AuthSecurityException.java | 6 +-
.../core/mapper/federated/InstitutionMapper.java | 27 +-
.../tenant}/AttributeUpdateMetadataMapper.java | 61 +-
.../mapper/tenant}/StatusUpdateMetadataMapper.java | 37 +-
.../custos/core/mapper/tenant}/TenantMapper.java | 109 +-
.../user}/AttributeUpdateMetadataMapper.java | 33 +-
.../custos/core/mapper/user}/GroupMapper.java | 72 +-
.../mapper/user}/StatusUpdateMetadataMapper.java | 26 +-
.../core/mapper/user}/UserProfileMapper.java | 139 +-
.../core/model/commons}/OperationStatus.java | 2 +-
.../custos/core/model/commons}/StatusEntity.java | 17 +-
.../credential/store}/AgentCredentialEntity.java | 16 +-
.../model/credential/store}/CredentialEntity.java | 44 +-
.../core/model/federated}/CILogonInstitution.java | 14 +-
.../apache/custos/core/model/tenant}/Contact.java | 28 +-
.../custos/core/model/tenant}/RedirectURI.java | 29 +-
.../apache/custos/core/model/tenant}/Tenant.java | 30 +-
.../tenant}/TenantAttributeUpdateMetadata.java | 19 +-
.../model/tenant}/TenantStatusUpdateMetadata.java | 19 +-
.../core/model/user}/AttributeUpdateMetadata.java | 17 +-
.../org/apache/custos/core/model/user}/Group.java | 18 +-
.../custos/core/model/user}/GroupAttribute.java | 17 +-
.../apache/custos/core/model/user}/GroupRole.java | 14 +-
.../core/model/user}/GroupToGroupMembership.java | 17 +-
.../core/model/user}/StatusUpdateMetadata.java | 17 +-
.../custos/core/model/user}/UserAttribute.java | 13 +-
.../core/model/user}/UserGroupMembership.java | 16 +-
.../core/model/user}/UserGroupMembershipType.java | 18 +-
.../custos/core/model/user}/UserProfile.java | 21 +-
.../apache/custos/core/model/user}/UserRole.java | 12 +-
.../repo/commons}/StatusUpdaterRepository.java | 6 +-
.../store}/AgentCredentialRepository.java | 5 +-
.../credential/store}/CredentialRepository.java | 11 +-
.../CiLogonInstitutionCacheRepository.java | 6 +-
.../custos/core/repo/tenant/ContactRepository.java | 8 +-
.../core/repo/tenant/RedirectURIRepository.java | 8 +-
.../core/repo/tenant}/SearchTenantRepository.java | 6 +-
.../repo/tenant}/SearchTenantRepositoryImpl.java | 30 +-
.../TenantAttributeUpdateMetadataRepository.java | 6 +-
.../custos/core/repo/tenant/TenantRepository.java | 9 +-
.../TenantStatusUpdateMetadataRepository.java | 7 +-
.../user/AttributeUpdateMetadataRepository.java | 9 +-
.../core/repo/user/GroupAttributeRepository.java | 8 +-
.../core/repo/user/GroupMembershipRepository.java | 18 +-
.../repo/user}/GroupMembershipTypeRepository.java | 6 +-
.../custos/core/repo/user/GroupRepository.java | 9 +-
.../custos/core/repo/user/GroupRoleRepository.java | 6 +-
.../user}/GroupToGroupMembershipRepository.java | 13 +-
.../core/repo/user}/SearchGroupsRepository.java | 8 +-
.../repo/user}/SearchGroupsRepositoryImpl.java | 46 +-
.../repo/user/StatusUpdateMetadataRepository.java | 9 +-
.../core/repo/user/UserAttributeRepository.java | 15 +-
.../core/repo/user/UserProfileRepository.java | 16 +-
.../custos/core/repo/user/UserRoleRepository.java | 6 +-
.../apache/custos/core/task}/ServiceCallback.java | 4 +-
.../org/apache/custos/core/task/ServiceChain.java | 73 +
.../apache/custos/core/task}/ServiceException.java | 15 +-
.../org/apache/custos/core/task}/ServiceTask.java | 13 +-
.../apache/custos/core/task}/ServiceTaskImpl.java | 27 +-
core/src/main/proto/CredentialStore.proto | 116 +
core/src/main/proto/FederatedAuthentication.proto | 127 +
core/src/main/proto/IamAdmin.proto | 434 +++
core/src/main/proto/Identity.proto | 175 +
core/src/main/proto/IdentityManagement.proto | 65 +
core/src/main/proto/TenantManagement.proto | 115 +
core/src/main/proto/TenantProfile.proto | 162 +
core/src/main/proto/UserManagement.proto | 84 +
core/src/main/proto/UserProfile.proto | 171 +
custos-core/pom.xml | 43 -
custos-core/sharing-core-impl/pom.xml | 48 -
.../org/apache/custos/sharing/core/SharingAPI.java | 287 --
.../core/exceptions/CustosSharingException.java | 35 -
.../custos/sharing/core/impl/SharingImpl.java | 1168 -------
.../custos/sharing/core/mapper/EntityMapper.java | 121 -
.../sharing/core/mapper/EntityTypeMapper.java | 69 -
.../sharing/core/mapper/PermissionTypeMapper.java | 66 -
.../custos/sharing/core/mapper/SharingMapper.java | 150 -
.../sharing/core/persistance/model/Entity.java | 238 --
.../sharing/core/persistance/model/EntityType.java | 143 -
.../core/persistance/model/PermissionType.java | 142 -
.../sharing/core/persistance/model/Sharing.java | 182 -
.../repository/SearchEntityRepository.java | 34 -
.../repository/SearchEntityRepositoryImpl.java | 183 -
.../persistance/repository/SharingRepository.java | 95 -
.../custos/sharing/core/utils/Constants.java | 33 -
.../src/main/proto/SharingModel.proto | 117 -
.../agent-profile-core-service-client-stub/pom.xml | 98 -
.../agent/profile/client/AgentProfileClient.java | 100 -
.../pom.xml | 104 -
.../management/client/ClusterManagementClient.java | 57 -
.../pom.xml | 97 -
.../store/client/CredentialStoreServiceClient.java | 203 --
.../custos-logging-client-stub/pom.xml | 117 -
.../custos/logging/client/LoggingClient.java | 105 -
.../pom.xml | 105 -
.../client/FederatedAuthenticationClient.java | 142 -
.../iam-admin-core-service-client-stub/pom.xml | 100 -
.../iam/admin/client/IamAdminServiceClient.java | 396 ---
.../identity-core-service-client-stub/pom.xml | 96 -
.../custos/identity/client/IdentityClient.java | 151 -
.../custos/messaging/client/MessagingClient.java | 96 -
.../custos-core-services-client-stubs/pom.xml | 62 -
.../pom.xml | 97 -
.../secret/client/ResourceSecretClient.java | 131 -
.../sharing-core-service-client-stub/pom.xml | 104 -
.../custos/sharing/client/SharingClient.java | 201 --
.../pom.xml | 102 -
.../profile/client/async/TenantProfileClient.java | 185 -
.../user-profile-core-service-client-stub/pom.xml | 95 -
.../user/profile/client/UserProfileClient.java | 240 --
.../custos-core-services-server/Dockerfile | 6 -
.../custos-core-services-server/pom.xml | 275 --
.../src/main/dist/bin/custos-daemon.sh | 113 -
.../src/main/dist/bin/custos.sh | 71 -
.../src/main/dist/bin/setenv.sh | 46 -
.../src/main/dist/conf/application.properties | 90 -
.../src/main/dist/conf/bootstrap.properties | 26 -
.../dist/conf/keycloak-client-truststore.pkcs12 | Bin 5709 -> 0 bytes
.../src/main/dist/conf/log4j2.xml | 49 -
.../main/dist/conf/vault-client-truststore.pkcs12 | Bin 5709 -> 0 bytes
.../dist/custos-core-services-server-assembly.xml | 84 -
.../core/services/api/CoreServicesServer.java | 118 -
.../src/main/resources/application.properties | 70 -
.../src/main/resources/bootstrap.properties | 27 -
.../src/main/resources/certificate.p12 | Bin 2501 -> 0 bytes
.../src/main/resources/certificate_mul.p12 | Bin 2621 -> 0 bytes
.../resources/keycloak-client-truststore.pkcs12 | Bin 5709 -> 0 bytes
.../src/main/resources/log4j2.xml | 27 -
.../main/resources/vault-client-truststore.pkcs12 | Bin 5709 -> 0 bytes
.../agent-profile-core-service/pom.xml | 154 -
.../custos/agent/profile/mapper/AgentMapper.java | 160 -
.../agent/profile/persistance/model/Agent.java | 131 -
.../profile/persistance/model/AgentAttribute.java | 75 -
.../agent/profile/persistance/model/AgentRole.java | 75 -
.../repository/AgentAttributeRepository.java | 27 -
.../persistance/repository/AgentRepository.java | 27 -
.../repository/AgentRoleRepository.java | 28 -
.../agent/profile/service/AgentProfileService.java | 242 --
.../custos/agent/profile/utils/Constants.java | 25 -
.../profile/validator/AgentInputValidator.java | 74 -
.../src/main/proto/AgentProfileService.proto | 66 -
.../cluster-management-core-service/pom.xml | 157 -
.../service/ClusterManagementService.java | 105 -
.../util/ClusterManagementOperations.java | 23 -
.../validator/ClusterManagementInputValidator.java | 59 -
.../credential-store-core-service/pom.xml | 187 -
.../store/service/CredentialStoreService.java | 1148 -------
.../validator/CredentialStoreInputValidator.java | 178 -
.../src/main/proto/CredentialStoreService.proto | 144 -
.../custos-core-services-commons/pom.xml | 111 -
.../services/api/commons/ServiceInterceptor.java | 96 -
.../core/services/api/commons/Validator.java | 25 -
.../exceptions/MissingParameterException.java | 30 -
.../core/services/api/commons/util/Constants.java | 32 -
.../api/commons/util/MethodNameExtractor.java | 28 -
.../custos-core-services/custos-logging/pom.xml | 150 -
.../custos/logging/mapper/LogEventMapper.java | 59 -
.../custos/logging/persistance/model/LogEvent.java | 123 -
.../persistance/model/LoggingEnabledStatus.java | 57 -
.../persistance/repository/LogEventRepo.java | 30 -
.../persistance/repository/LogEventRepoImpl.java | 144 -
.../custos/logging/service/LoggingService.java | 157 -
.../validator/CustosLoggingInputValidator.java | 119 -
.../src/main/proto/LoggingService.proto | 78 -
.../custos-messaging-core-service/pom.xml | 172 -
.../messaging/MessagingServiceInitializer.java | 51 -
.../custos/messaging/events/email/EmailSender.java | 62 -
.../events/model/MessageDeserializer.java | 58 -
.../messaging/events/model/MessageSerializer.java | 57 -
.../events/publisher/MessageProducer.java | 56 -
.../custos/messaging/mapper/EmailMapper.java | 113 -
.../custos/messaging/mapper/MessagingMapper.java | 51 -
.../persistance/model/EmailBodyParams.java | 70 -
.../persistance/model/EmailReceivers.java | 77 -
.../messaging/persistance/model/EmailTemplate.java | 155 -
.../persistance/model/MessagingMetadata.java | 105 -
.../repository/MessagingMetadataRepository.java | 31 -
.../custos/messaging/service/EmailService.java | 287 --
.../custos/messaging/service/MessagingService.java | 89 -
.../src/main/proto/EmailService.proto | 112 -
.../federated-authentication-core-service/pom.xml | 180 -
.../exceptions/MissingParameterException.java | 30 -
.../service/FederatedAuthenticationService.java | 458 ---
.../FederatedAuthenticationInputValidator.java | 195 --
.../proto/FederatedAuthenticationService.proto | 143 -
.../iam-admin-core-service/IamAdminService_pb2.py | 3592 --------------------
.../IamAdminService_pb2_grpc.py | 1585 ---------
.../iam-admin-core-service/pom.xml | 150 -
.../iam/exceptions/MissingParameterException.java | 30 -
.../custos/iam/validator/IAMInputValidator.java | 901 -----
.../src/main/proto/IamAdminService.proto | 508 ---
.../identity-core-service/pom.xml | 148 -
.../identity/authzcache/AuthzCacheManager.java | 79 -
.../custos/identity/service/IdentityService.java | 454 ---
.../apache/custos/identity/utils/Constants.java | 26 -
.../identity/validator/IdentityInputValidator.java | 321 --
.../src/main/proto/IdentityService.proto | 137 -
.../src/main/proto/IdentityService_pb.js | 3255 ------------------
custos-services/custos-core-services/pom.xml | 54 -
.../resource-secret-core-service/pom.xml | 204 --
.../custos/resource/secret/manager/Credential.java | 27 -
.../secret/manager/CredentialGeneratorFactory.java | 59 -
.../manager/adaptor/inbound/CredentialReader.java | 465 ---
.../adaptor/outbound/CertificateCredential.java | 113 -
.../manager/adaptor/outbound/CredentialMap.java | 76 -
.../manager/adaptor/outbound/CredentialWriter.java | 576 ----
.../manager/adaptor/outbound/KVCredential.java | 52 -
.../adaptor/outbound/PasswordCredential.java | 57 -
.../adaptor/outbound/ResourceCredential.java | 154 -
.../manager/adaptor/outbound/SSHCredential.java | 111 -
.../secret/persistance/local/model/Secret.java | 149 -
.../local/repository/SecretRepository.java | 41 -
.../secret/persistance/vault/Certificate.java | 88 -
.../secret/persistance/vault/KVSecret.java | 54 -
.../secret/persistance/vault/PasswordSecret.java | 61 -
.../persistance/vault/SSHCredentialSecrets.java | 65 -
.../secret/service/ResourceSecretService.java | 559 ---
.../custos/resource/secret/utils/Constants.java | 32 -
.../custos/resource/secret/utils/Operations.java | 37 -
.../validator/ResourceSecretInputValidator.java | 155 -
.../src/main/proto/ResourceSecretService.proto | 203 --
.../sharing-core-service/pom.xml | 162 -
.../custos/sharing/service/SharingService.java | 724 ----
.../sharing/validator/SharingInputValidator.java | 340 --
.../src/main/proto/SharingService.proto | 165 -
.../tenant-profile-core-service/pom.xml | 166 -
.../profile/TenantProfileServiceInitializer.java | 63 -
.../exceptions/MissingParameterException.java | 30 -
.../respository/RedirectURIRepository.java | 30 -
.../persistance/respository/TenantRepository.java | 47 -
.../profile/service/TenantProfileService.java | 422 ---
.../validator/TenantProfileInputValidator.java | 261 --
.../src/main/proto/TenantProfileService.proto | 174 -
.../user-profile-core-service/pom.xml | 139 -
.../AttributeUpdateMetadataRepository.java | 30 -
.../repository/GroupAttributeRepository.java | 28 -
.../repository/GroupMembershipRepository.java | 42 -
.../persistance/repository/GroupRepository.java | 33 -
.../persistance/repository/RoleRepository.java | 32 -
.../repository/UserAttributeRepository.java | 39 -
.../persistance/repository/UserRepository.java | 36 -
.../user/profile/service/UserProfileService.java | 1493 --------
.../custos/user/profile/utils/Constants.java | 25 -
.../validator/UserProfileInputValidator.java | 364 --
.../src/main/proto/UserProfileService.proto | 216 --
.../custos-grpc-web-proxy/Dockerfile | 2 -
.../custos-grpc-web-proxy/pom.xml | 60 -
.../src/main/helm/.helmignore | 22 -
.../custos-grpc-web-proxy/src/main/helm/Chart.yaml | 5 -
.../src/main/helm/templates/NOTES.txt | 21 -
.../src/main/helm/templates/_helpers.tpl | 56 -
.../src/main/helm/templates/deployment.yaml | 61 -
.../src/main/helm/templates/service.yaml | 29 -
.../src/main/helm/templates/serviceaccount.yaml | 8 -
.../main/helm/templates/tests/test-connection.yaml | 15 -
.../src/main/helm/values.yaml | 90 -
.../src/main/resources/envoy.yaml | 113 -
.../custos-keycloak/Dockerfile | 5 -
.../custos-keycloak/pom.xml | 32 -
.../main/resources/keycloak-metrics-spi-2.5.1.jar | Bin 232640 -> 0 bytes
.../src/main/resources/standalone-ha.xml | 657 ----
.../src/main/resources/standalone.xml | 596 ----
.../htrc/email/messages/messages_en.properties | 55 -
.../resources/themes/htrc/email/theme.properties | 18 -
.../src/main/resources/themes/htrc/login/error.ftl | 44 -
.../themes/htrc/login/login-idp-link-confirm.ftl | 42 -
.../themes/htrc/login/login-idp-link-email.ftl | 25 -
.../themes/htrc/login/login-page-expired.ftl | 42 -
.../themes/htrc/login/login-update-profile.ftl | 74 -
.../themes/htrc/login/login-verify-email.ftl | 18 -
.../src/main/resources/themes/htrc/login/login.ftl | 70 -
.../themes/htrc/login/resources/css/styles.css | 192 --
.../main/resources/themes/htrc/login/template.ftl | 25 -
.../resources/themes/htrc/login/theme.properties | 20 -
.../custos-external-services-distributions/pom.xml | 21 -
.../custos-federated-services-clients/pom.xml | 102 -
.../services/clients/keycloak/KeycloakUtils.java | 199 --
.../clients/keycloak/auth/TokenResponse.java | 120 -
.../custos/integration/core/ServiceChain.java | 84 -
.../integration/core/endpoint/TargetEndpoint.java | 50 -
.../core/exceptions/InValidParameterException.java | 27 -
.../core/exceptions/MissingParameterException.java | 30 -
.../core/exceptions/UnAuthorizedException.java | 30 -
.../interceptor/IntegrationServiceInterceptor.java | 27 -
.../core/interceptor/ServiceInterceptor.java | 103 -
.../custos/integration/core/utils/Constants.java | 39 -
.../core/utils/ShamirSecretHandler.java | 72 -
.../custos-integration-services-server/Dockerfile | 6 -
.../custos-integration-services-server/pom.xml | 281 --
.../src/main/dist/bin/custos-daemon.sh | 113 -
.../src/main/dist/bin/custos.sh | 71 -
.../src/main/dist/bin/setenv.sh | 46 -
.../src/main/dist/conf/application.properties | 38 -
.../dist/conf/custos_user_schema_extention.json | 91 -
.../src/main/dist/conf/log4j2.xml | 49 -
...custos-integration-services-server-assembly.xml | 84 -
.../services/api/IntegrationServicesServer.java | 126 -
.../src/main/resources/application.properties | 38 -
.../resources/custos_user_schema_extention.json | 91 -
.../src/main/resources/log4j2.xml | 27 -
.../agent-management-service/pom.xml | 138 -
.../AgentManagementClientAuthInterceptorImpl.java | 52 -
.../AgentManagementInputValidator.java | 85 -
...rTenantRestrictedOperationsInterceptorImpl.java | 70 -
.../AgentManagementUserAuthInterceptorImpl.java | 241 --
.../management/service/AgentManagementService.java | 870 -----
.../src/main/proto/AgentManagementService.proto | 148 -
.../custos-integration-services-commons/pom.xml | 122 -
.../commons/interceptors/AuthInterceptor.java | 597 ----
.../commons/interceptors/LoggingInterceptor.java | 104 -
.../interceptors/MultiTenantAuthInterceptor.java | 91 -
.../services/commons/utils/EmailSender.java | 54 -
.../utils/EmailServiceOutputStreamObserver.java | 43 -
.../services/commons/utils/EventPublisher.java | 55 -
.../commons/utils/InterServiceModelMapper.java | 68 -
.../commons/utils/OutputStreamObserver.java | 44 -
.../custos-integration-services-swagger/pom.xml | 97 -
.../services/swagger/SwaggerInitializer.java | 50 -
.../custos/services/swagger/SwaggerSpecConfig.java | 55 -
.../swagger/controller/SwaggerUIController.java | 37 -
.../src/main/resources/application.properties | 26 -
.../resources/protos/AgentManagementService.proto | 148 -
.../resources/protos/AgentProfileService.proto | 66 -
.../protos/ClusterManagementService.proto | 42 -
.../resources/protos/CredentialStoreService.proto | 143 -
.../src/main/resources/protos/EmailService.proto | 112 -
.../protos/FederatedAuthenticationService.proto | 143 -
.../resources/protos/GroupManagementService.proto | 211 --
.../main/resources/protos/IamAdminService.proto | 508 ---
.../protos/IdentityManagementService.proto | 156 -
.../main/resources/protos/IdentityService.proto | 137 -
.../resources/protos/LogManagementService.proto | 53 -
.../src/main/resources/protos/LoggingService.proto | 78 -
.../main/resources/protos/MessagingService.proto | 63 -
.../protos/ResourceSecretManagementService.proto | 156 -
.../resources/protos/ResourceSecretService.proto | 203 --
.../protos/SharingManagementService.proto | 206 --
.../src/main/resources/protos/SharingService.proto | 222 --
.../resources/protos/TenantManagementService.proto | 285 --
.../resources/protos/TenantProfileService.proto | 174 -
.../resources/protos/UserManagementService.proto | 277 --
.../main/resources/protos/UserProfileService.proto | 213 --
.../src/main/resources/pythonStubGenerator.sh | 24 -
.../agent-management-service/swagger.json | 830 -----
.../cluster-management-service/swagger.json | 59 -
.../group-management-service/swagger.json | 2119 ------------
.../identity-management-service/swagger.json | 659 ----
.../log-management-service/swagger.json | 245 --
.../swagger.json | 1792 ----------
.../sharing-management-service/swagger.json | 2390 -------------
.../tenant-management-service/swagger.json | 1660 ---------
.../user-management-service/swagger.json | 1997 -----------
.../group-management-service/pom.xml | 139 -
.../GroupManagementClientAuthInterceptorImpl.java | 193 --
.../GroupManagementInputValidator.java | 89 -
.../management/service/GroupManagementService.java | 887 -----
.../src/main/proto/GroupManagementService.proto | 211 --
.../identity-management-service/pom.xml | 141 -
.../IdentityManagementAgentAuthInterceptor.java | 90 -
.../IdentityManagementAuthInterceptorImpl.java | 176 -
.../IdentityManagementInputValidator.java | 138 -
.../service/IdentityManagementService.java | 392 ---
.../identity/management/utils/Constants.java | 35 -
.../src/main/proto/IdentityManagementService.proto | 156 -
.../src/main/resources/application.properties | 29 -
.../src/main/resources/bootstrap.properties | 22 -
.../log-management-service/pom.xml | 170 -
.../LogManagementAuthInterceptorImpl.java | 126 -
.../interceptors/LogManagementInputValidator.java | 74 -
.../management/service/LogManagementService.java | 92 -
.../src/main/proto/LogManagementService.proto | 53 -
.../resource-secret-management-service/pom.xml | 158 -
...esourceSecretManagementAuthInterceptorImpl.java | 208 --
.../ResourceSecretManagementInputValidator.java | 120 -
.../service/ResourceSecretManagementService.java | 506 ---
.../proto/ResourceSecretManagementService.proto | 156 -
.../src/main/resources/application.properties | 29 -
.../src/main/resources/bootstrap.properties | 22 -
.../scim-service/pom.xml | 134 -
.../apache/custos/scim/SCIMServiceInitializer.java | 32 -
.../apache/custos/scim/config/Swagger2Config.java | 55 -
.../custos/scim/exception/CustosSCIMException.java | 32 -
.../scim/exception/NotAuthorizedException.java | 27 -
.../custos/scim/resource/AbstractResource.java | 63 -
.../apache/custos/scim/resource/GroupResource.java | 334 --
.../scim/resource/ServiceProviderResource.java | 69 -
.../apache/custos/scim/resource/UserResource.java | 304 --
.../scim/resource/manager/ResourceManager.java | 919 -----
.../org/apache/custos/scim/utils/AuthHandler.java | 69 -
.../org/apache/custos/scim/utils/Constants.java | 75 -
.../resources/custos_user_schema_extention.bk.json | 149 -
.../resources/custos_user_schema_extention.json | 91 -
.../sharing-management-service/pom.xml | 149 -
.../management/exceptions/SharingException.java | 28 -
.../SharingManagementAuthInterceptorImpl.java | 145 -
.../SharingManagementInputValidator.java | 114 -
.../service/SharingManagementService.java | 801 -----
.../src/main/proto/SharingManagementService.proto | 207 --
.../tenant-management-service/pom.xml | 155 -
.../exceptions/MissingParameterException.java | 30 -
.../TenantManagementAuthInterceptorImpl.java | 435 ---
...nantManagementDynamicRegistrationValidator.java | 168 -
.../TenantManagementInputValidator.java | 227 --
...rTenantRestrictedOperationsInterceptorImpl.java | 128 -
.../service/TenantManagementService.java | 969 ------
.../src/main/proto/TenantManagementService.proto | 285 --
.../user-management-service/pom.xml | 138 -
.../UserManagementServiceInitializer.java | 86 -
.../UserManagementAuthInterceptorImpl.java | 517 ---
.../interceptors/UserManagementInputValidator.java | 92 -
...rTenantRestrictedOperationsInterceptorImpl.java | 70 -
.../management/service/UserManagementService.java | 1438 --------
.../src/main/proto/UserManagementService.proto | 279 --
.../src/main/proto/UserManagementService_pb.js | 1954 -----------
custos-services/pom.xml | 50 -
pom.xml | 532 ++-
services/pom.xml | 114 +
.../org/apache/custos/service/auth}/AuthClaim.java | 6 +-
.../org/apache/custos/service/auth/KeyLoader.java | 96 +
.../custos/service/auth/TokenAuthorizer.java | 420 +++
.../apache/custos/service/auth/TokenService.java | 145 +
.../service/credential/store}/Credential.java | 5 +-
.../credential/store}/CredentialManager.java | 124 +-
.../credential/store/CredentialStoreService.java | 627 ++++
.../service/credential/store}/CredentialTypes.java | 2 +-
.../service/credential/store}/Operations.java | 6 +-
.../exceptions/AuthenticationException.java | 16 +-
.../FederatedAuthenticationServiceException.java | 2 +-
.../exceptions/InternalServerException.java | 15 +-
.../store}/CredentialGenerationException.java | 8 +-
.../store}/CredentialsAuthenticationException.java | 8 +-
.../store}/MissingParameterException.java | 10 +-
.../cilogon/FederatedAuthenticationService.java | 357 ++
.../service/federated/cilogon}/Operations.java | 2 +-
.../federated/client}/cilogon/CILogonClient.java | 53 +-
.../client}/cilogon/CILogonInstitution.java | 2 +-
.../federated/client}/cilogon/CILogonRequest.java | 5 +-
.../federated/client}/cilogon/CILogonResponse.java | 7 +-
.../federated/client}/keycloak/KeycloakClient.java | 968 ++----
.../client}/keycloak/KeycloakClientSecret.java | 4 +-
.../federated/client/keycloak/KeycloakUtils.java | 97 +
.../client}/keycloak/auth/KeycloakAuthClient.java | 387 +--
.../federated/client}/keycloak/auth/User.java | 2 +-
.../apache/custos/service/iam}/IAMOperations.java | 2 +-
.../custos/service/iam}/IamAdminService.java | 1595 +++------
.../org/apache/custos/service/iam}/Status.java | 2 +-
.../custos/service/identity/IdentityService.java | 486 +++
.../service/management/GroupManagementService.java | 434 +++
.../management/IdentityManagementService.java | 394 +++
.../service/management}/TenantActivationTask.java | 172 +-
.../management/TenantManagementService.java | 760 +++++
.../service/management/UserManagementService.java | 1379 ++++++++
.../service/profile/TenantProfileService.java | 333 ++
.../custos/service/profile/UserProfileService.java | 1144 +++++++
485 files changed, 14160 insertions(+), 75266 deletions(-)
diff --git a/custos-services/custos-integration-services/pom.xml b/api/pom.xml
similarity index 61%
rename from custos-services/custos-integration-services/pom.xml
rename to api/pom.xml
index b2e78fec9..a4bfd25a6 100644
--- a/custos-services/custos-integration-services/pom.xml
+++ b/api/pom.xml
@@ -21,30 +21,27 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
<parent>
- <artifactId>custos</artifactId>
<groupId>org.apache.custos</groupId>
- <version>1.1-SNAPSHOT</version>
- <relativePath>../../pom.xml</relativePath>
+ <artifactId>custos</artifactId>
+ <version>1.1-SNAPSHOT</version>
</parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>custos-integration-services</artifactId>
- <packaging>pom</packaging>
- <modules>
- <module>tenant-management-service</module>
- <module>identity-management-service</module>
- <module>custos-integration-services-commons</module>
- <module>user-management-service</module>
- <module>scim-service</module>
+ <artifactId>custos-api</artifactId>
- <module>group-management-service</module>
- <module>agent-management-service</module>
- <module>resource-secret-management-service</module>
- <module>sharing-management-service</module>
- <module>log-management-service</module>
- <module>custos-integration-services-swagger</module>
+ <dependencies>
- </modules>
+ <dependency>
+ <groupId>org.apache.custos</groupId>
+ <artifactId>custos-services</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
+ <version>${springdoc.version}</version>
+ </dependency>
+ </dependencies>
</project>
\ No newline at end of file
diff --git a/api/src/main/java/org/apache/custos/api/CustosAppController.java b/api/src/main/java/org/apache/custos/api/CustosAppController.java
new file mode 100644
index 000000000..b3a8985d3
--- /dev/null
+++ b/api/src/main/java/org/apache/custos/api/CustosAppController.java
@@ -0,0 +1,18 @@
+package org.apache.custos.api;
+
+import io.swagger.v3.oas.annotations.Hidden;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/api/v1")
+public class CustosAppController {
+
+ @Hidden
+ @GetMapping("/health")
+ public ResponseEntity<?> health() {
+ return ResponseEntity.ok().build();
+ }
+}
diff --git a/api/src/main/java/org/apache/custos/api/GlobalExceptionHandler.java b/api/src/main/java/org/apache/custos/api/GlobalExceptionHandler.java
new file mode 100644
index 000000000..3ee2aad8b
--- /dev/null
+++ b/api/src/main/java/org/apache/custos/api/GlobalExceptionHandler.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.custos.api;
+
+import org.apache.custos.core.exception.UnauthorizedException;
+import org.apache.custos.service.exceptions.AuthenticationException;
+import org.apache.custos.service.exceptions.InternalServerException;
+import jakarta.persistence.EntityNotFoundException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+
+@ControllerAdvice
+public class GlobalExceptionHandler {
+
+ private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
+
+ @ExceptionHandler(AuthenticationException.class)
+ public ResponseEntity<String> handleAuthenticationException(AuthenticationException ex) {
+ logger.error("Authentication exception: ", ex);
+ return ResponseEntity
+ .status(HttpStatus.UNAUTHORIZED)
+ .body(ex.getMessage());
+ }
+
+ @ExceptionHandler(InternalServerException.class)
+ public ResponseEntity<String> handleInternalServerError(InternalServerException ex) {
+ logger.error("Internal server error: ", ex);
+ return ResponseEntity
+ .status(HttpStatus.INTERNAL_SERVER_ERROR)
+ .body(ex.getMessage());
+ }
+
+ @ExceptionHandler(IllegalArgumentException.class)
+ public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex) {
+ logger.error("Illegal argument error: ", ex);
+ return ResponseEntity
+ .status(HttpStatus.BAD_REQUEST)
+ .body(ex.getMessage());
+ }
+
+ @ExceptionHandler(EntityNotFoundException.class)
+ public ResponseEntity<String> handleEntityNotFoundException(EntityNotFoundException ex) {
+ logger.error("Entity not found: ", ex);
+ return ResponseEntity
+ .status(HttpStatus.NOT_FOUND)
+ .body(ex.getMessage());
+ }
+
+ @ExceptionHandler(UnauthorizedException.class)
+ public ResponseEntity<String> handleUnauthorizedExceptions(UnauthorizedException ex) {
+ logger.error("Unauthorized exception: ", ex);
+ return ResponseEntity
+ .status(HttpStatus.UNAUTHORIZED)
+ .body("Unauthorized: " + ex.getMessage());
+ }
+
+ @ExceptionHandler(Exception.class)
+ public ResponseEntity<String> handleOtherExceptions(Exception ex) {
+ logger.error("Unexpected error occurred: ", ex);
+ return ResponseEntity
+ .status(HttpStatus.INTERNAL_SERVER_ERROR)
+ .body("Unexpected error occurred");
+ }
+}
\ No newline at end of file
diff --git a/api/src/main/java/org/apache/custos/api/ProtobufJsonHttpMessageConverter.java b/api/src/main/java/org/apache/custos/api/ProtobufJsonHttpMessageConverter.java
new file mode 100644
index 000000000..6830664fd
--- /dev/null
+++ b/api/src/main/java/org/apache/custos/api/ProtobufJsonHttpMessageConverter.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.custos.api;
+
+import com.google.protobuf.Message;
+import com.google.protobuf.util.JsonFormat;
+import org.springframework.http.HttpInputMessage;
+import org.springframework.http.HttpOutputMessage;
+import org.springframework.http.MediaType;
+import org.springframework.http.converter.AbstractHttpMessageConverter;
+import org.springframework.http.converter.HttpMessageConversionException;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.http.converter.HttpMessageNotWritableException;
+
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+
+public class ProtobufJsonHttpMessageConverter extends AbstractHttpMessageConverter<Message> {
+
+ public ProtobufJsonHttpMessageConverter() {
+ super(new MediaType("application", "json", StandardCharsets.UTF_8));
+ }
+
+ @Override
+ protected boolean supports(Class<?> clazz) {
+ return Message.class.isAssignableFrom(clazz);
+ }
+
+ @Override
+ protected Message readInternal(Class<? extends Message> clazz, HttpInputMessage inputMessage) throws HttpMessageNotReadableException {
+ try (InputStreamReader reader = new InputStreamReader(inputMessage.getBody(), StandardCharsets.UTF_8)) {
+ Message.Builder builder = (Message.Builder) clazz.getMethod("newBuilder").invoke(null);
+ JsonFormat.parser().ignoringUnknownFields().merge(reader, builder);
+ return builder.build();
+ } catch (Exception e) {
+ throw new HttpMessageNotReadableException("Error reading Protobuf message", e, inputMessage);
+ }
+ }
+
+ @Override
+ protected void writeInternal(Message message, HttpOutputMessage outputMessage) throws HttpMessageNotWritableException {
+ try {
+ outputMessage.getBody().write(JsonFormat.printer().preservingProtoFieldNames().print(message).getBytes(StandardCharsets.UTF_8));
+ } catch (Exception e) {
+ throw new HttpMessageConversionException("Error writing Protobuf message", e);
+ }
+ }
+
+}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/exceptions/TenantNotFoundException.java b/api/src/main/java/org/apache/custos/api/exception/ProtobufConversionException.java
similarity index 81%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/exceptions/TenantNotFoundException.java
rename to api/src/main/java/org/apache/custos/api/exception/ProtobufConversionException.java
index 4b245d108..a79ce116f 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/exceptions/TenantNotFoundException.java
+++ b/api/src/main/java/org/apache/custos/api/exception/ProtobufConversionException.java
@@ -17,10 +17,11 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.exceptions;
+package org.apache.custos.api.exception;
-public class TenantNotFoundException extends RuntimeException {
- public TenantNotFoundException(String message, Throwable cause) {
+public class ProtobufConversionException extends RuntimeException {
+
+ public ProtobufConversionException(String message, Throwable cause) {
super(message, cause);
}
-}
+}
\ No newline at end of file
diff --git a/api/src/main/java/org/apache/custos/api/group/GroupManagementController.java b/api/src/main/java/org/apache/custos/api/group/GroupManagementController.java
new file mode 100644
index 000000000..b29f22334
--- /dev/null
+++ b/api/src/main/java/org/apache/custos/api/group/GroupManagementController.java
@@ -0,0 +1,1053 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.custos.api.group;
+
+import org.apache.custos.core.constants.Constants;
+import org.apache.custos.core.user.profile.api.DefaultGroupMembershipTypes;
+import org.apache.custos.core.user.profile.api.GetAllGroupsResponse;
+import org.apache.custos.core.user.profile.api.GetAllUserProfilesResponse;
+import org.apache.custos.core.user.profile.api.Group;
+import org.apache.custos.core.user.profile.api.GroupAttribute;
+import org.apache.custos.core.user.profile.api.GroupMembership;
+import org.apache.custos.core.user.profile.api.GroupRequest;
+import org.apache.custos.core.user.profile.api.GroupToGroupMembership;
+import org.apache.custos.core.user.profile.api.Status;
+import org.apache.custos.core.user.profile.api.UserGroupMembershipTypeRequest;
+import org.apache.custos.core.user.profile.api.UserProfile;
+import org.apache.custos.core.user.profile.api.UserProfileRequest;
+import org.apache.custos.service.auth.AuthClaim;
+import org.apache.custos.service.auth.TokenAuthorizer;
+import org.apache.custos.service.management.GroupManagementService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.Parameter;
+import io.swagger.v3.oas.annotations.enums.ParameterIn;
+import io.swagger.v3.oas.annotations.media.ArraySchema;
+import io.swagger.v3.oas.annotations.media.Content;
+import io.swagger.v3.oas.annotations.media.Schema;
+import io.swagger.v3.oas.annotations.media.SchemaProperty;
+import io.swagger.v3.oas.annotations.responses.ApiResponse;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.DeleteMapping;
+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.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.server.ResponseStatusException;
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
+
+import java.net.URI;
+import java.util.Optional;
+
+@RestController
+@RequestMapping("/api/v1/group-management")
+@Tag(name = "Group Management")
+public class GroupManagementController {
+
+ private final GroupManagementService groupManagementService;
+ private final TokenAuthorizer tokenAuthorizer;
+
+ public GroupManagementController(GroupManagementService groupManagementService, TokenAuthorizer tokenAuthorizer) {
+ this.groupManagementService = groupManagementService;
+ this.tokenAuthorizer = tokenAuthorizer;
+ }
+
+ @PostMapping("/groups")
+ @Operation(
+ summary = "Group Creation",
+ description = "Creates a new group. If a group ID is provided and it already exists, an error will be thrown. " +
+ "If no ID is provided, the group name will be used as the ID along with a random string.",
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ required = true,
+ content = @Content(
+ schemaProperties = {
+ @SchemaProperty(
+ name = "id",
+ schema = @Schema(
+ type = "string",
+ description = "The Group ID"
+ )
+ ),
+ @SchemaProperty(
+ name = "name",
+ schema = @Schema(
+ type = "string",
+ description = "Group Name"
+ )
+ ),
+ @SchemaProperty(
+ name = "description",
+ schema = @Schema(
+ type = "string",
+ description = "Parent Group ID"
+ )
+ ),
+ @SchemaProperty(
+ name = "owner_id",
+ schema = @Schema(
+ type = "string",
+ description = "User ID of the group owner"
+ )
+ ),
+ @SchemaProperty(
+ name = "parent_id",
+ schema = @Schema(
+ type = "string",
+ description = "Parent Group ID"
+ )
+ ),
+ @SchemaProperty(
+ name = "attributes",
+ array = @ArraySchema(
+ schema = @Schema(implementation = GroupAttribute.class),
+ arraySchema = @Schema(description = "List of Group Attributes")
+ )
+ ),
+ @SchemaProperty(
+ name = "realm_roles",
+ array = @ArraySchema(
+ schema = @Schema(implementation = String.class),
+ arraySchema = @Schema(description = "List of Realm Roles")
+ )
+ ),
+ @SchemaProperty(
+ name = "client_roles",
+ array = @ArraySchema(
+ schema = @Schema(implementation = String.class),
+ arraySchema = @Schema(description = "List of Client Roles")
+ )
+ )
+ }
+ )
+ ),
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group creation request",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(responseCode = "201", description = "Successful operation", content = @Content(schema = @Schema(implementation = Group.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "400", description = "Bad Request, If the 'parent_id' doesn't exist", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<Group> createGroup(@RequestBody Group request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, headers.getFirst("client_id"));
+ if (claim.isEmpty()) {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ AuthClaim authClaim = claim.get();
+ GroupRequest groupRequest = GroupRequest.newBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .setPerformedBy(authClaim.getPerformedBy() != null ? authClaim.getPerformedBy() : Constants.SYSTEM)
+ .setGroup(request)
+ .build();
+
+ Group group = groupManagementService.createGroup(groupRequest);
+
+ URI location = ServletUriComponentsBuilder.fromCurrentRequest()
+ .path("/{id}")
+ .buildAndExpand(group.getId())
+ .encode()
+ .toUri();
+
+ return ResponseEntity.created(location).body(group);
+ }
+
+ @PutMapping("/groups/{groupId}")
+ @Operation(
+ summary = "Update Group",
+ description = "Updates an existing group with the given ID",
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ required = true,
+ content = @Content(
+ schemaProperties = {
+ @SchemaProperty(
+ name = "name",
+ schema = @Schema(
+ type = "string",
+ description = "Group Name"
+ )
+ ),
+ @SchemaProperty(
+ name = "description",
+ schema = @Schema(
+ type = "string",
+ description = "Group Description"
+ )
+ ),
+ @SchemaProperty(
+ name = "attributes",
+ array = @ArraySchema(
+ schema = @Schema(implementation = GroupAttribute.class),
+ arraySchema = @Schema(description = "List of Group Attributes")
+ )
+ ),
+ @SchemaProperty(
+ name = "realm_roles",
+ array = @ArraySchema(
+ schema = @Schema(implementation = String.class),
+ arraySchema = @Schema(description = "List of Realm Roles")
+ )
+ ),
+ @SchemaProperty(
+ name = "client_roles",
+ array = @ArraySchema(
+ schema = @Schema(implementation = String.class),
+ arraySchema = @Schema(description = "List of Client Roles")
+ )
+ )
+ }
+ )
+ ),
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group update request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "groupId",
+ in = ParameterIn.PATH,
+ description = "The ID of the group to update",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Group updated successfully", content = @Content(schema = @Schema(implementation = Group.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "404", description = "When the associated Group cannot be found", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<Group> updateGroup(@PathVariable("groupId") String groupId, @RequestBody Group request, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ GroupRequest groupRequest = GroupRequest.newBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .setPerformedBy(authClaim.getPerformedBy() != null ? authClaim.getPerformedBy() : Constants.SYSTEM)
+ .setGroup(request.toBuilder().setId(groupId).build())
+ .build();
+
+ Group updatedGroup = groupManagementService.updateGroup(groupRequest);
+ return ResponseEntity.ok(updatedGroup);
+
+ }
+
+ @DeleteMapping("/groups/{groupId}")
+ @Operation(
+ summary = "Delete Group",
+ description = "Deletes an existing group with the given ID",
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group deletion request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "groupId",
+ in = ParameterIn.PATH,
+ description = "The ID of the group to delete",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(responseCode = "204", description = "Group deleted successfully"),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "404", description = "When the associated Group cannot be found", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<?> deleteGroup(@PathVariable("groupId") String groupId, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ GroupRequest groupRequest = GroupRequest.newBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .setPerformedBy(authClaim.getPerformedBy() != null ? authClaim.getPerformedBy() : Constants.SYSTEM)
+ .setGroup(Group.newBuilder().setId(groupId).build())
+ .build();
+
+ groupManagementService.deleteGroup(groupRequest);
+ return ResponseEntity.noContent().build();
+ }
+
+ @GetMapping("/groups/{groupId}")
+ @Operation(
+ summary = "Get Group by ID",
+ description = "Retrieves a group with the given ID",
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group retrieval request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "groupId",
+ in = ParameterIn.PATH,
+ description = "The ID of the group to retrieve",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Group found successfully", content = @Content(schema = @Schema(implementation = Group.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "404", description = "When the Group cannot be found", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<Group> findGroup(@PathVariable("groupId") String groupId, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ GroupRequest groupRequest = GroupRequest.newBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .setPerformedBy(authClaim.getPerformedBy() != null ? authClaim.getPerformedBy() : Constants.SYSTEM)
+ .setGroup(Group.newBuilder().setId(groupId).build())
+ .build();
+
+ Group group = groupManagementService.findGroup(groupRequest);
+ return ResponseEntity.ok(group);
+ }
+
+ @GetMapping("/groups")
+ @Operation(
+ summary = "Get All Groups (with Search)",
+ description = "Retrieves a list of groups based on search criteria. Supports pagination.",
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group retrieval request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "name",
+ in = ParameterIn.QUERY,
+ description = "Filter by group name (partial match)",
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "description",
+ in = ParameterIn.QUERY,
+ description = "Filter by group description (partial match)",
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "id",
+ in = ParameterIn.QUERY,
+ description = "Filter by group ID",
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "created_time",
+ in = ParameterIn.QUERY,
+ description = "Filter by groups created on or after this timestamp (milliseconds since epoch)",
+ schema = @Schema(type = "integer", format = "int64")
+ ),
+ @Parameter(
+ name = "last_modified_time",
+ in = ParameterIn.QUERY,
+ description = "Filter by groups modified on or after this timestamp (milliseconds since epoch)",
+ schema = @Schema(type = "integer", format = "int64")
+ ),
+ @Parameter(
+ name = "offset",
+ in = ParameterIn.QUERY,
+ description = "Pagination offset (start index)",
+ schema = @Schema(type = "integer", defaultValue = "0")
+ ),
+ @Parameter(
+ name = "limit",
+ in = ParameterIn.QUERY,
+ description = "Maximum number of groups to return",
+ schema = @Schema(type = "integer", defaultValue = "20")
+ )
+ },
+ responses = {
+ @ApiResponse(
+ responseCode = "200",
+ description = "Groups retrieved successfully",
+ content = @Content(schema = @Schema(implementation = GetAllGroupsResponse.class))
+ ),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<GetAllGroupsResponse> searchGroups(
+ @RequestParam(name = "name", defaultValue = "", required = false) String name,
+ @RequestParam(name = "description", defaultValue = "", required = false) String description,
+ @RequestParam(name = "id", defaultValue = "", required = false) String id,
+ @RequestParam(name = "created_time", defaultValue = "0", required = false) Long createdTime,
+ @RequestParam(name = "last_modified_time", defaultValue = "0", required = false) Long lastModifiedTime,
+ @RequestParam(name = "offset", defaultValue = "0") int offset,
+ @RequestParam(name = "limit", defaultValue = "20") int limit,
+ @RequestHeader HttpHeaders headers) {
+
+ AuthClaim authClaim = authorize(headers);
+ Group group = Group.newBuilder()
+ .setId(id)
+ .setName(name)
+ .setDescription(description)
+ .setCreatedTime(createdTime)
+ .setLastModifiedTime(lastModifiedTime)
+ .build();
+
+ GroupRequest groupRequest = GroupRequest.newBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .setPerformedBy(authClaim.getPerformedBy() != null ? authClaim.getPerformedBy() : Constants.SYSTEM)
+ .setGroup(group)
+ .setOffset(offset)
+ .setLimit(limit)
+ .build();
+
+ GetAllGroupsResponse groups = groupManagementService.getAllGroups(groupRequest);
+ return ResponseEntity.ok(groups);
+ }
+
+ @DeleteMapping("/groups/{groupId}/members/{userId}")
+ @Operation(
+ summary = "Remove User from Group",
+ description = "Removes a user from an existing group. If the user is the group owner, an error will be thrown.",
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the user removal request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "groupId",
+ in = ParameterIn.PATH,
+ description = "The ID of the group where to remove the user",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "userId",
+ in = ParameterIn.PATH,
+ description = "ID of the User to be removed from the group",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(responseCode = "204", description = "User successfully removed from group"),
+ @ApiResponse(responseCode = "400", description = "Bad Request - Cannot remove the default owner"),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request"),
+ @ApiResponse(responseCode = "404", description = "Group or user not found"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error")
+ }
+ )
+ public ResponseEntity<?> removeUserFromGroup(@PathVariable("groupId") String groupId, @PathVariable("userId") String userId, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ GroupMembership request = GroupMembership.newBuilder()
+ .setGroupId(groupId)
+ .setUsername(userId)
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .build();
+ Status status = groupManagementService.removeUserFromGroup(request);
+ return status.getStatus() ? ResponseEntity.noContent().build() : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("USER_REMOVAL_FAILED");
+
+ }
+
+ @PostMapping("/groups/{groupId}/members")
+ @Operation(
+ summary = "Add User to Group",
+ description = "Adds an existing user to an existing group. If the user is already a member of the group, the request is considered successful.",
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ description = "Group membership details",
+ required = true,
+ content = @Content(
+ schemaProperties = {
+ @SchemaProperty(
+ name = "username",
+ schema = @Schema(
+ type = "string",
+ description = "Username"
+ )
+ ),
+ @SchemaProperty(
+ name = "type",
+ schema = @Schema(
+ implementation = DefaultGroupMembershipTypes.class,
+ description = "Type of the user"
+ )
+ )
+ }
+ )
+ ),
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the user addition request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "groupId",
+ in = ParameterIn.PATH,
+ description = "The ID of the group to add the user",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(responseCode = "200", description = "User successfully added to the group (or was already a member)"),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request"),
+ @ApiResponse(responseCode = "404", description = "Group or user not found"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error")
+ }
+ )
+ public ResponseEntity<Status> addUserToGroup(@PathVariable("groupId") String groupId, @RequestBody GroupMembership request, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ request = request.toBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .setGroupId(groupId)
+ .build();
+ org.apache.custos.core.user.profile.api.Status status = groupManagementService.addUserToGroup(request);
+ return ResponseEntity.ok(status);
+ }
+
+ @PostMapping("/groups/{parentId}/children")
+ @Operation(
+ summary = "Add Child Group to Parent Group",
+ description = "Establishes a parent-child relationship between two existing groups. If the relationship already exists, the request is considered successful.",
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ description = "Group-to-group membership details",
+ required = true,
+ content = @Content(
+ schemaProperties = {
+ @SchemaProperty(
+ name = "child_id",
+ schema = @Schema(
+ type = "string",
+ description = "Child Group ID"
+ )
+ )
+ }
+ )
+ ),
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group relationship creation request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "parentId",
+ in = ParameterIn.PATH,
+ description = "The ID of the parent group to which the child group will be added",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Child group successfully added to parent group (or relationship already existed)"),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request"),
+ @ApiResponse(responseCode = "404", description = "Child or parent group not found"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error")
+ }
+ )
+ public ResponseEntity<Status> addChildGroupToParentGroup(@PathVariable("parentId") String parentGroupId, @RequestBody GroupToGroupMembership request, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ request = request.toBuilder()
+ .setParentId(parentGroupId)
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .build();
+
+ return ResponseEntity.ok(groupManagementService.addChildGroupToParentGroup(request));
+ }
+
+ @DeleteMapping("/groups/{parentId}/children/{childId}")
+ @Operation(
+ summary = "Remove Child Group from Parent Group",
+ description = "Removes the parent-child relationship between two groups. If the relationship does not exist, the request is still considered successful.",
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group relationship removal request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "parentId",
+ in = ParameterIn.PATH,
+ description = "The ID of the parent group",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "childId",
+ in = ParameterIn.PATH,
+ description = "The ID of the child group",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(responseCode = "204", description = "Child group successfully removed from parent group (or relationship did not exist)"),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request"),
+ @ApiResponse(responseCode = "404", description = "Child or parent group not found"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error")
+ }
+ )
+ public ResponseEntity<?> removeChildGroupFromParentGroup(@PathVariable("parentId") String parentId, @PathVariable("childId") String childId, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ GroupToGroupMembership groupRequest = GroupToGroupMembership.newBuilder()
+ .setParentId(parentId)
+ .setChildId(childId)
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .build();
+
+ Status status = groupManagementService.removeChildGroupFromParentGroup(groupRequest);
+ return status.getStatus() ? ResponseEntity.noContent().build() : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("CHILD_GROUP_REMOVAL_FAILED");
+
+ }
+
+ @GetMapping("/users/{userId}/group-memberships")
+ @Operation(
+ summary = "Get All Groups of a User",
+ description = "Retrieves all groups that a user is a member of",
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group retrieval request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "userId",
+ in = ParameterIn.PATH,
+ description = "User ID",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(
+ responseCode = "200",
+ description = "Groups retrieved successfully",
+ content = @Content(schema = @Schema(implementation = GetAllGroupsResponse.class))
+ ),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request"),
+ @ApiResponse(responseCode = "404", description = "User not found"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error")
+ }
+ )
+ public ResponseEntity<GetAllGroupsResponse> getAllGroupsOfUser(@PathVariable("userId") String username, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ UserProfileRequest request = UserProfileRequest.newBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setProfile(UserProfile.newBuilder().setUsername(username).build())
+ .build();
+ GetAllGroupsResponse response = groupManagementService.getAllGroupsOfUser(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/groups/{groupId}/parents")
+ @Operation(
+ summary = "Get All Parent Groups of a Group",
+ description = "Retrieves all parent groups of the specified group.",
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group retrieval request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "groupId",
+ in = ParameterIn.PATH,
+ description = "The ID of the group for which to retrieve parent groups",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(
+ responseCode = "200",
+ description = "Parent groups retrieved successfully",
+ content = @Content(schema = @Schema(implementation = GetAllGroupsResponse.class))
+ ),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request"),
+ @ApiResponse(responseCode = "404", description = "Group not found"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error")
+ }
+ )
+ public ResponseEntity<GetAllGroupsResponse> getAllParentGroupsOfGroup(@PathVariable("groupId") String groupId, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ GroupRequest groupRequest = GroupRequest.newBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setGroup(Group.newBuilder().setId(groupId).build())
+ .build();
+
+ GetAllGroupsResponse response = groupManagementService.getAllParentGroupsOfGroup(groupRequest);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/groups/{groupId}/members")
+ @Operation(
+ summary = "Get All Users of a Group",
+ description = "Retrieves all users who are members of the specified group",
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the user retrieval request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "groupId",
+ in = ParameterIn.PATH,
+ description = "The ID of the group for which to retrieve child users",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(
+ responseCode = "200",
+ description = "Child users retrieved successfully",
+ content = @Content(schema = @Schema(implementation = GetAllUserProfilesResponse.class))
+ ),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request"),
+ @ApiResponse(responseCode = "404", description = "Group not found"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error")
+ }
+ )
+ public ResponseEntity<GetAllUserProfilesResponse> getAllChildUsers(@PathVariable("groupId") String groupId, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ GroupRequest groupRequest = GroupRequest.newBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setGroup(Group.newBuilder().setId(groupId).build())
+ .build();
+
+ GetAllUserProfilesResponse response = groupManagementService.getAllChildUsers(groupRequest);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/groups/{groupId}/children")
+ @Operation(
+ summary = "Get All Child Groups of a Group",
+ description = "Retrieves all child groups of the specified group",
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group retrieval request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "groupId",
+ in = ParameterIn.PATH,
+ description = "The ID of the parent group for which to retrieve child groups",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(
+ responseCode = "200",
+ description = "Child groups retrieved successfully",
+ content = @Content(schema = @Schema(implementation = GetAllGroupsResponse.class))
+ ),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request"),
+ @ApiResponse(responseCode = "404", description = "Group not found"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error")
+ }
+ )
+ public ResponseEntity<GetAllGroupsResponse> getAllChildGroups(@PathVariable("groupId") String groupId, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ GroupRequest groupRequest = GroupRequest.newBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setGroup(Group.newBuilder().setId(groupId).build())
+ .build();
+
+ GetAllGroupsResponse response = groupManagementService.getAllChildGroups(groupRequest);
+ return ResponseEntity.ok(response);
+ }
+
+ @PutMapping("/groups/{groupId}/members/{userId}")
+ @Operation(
+ summary = "Change User Membership Type",
+ description = "Changes the membership type of a user within a group. Only one owner can exist within a group, " +
+ "and the default owner cannot have their membership type changed.",
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ description = "Group membership details for updating the membership type",
+ required = true,
+ content = @Content(
+ schemaProperties = {
+ @SchemaProperty(
+ name = "group_id",
+ schema = @Schema(
+ type = "string",
+ description = "The ID of the group to which the user should be added"
+ )
+ ),
+ @SchemaProperty(
+ name = "username",
+ schema = @Schema(
+ type = "string",
+ description = "Username"
+ )
+ ),
+ @SchemaProperty(
+ name = "type",
+ schema = @Schema(
+ implementation = DefaultGroupMembershipTypes.class,
+ description = "Type of the user"
+ )
+ )
+ }
+ )
+ ),
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the membership type change request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "groupId",
+ in = ParameterIn.PATH,
+ description = "ID of the group where the user membership type should be changed",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "userId",
+ in = ParameterIn.PATH,
+ description = "User ID",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Membership type changed successfully"),
+ @ApiResponse(responseCode = "400", description = "Bad Request - Cannot change default owner's type or invalid type"),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request"),
+ @ApiResponse(responseCode = "404", description = "Group membership not found"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error")
+ }
+ )
+ public ResponseEntity<?> changeUserMembershipType(@PathVariable("groupId") String groupId, @PathVariable("userId") String userId, @RequestBody GroupMembership request, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ request = request.toBuilder()
+ .setGroupId(groupId)
+ .setUsername(userId)
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .build();
+ Status status = groupManagementService.changeUserMembershipType(request);
+ return status.getStatus() ? ResponseEntity.ok(status) : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("USER_MEMBERSHIP_TYPE_CHANGED_FAILED");
+ }
+
+ @GetMapping("/groups/{groupId}/members/{userId}/access")
+ @Operation(
+ summary = "Check User Group Access",
+ description = "Checks if a user has a specific type of access within a group",
+ parameters = {
+ @Parameter(
+ name = "userId",
+ in = ParameterIn.PATH,
+ description = "Username of the user",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "groupId",
+ in = ParameterIn.PATH,
+ description = "Group ID",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the access check request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "type",
+ in = ParameterIn.QUERY,
+ description = "Type of membership (e.g., MEMBER, OWNER, or ADMIN)",
+ required = true,
+ schema = @Schema(implementation = DefaultGroupMembershipTypes.class)
+ )
+ },
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Access check result", content = @Content(schema = @Schema(implementation = Status.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error")
+ }
+ )
+ public ResponseEntity<Status> hasAccess(@PathVariable("groupId") String groupId, @PathVariable("userId") String username, @RequestParam String type, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ GroupMembership request = GroupMembership.newBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setUsername(username)
+ .setGroupId(groupId)
+ .setType(type)
+ .build();
+ Status status = groupManagementService.hasAccess(request);
+ return ResponseEntity.ok(status);
+ }
+
+ @PostMapping("/group-membership-types")
+ @Operation(
+ summary = "Add Group Membership Type",
+ description = "Adds a new group membership type. If the type already exists, the request is considered successful.",
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ description = "Group membership type",
+ required = true,
+ content = @Content(
+ schemaProperties = {
+ @SchemaProperty(
+ name = "type",
+ schema = @Schema(
+ type = "string",
+ description = "Type of the user"
+ )
+ )
+ }
+ )
+ ),
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group membership type creation request",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Group membership type successfully added (or already existed)"),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error")
+ }
+ )
+ public ResponseEntity<Status> addGroupMembershipType(@RequestBody UserGroupMembershipTypeRequest request, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ request = request.toBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .build();
+ Status status = groupManagementService.addGroupMembershipType(request);
+ return ResponseEntity.ok(status);
+ }
+
+ @DeleteMapping("/group-membership-types/{type}")
+ @Operation(
+ summary = "Remove Group Membership Type",
+ description = "Removes an existing group membership type. If the type does not exist or if it is used by existing group memberships, the request will fail.",
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group membership type removal request",
+ required = true,
+ schema = @Schema(type = "string")
+ ),
+ @Parameter(
+ name = "type",
+ in = ParameterIn.PATH,
+ description = "The type of group membership to remove",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ },
+ responses = {
+ @ApiResponse(responseCode = "204", description = "Group membership type successfully removed"),
+ @ApiResponse(responseCode = "400", description = "Bad Request - Cannot remove default membership types (MEMBER, OWNER, ADMIN) or if the type is in use"),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request"),
+ @ApiResponse(responseCode = "404", description = "Group membership type not found"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error")
+ }
+ )
+ public ResponseEntity<?> removeUserGroupMembershipType(@PathVariable("type") String type, @RequestHeader HttpHeaders headers) {
+ AuthClaim authClaim = authorize(headers);
+ UserGroupMembershipTypeRequest request = UserGroupMembershipTypeRequest.newBuilder()
+ .setType(type)
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .build();
+ Status status = groupManagementService.removeUserGroupMembershipType(request);
+ return status.getStatus() ? ResponseEntity.noContent().build() : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("GROUP_MEMBERSHIP_REMOVAL_FAILED");
+ }
+
+ private AuthClaim authorize(@RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, headers.getFirst("client_id"));
+ if (claim.isEmpty()) {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ return claim.get();
+ }
+
+}
diff --git a/api/src/main/java/org/apache/custos/api/identity/IdentityManagementController.java b/api/src/main/java/org/apache/custos/api/identity/IdentityManagementController.java
new file mode 100644
index 000000000..c246eef04
--- /dev/null
+++ b/api/src/main/java/org/apache/custos/api/identity/IdentityManagementController.java
@@ -0,0 +1,606 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.custos.api.identity;
+
+import com.nimbusds.jose.jwk.JWK;
+import com.nimbusds.jose.jwk.KeyUse;
+import com.nimbusds.jose.jwk.RSAKey;
+import org.apache.custos.core.credential.store.api.Credentials;
+import org.apache.custos.core.identity.api.AuthToken;
+import org.apache.custos.core.identity.api.AuthenticationRequest;
+import org.apache.custos.core.identity.api.Claim;
+import org.apache.custos.core.identity.api.GetOIDCConfiguration;
+import org.apache.custos.core.identity.api.GetTokenRequest;
+import org.apache.custos.core.identity.api.GetUserManagementSATokenRequest;
+import org.apache.custos.core.identity.api.IsAuthenticatedResponse;
+import org.apache.custos.core.identity.api.OIDCConfiguration;
+import org.apache.custos.core.identity.api.OperationStatus;
+import org.apache.custos.core.identity.api.TokenResponse;
+import org.apache.custos.core.identity.api.User;
+import org.apache.custos.core.identity.management.api.AuthorizationRequest;
+import org.apache.custos.core.identity.management.api.AuthorizationResponse;
+import org.apache.custos.core.identity.management.api.EndSessionRequest;
+import org.apache.custos.core.identity.management.api.GetCredentialsRequest;
+import org.apache.custos.service.auth.AuthClaim;
+import org.apache.custos.service.auth.KeyLoader;
+import org.apache.custos.service.auth.TokenAuthorizer;
+import org.apache.custos.service.credential.store.Credential;
+import org.apache.custos.service.credential.store.CredentialManager;
+import org.apache.custos.service.management.IdentityManagementService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.Parameter;
+import io.swagger.v3.oas.annotations.media.ArraySchema;
+import io.swagger.v3.oas.annotations.media.Content;
+import io.swagger.v3.oas.annotations.media.Schema;
+import io.swagger.v3.oas.annotations.media.SchemaProperty;
+import io.swagger.v3.oas.annotations.responses.ApiResponse;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.apache.commons.lang3.StringUtils;
+import org.json.JSONObject;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.server.ResponseStatusException;
+
+import java.net.URI;
+import java.security.KeyPair;
+import java.security.interfaces.RSAPublicKey;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+
+@RestController
+@RequestMapping("/api/v1/identity-management")
+@Tag(name = "Identity Management")
+public class IdentityManagementController {
+
+ private final IdentityManagementService identityManagementService;
+ private final TokenAuthorizer tokenAuthorizer;
+ private final KeyLoader keyLoader;
+
+ public IdentityManagementController(IdentityManagementService identityManagementService, TokenAuthorizer tokenAuthorizer, KeyLoader keyLoader) {
+ this.identityManagementService = identityManagementService;
+ this.tokenAuthorizer = tokenAuthorizer;
+ this.keyLoader = keyLoader;
+ }
+
+ @PostMapping("/authenticate")
+ @Operation(
+ summary = "User Authentication",
+ description = "Authenticates the user by verifying the provided request credentials. If authenticated successfully, " +
+ "returns an AuthToken which includes authentication details and associated claims.",
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ required = true,
+ content = @Content(
+ schemaProperties = {
+ @SchemaProperty(
+ name = "username",
+ schema = @Schema(
+ type = "string",
+ description = "The user's username"
+ )
+ ),
+ @SchemaProperty(
+ name = "password",
+ schema = @Schema(
+ type = "string",
+ description = "The user's password"
+ )
+ )
+ }
+ )
+ ),
+ responses = {
+ @io.swagger.v3.oas.annotations.responses.ApiResponse(
+ responseCode = "200",
+ description = "Successful operation",
+ content = @Content(
+ schemaProperties = {
+ @SchemaProperty(
+ name = "access_token",
+ schema = @Schema(
+ type = "string",
+ description = "Access Token"
+ )
+ ),
+ @SchemaProperty(
+ name = "claims",
+ array = @ArraySchema(
+ schema = @Schema(implementation = Claim.class),
+ arraySchema = @Schema(description = "List of Claims")
+ )
+ )
+ }
+ )
+ ),
+ @ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = AuthToken.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<AuthToken> authenticate(@RequestBody AuthenticationRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers);
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ request.toBuilder().setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSecret(authClaim.getIamAuthSecret());
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ AuthToken response = identityManagementService.authenticate(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/authenticate/status")
+ @Operation(
+ summary = "Authentication Status Check",
+ description = "Checks the authentication status based on the provided AuthToken. Returns an IsAuthenticatedResponse portraying the status.",
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ required = true,
+ content = @Content(
+ schemaProperties = {
+ @SchemaProperty(
+ name = "access_token",
+ schema = @Schema(
+ type = "string",
+ description = "Access Token"
+ )
+ ),
+ @SchemaProperty(
+ name = "claims",
+ array = @ArraySchema(
+ schema = @Schema(implementation = Claim.class),
+ arraySchema = @Schema(description = "List of Claims")
+ )
+ )
+ }
+ )
+ ),
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = Boolean.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<Boolean> isAuthenticated(@RequestBody AuthToken request, @RequestHeader HttpHeaders headers) {
+ IsAuthenticatedResponse response = identityManagementService.isAuthenticated(generateAuthTokenRequest(request.toBuilder(), headers).build());
+ return ResponseEntity.ok(response.getAuthenticated());
+ }
+
+ @GetMapping("/user")
+ @Operation(
+ summary = "Retrieve User Information",
+ description = "Retrieves User Information using the provided access token. Returns a User object containing user details.",
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = User.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<User> getUser(@Parameter(description = "Access Token used for authentication", required = true)
+ @RequestParam("access_token") String accessToken, @RequestHeader HttpHeaders headers) {
+ AuthToken.Builder builder = AuthToken.newBuilder().setAccessToken(accessToken);
+ User response = identityManagementService.getUser(generateAuthTokenRequest(builder, headers).build());
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/account/token")
+ @Operation(
+ summary = "Get User Management Service Account Access Token",
+ description = "Retrieves the User Management Service Account Access Token using the provided GetUserManagementSATokenRequest. " +
+ "Returns an AuthToken for the user management service account.",
+ responses = {
+ @io.swagger.v3.oas.annotations.responses.ApiResponse(
+ responseCode = "200",
+ description = "Successful operation",
+ content = @Content(
+ schemaProperties = {
+ @SchemaProperty(
+ name = "access_token",
+ schema = @Schema(
+ type = "string",
+ description = "Access Token"
+ )
+ ),
+ @SchemaProperty(
+ name = "claims",
+ array = @ArraySchema(
+ schema = @Schema(implementation = Claim.class),
+ arraySchema = @Schema(description = "List of Claims")
+ )
+ )
+ }
+ )
+ ),
+ @ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = AuthToken.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<AuthToken> getUserManagementServiceAccountAccessToken(
+ @RequestParam(value = "client_id", required = false) String clientId,
+ @RequestParam(value = "client_secret", required = false) String clientSecret,
+ @RequestParam(value = "tenant_id", required = false) String tenantId,
+ @RequestHeader HttpHeaders headers) {
+
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers);
+ GetUserManagementSATokenRequest.Builder builder = GetUserManagementSATokenRequest.newBuilder();
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ builder.setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSecret(authClaim.getIamAuthSecret());
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ AuthToken response = identityManagementService.getUserManagementServiceAccountAccessToken(builder.build());
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/user/logout")
+ @Operation(
+ summary = "End User Session",
+ description = "Ends the user session based on the provided EndSessionRequest. " +
+ "Returns an OperationStatus response confirming the action.",
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ required = true,
+ content = @Content(
+ mediaType = "application/json",
+ schemaProperties = {
+ @SchemaProperty(
+ name = "refresh_token",
+ schema = @Schema(
+ type = "string",
+ description = "Refresh Token"
+ )
+ )
+ }
+ )
+ ),
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = Boolean.class))),
+ @ApiResponse(responseCode = "400", description = "Invalid request", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<Boolean> endUserSession(@RequestBody Map<String, String> requestData, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers);
+ String refreshToken = requestData.get("refresh_token");
+ if (refreshToken == null || refreshToken.isBlank()) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing or empty refresh_token");
+ }
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ org.apache.custos.core.identity.api.EndSessionRequest endSessionRequest = org.apache.custos.core.identity.api.EndSessionRequest.newBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSecret(authClaim.getIamAuthSecret())
+ .setRefreshToken(refreshToken)
+ .build();
+ EndSessionRequest request = EndSessionRequest.newBuilder().setBody(endSessionRequest).build();
+ OperationStatus response = identityManagementService.endUserSession(request);
+
+ return ResponseEntity.ok(response.getStatus());
+
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+ }
+
+ @GetMapping("/authorize")
+ @Operation(
+ summary = "Authorize User",
+ description = "Authorizes the user by verifying the provided AuthorizationRequest. If authorized, an AuthorizationResponse is returned.",
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = AuthorizationResponse.class))),
+ @ApiResponse(responseCode = "400", description = "Invalid request", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<?> authorize(
+ @RequestParam(value = "client_id") String clientId,
+ @RequestParam(value = "redirect_uri") String redirectUri,
+ @RequestParam(value = "scope") String scope,
+ @RequestParam(value = "state") String state,
+ @RequestParam(value = "response_type") String responseType,
+ @RequestParam(value = "code_challenge", required = false) String codeChallenge,
+ @RequestParam(value = "code_challenge_method", required = false) String codeChallengeMethod) {
+
+ AuthorizationRequest request = AuthorizationRequest.newBuilder()
+ .setClientId(clientId)
+ .setRedirectUri(redirectUri)
+ .setScope(scope)
+ .setState(state)
+ .setResponseType(responseType)
+ .setCodeChallenge(StringUtils.isNotBlank(codeChallenge) ? codeChallenge : "")
+ .setCodeChallengeMethod(StringUtils.isNotBlank(codeChallengeMethod) ? codeChallengeMethod : "")
+ .build();
+ AuthorizationResponse response = identityManagementService.authorize(request);
+ return ResponseEntity.status(HttpStatus.FOUND).location(URI.create(response.getRedirectUri())).build();
+ }
+
+ @PostMapping(value = "/token", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
+ @Operation(
+ summary = "Get Token",
+ description = "Retrieves a token based on the provided request. For basic authentication, use 'user_name' and 'password'; for authorization code grant flow, use 'code'. If successful, returns a TokenResponse.",
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ required = true,
+ content = @Content(
+ mediaType = "application/json",
+ schemaProperties = {
+ @SchemaProperty(
+ name = "code",
+ schema = @Schema(
+ type = "string",
+ description = "Authorization Code",
+ example = "wsxdcfvgbg"
+ )
+ ),
+ @SchemaProperty(
+ name = "redirect_uri",
+ schema = @Schema(
+ type = "string",
+ description = "Redirect URI",
+ example = "https://domain/callback"
+ )
+ ),
+ @SchemaProperty(
+ name = "grant_type",
+ schema = @Schema(
+ type = "string",
+ description = "Grant Type",
+ example = "authorization_code"
+ )
+ ),
+ @SchemaProperty(
+ name = "username",
+ schema = @Schema(
+ type = "string",
+ description = "User Name"
+ )
+ ),
+ @SchemaProperty(
+ name = "password",
+ schema = @Schema(
+ type = "string",
+ description = "User's password"
+ )
+ )
+ }
+ )
+ ),
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = TokenResponse.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "404", description = "When the associated Tenant cannot be found", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<?> token(@RequestParam Map<String, String> params, @RequestHeader HttpHeaders headers) {
+ // Expects the Base64 encoded value 'clientId:clientSecret' for Authorization Header
+ //Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers);
+
+ /*if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ request = request.toBuilder().setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSecret(authClaim.getIamAuthSecret())
+ .build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }*/
+
+ boolean isPKCEFlow = params.containsKey("code_verifier");
+ if (!isPKCEFlow && !(headers.containsKey("authorization") || params.containsKey("client_secret"))) {
+ return ResponseEntity.badRequest().body("No client id and secret or code_verifier is provided in the request");
+ }
+
+ Credential credential;
+ if (isPKCEFlow) {
+ // If PKCE flow, only get the client ID
+ credential = new Credential(params.get("client_id"), "");
+ } else {
+ if (headers.containsKey("authorization") && headers.getFirst("authorization") != null) {
+ String authorizationHeader = headers.get("authorization").get(0);
+ if (!authorizationHeader.startsWith("Basic")) {
+ return ResponseEntity.badRequest().body("Expecting a basic auth type auth header");
+ }
+
+ credential = CredentialManager.decodeToken(authorizationHeader.substring("Basic ".length()));
+ } else {
+ credential = new Credential(params.get("client_id"), params.get("client_secret"));
+ }
+
+ if (credential == null) {
+ return ResponseEntity.badRequest().body("Credentials were provided in incorrect format. Is should be 'Basic base64(client_id:client_secret)'");
+ }
+ }
+
+ // TODO : Validate key availability in params redirect_uri, code, grant_type
+ GetTokenRequest request = GetTokenRequest.newBuilder()
+ .setRedirectUri(params.get("redirect_uri"))
+ .setCode(params.get("code"))
+ .setCodeVerifier(params.getOrDefault("code_verifier", ""))
+ .setGrantType(params.get("grant_type"))
+ .setClientId(credential.getId())
+ .setTenantId(Long.parseLong(credential.getId().split("-")[2])) // TODO This is very risky. Find a different way to figure out tenant id
+ .setClientSecret(credential.getSecret()).build();
+
+ TokenResponse response = identityManagementService.token(request);
+ System.out.println("customized token \n");
+ System.out.println(response.getAccessToken());
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/credentials")
+ @Operation(
+ summary = "Get Credentials",
+ description = "Retrieves credentials based on the provided client_id. Returns a Credentials object.",
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = Credentials.class))),
+ @ApiResponse(responseCode = "400", description = "Invalid request", content = @Content()),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<Credentials> getCredentials(@RequestParam(value = "client_id") String clientId, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, clientId);
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ Credentials credentials = Credentials.newBuilder()
+ .setCustosClientId(authClaim.getCustosId())
+ .setCustosClientSecret(authClaim.getCustosSecret())
+ .setCustosClientIdIssuedAt(authClaim.getCustosIdIssuedAt())
+ .setCustosClientSecretExpiredAt(authClaim.getCustosSecretExpiredAt())
+ .setCiLogonClientId(authClaim.getCiLogonId())
+ .setCiLogonClientSecret(authClaim.getCiLogonSecret())
+ .setIamClientId(authClaim.getIamAuthId())
+ .setIamClientSecret(authClaim.getIamAuthSecret())
+ .build();
+ GetCredentialsRequest request = GetCredentialsRequest.newBuilder().setCredentials(credentials).build();
+ Credentials response = identityManagementService.getCredentials(request);
+ return ResponseEntity.ok(response);
+
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+ }
+
+ @GetMapping("/.well-known/openid-configuration")
+ @Operation(
+ summary = "Get OIDC Configuration",
+ description = "Retrieves the OpenID Connect (OIDC) configuration using the provided GetOIDCConfiguration request. " +
+ "Returns an OIDCConfiguration object.",
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = OIDCConfiguration.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "404", description = "When the associated Tenant or Credentials cannot be found", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<OIDCConfiguration> getOIDCConfiguration(@RequestParam(value = "client_id") String clientId) {
+ GetOIDCConfiguration request = GetOIDCConfiguration.newBuilder()
+ .setClientId(clientId)
+ .build();
+ OIDCConfiguration response = identityManagementService.getOIDCConfiguration(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/.well-known/jwks.json")
+ public ResponseEntity<?> keys() {
+ KeyPair keyPair = keyLoader.getKeyPair();
+ RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
+
+ JWK jwk = new RSAKey.Builder(rsaPublicKey)
+ .keyID(keyLoader.getKeyID())
+ .keyUse(KeyUse.SIGNATURE)
+ .build();
+
+ Map<String, Object> jwkMap = Map.of(
+ "kty", "RSA",
+ "alg", "RS256",
+ "use", "sig",
+ "kid", jwk.getKeyID(),
+ "n", Base64.getUrlEncoder().withoutPadding().encodeToString(rsaPublicKey.getModulus().toByteArray()),
+ "e", Base64.getUrlEncoder().withoutPadding().encodeToString(rsaPublicKey.getPublicExponent().toByteArray()),
+ "x5c", Collections.singletonList(Base64.getUrlEncoder().withoutPadding().encodeToString(rsaPublicKey.getEncoded()))
+ );
+
+ return ResponseEntity.ok(Map.of("keys", Collections.singletonList(jwkMap)));
+ }
+
+ @PostMapping("/token/introspect")
+ @Operation(
+ summary = "Introspect Token",
+ description = "Validates and provides information about the provided access token.",
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ required = true,
+ content = @Content(
+ mediaType = "application/x-www-form-urlencoded",
+ schemaProperties = {
+ @SchemaProperty(
+ name = "token",
+ schema = @Schema(
+ type = "string",
+ description = "The access token to introspect"
+ )
+ )
+ }
+ )
+ ),
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Successful introspection"),
+ @ApiResponse(responseCode = "400", description = "Invalid request"),
+ @ApiResponse(responseCode = "401", description = "Unauthorized client")
+ }
+ )
+ public ResponseEntity<?> introspectToken(@RequestParam Map<String, String> params) {
+ if (params.containsKey("client_id") && params.containsKey("client_secret") && params.containsKey("token")) {
+ JSONObject response = identityManagementService.introspectToken(params.get("client_id"), params.get("client_secret"),
+ String.valueOf(params.get("client_id").split("-")[2]), params.get("token"));
+
+ return ResponseEntity.ok(response.toMap());
+
+ } else {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing required client_id, client_secret, or token params");
+ }
+ }
+
+
+ private AuthToken.Builder generateAuthTokenRequest(AuthToken.Builder builder, HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers);
+ if (claim.isEmpty()) {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ Optional<AuthClaim> opAuthClaim = tokenAuthorizer.authorizeUsingUserToken(builder.getAccessToken());
+
+ if (opAuthClaim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ Claim userClaim = Claim.newBuilder().setKey("username").setValue(authClaim.getUsername()).build();
+ Claim tenantClaim = Claim.newBuilder().setKey("tenantId").setValue(String.valueOf(authClaim.getTenantId())).build();
+ Claim clientClaim = Claim.newBuilder().setKey("clientId").setValue(String.valueOf(authClaim.getCustosId())).build();
+
+ builder.addClaims(userClaim);
+ builder.addClaims(tenantClaim);
+ builder.addClaims(clientClaim);
+
+ return builder;
+
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized, User token not found");
+ }
+ }
+}
diff --git a/api/src/main/java/org/apache/custos/api/tenant/TenantManagementController.java b/api/src/main/java/org/apache/custos/api/tenant/TenantManagementController.java
new file mode 100644
index 000000000..05691ada1
--- /dev/null
+++ b/api/src/main/java/org/apache/custos/api/tenant/TenantManagementController.java
@@ -0,0 +1,428 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.custos.api.tenant;
+
+import org.apache.custos.core.credential.store.api.CredentialMetadata;
+import org.apache.custos.core.exception.UnauthorizedException;
+import org.apache.custos.core.federated.authentication.api.CacheManipulationRequest;
+import org.apache.custos.core.federated.authentication.api.GetInstitutionsResponse;
+import org.apache.custos.core.federated.authentication.api.Status;
+import org.apache.custos.core.iam.api.AddProtocolMapperRequest;
+import org.apache.custos.core.iam.api.AddRolesRequest;
+import org.apache.custos.core.iam.api.AllRoles;
+import org.apache.custos.core.iam.api.DeleteRoleRequest;
+import org.apache.custos.core.iam.api.EventPersistenceRequest;
+import org.apache.custos.core.iam.api.GetRolesRequest;
+import org.apache.custos.core.iam.api.OperationStatus;
+import org.apache.custos.core.tenant.management.api.CreateTenantResponse;
+import org.apache.custos.core.tenant.management.api.Credentials;
+import org.apache.custos.core.tenant.management.api.DeleteTenantRequest;
+import org.apache.custos.core.tenant.management.api.GetTenantRequest;
+import org.apache.custos.core.tenant.management.api.TenantValidationRequest;
+import org.apache.custos.core.tenant.management.api.UpdateTenantRequest;
+import org.apache.custos.core.tenant.profile.api.GetAllTenantsForUserRequest;
+import org.apache.custos.core.tenant.profile.api.GetAllTenantsForUserResponse;
+import org.apache.custos.core.tenant.profile.api.GetAllTenantsResponse;
+import org.apache.custos.core.tenant.profile.api.GetAttributeUpdateAuditTrailResponse;
+import org.apache.custos.core.tenant.profile.api.GetAuditTrailRequest;
+import org.apache.custos.core.tenant.profile.api.GetStatusUpdateAuditTrailResponse;
+import org.apache.custos.core.tenant.profile.api.GetTenantsRequest;
+import org.apache.custos.core.tenant.profile.api.Tenant;
+import org.apache.custos.core.tenant.profile.api.UpdateStatusRequest;
+import org.apache.custos.core.tenant.profile.api.UpdateStatusResponse;
+import org.apache.custos.service.auth.AuthClaim;
+import org.apache.custos.service.auth.TokenAuthorizer;
+import org.apache.custos.service.management.TenantManagementService;
+import io.swagger.v3.oas.annotations.Hidden;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import jakarta.validation.Valid;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.DeleteMapping;
+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.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.server.ResponseStatusException;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+@RestController
+@RequestMapping("/api/v1/tenant-management")
+@Tag(name = "Tenant Management")
+public class TenantManagementController {
+
+ private final TenantManagementService tenantManagementService;
+ private final TokenAuthorizer tokenAuthorizer;
+
+
+ public TenantManagementController(TenantManagementService tenantManagementService, TokenAuthorizer tokenAuthorizer) {
+ this.tenantManagementService = tenantManagementService;
+ this.tokenAuthorizer = tokenAuthorizer;
+ }
+
+ @PostMapping("/oauth2/tenant")
+ public ResponseEntity<CreateTenantResponse> createTenant(@Valid @RequestBody Tenant request, @RequestHeader HttpHeaders headers) {
+ String token = tokenAuthorizer.getToken(headers);
+
+ if (StringUtils.isBlank(token)) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers);
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ request = request.toBuilder().setParentTenantId(authClaim.getTenantId()).build();
+ }
+ }
+
+ CreateTenantResponse response = tenantManagementService.createTenant(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/oauth2/tenant")
+ public ResponseEntity<Tenant> getTenant(@Valid @RequestBody GetTenantRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorizeUsingUserToken(headers);
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ Credentials credentials = getCredentials(authClaim);
+
+ request = request.toBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setCredentials(credentials)
+ .build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized, token not found");
+ }
+
+ Tenant response = tenantManagementService.getTenant(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @PutMapping("/user/profile")
+ public ResponseEntity<Tenant> updateTenant(@Valid @RequestBody UpdateTenantRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorizeUsingUserToken(headers);
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ Credentials credentials = getCredentials(authClaim);
+
+ request = request.toBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setCredentials(credentials)
+ .build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized, token not found");
+ }
+
+ Tenant response = tenantManagementService.updateTenant(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @DeleteMapping("/user")
+ public ResponseEntity<?> deleteTenant(@Valid @RequestBody DeleteTenantRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorizeUsingUserToken(headers);
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ Credentials credentials = getCredentials(authClaim);
+
+ request = request.toBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setCredentials(credentials)
+ .build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized, token not found");
+ }
+
+ tenantManagementService.deleteTenant(request);
+ return ResponseEntity.noContent().build();
+ }
+
+ @PostMapping("/tenant/credentials/status")
+ public ResponseEntity<OperationStatus> validateTenant(@Valid @RequestBody TenantValidationRequest request) {
+ OperationStatus response = tenantManagementService.validateTenant(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/roles")
+ public ResponseEntity<AllRoles> addTenantRoles(@Valid @RequestBody AddRolesRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorizeUsingUserToken(headers);
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+
+ if (StringUtils.isBlank(request.getClientId())) {
+ request = request.toBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getCustosId())
+ .build();
+ } else {
+ CredentialMetadata metadata = tokenAuthorizer.getCredentialsFromClientId(request.getClientId());
+ if (authClaim.isSuperTenant() || tokenAuthorizer.validateParentChildTenantRelationShip(authClaim.getTenantId(), metadata.getOwnerId())) {
+ request = request.toBuilder()
+ .setTenantId(metadata.getOwnerId())
+ .build();
+ } else {
+ throw new UnauthorizedException("Request is not authorized, user not authorized with the requested clientId: " + request.getClientId());
+ }
+ }
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized, token not found");
+ }
+
+ AllRoles response = tenantManagementService.addTenantRoles(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/roles")
+ public ResponseEntity<AllRoles> getTenantRoles(@Valid @RequestBody GetRolesRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorizeUsingUserToken(headers);
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+
+ if (StringUtils.isBlank(request.getClientId())) {
+ request = request.toBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getCustosId())
+ .build();
+ } else {
+ CredentialMetadata metadata = tokenAuthorizer.getCredentialsFromClientId(request.getClientId());
+ if (authClaim.isSuperTenant() || tokenAuthorizer.validateParentChildTenantRelationShip(authClaim.getTenantId(), metadata.getOwnerId())) {
+ request = request.toBuilder()
+ .setTenantId(metadata.getOwnerId())
+ .build();
+ } else {
+ throw new UnauthorizedException("Request is not authorized, user not authorized with the requested clientId: " + request.getClientId());
+ }
+ }
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized, token not found");
+ }
+
+ AllRoles response = tenantManagementService.getTenantRoles(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @DeleteMapping("/role")
+ public ResponseEntity<OperationStatus> deleteRole(@Valid @RequestBody DeleteRoleRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorizeUsingUserToken(headers);
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+
+ if (StringUtils.isBlank(request.getClientId())) {
+ request = request.toBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getCustosId())
+ .build();
+ } else {
+ CredentialMetadata metadata = tokenAuthorizer.getCredentialsFromClientId(request.getClientId());
+ if (authClaim.isSuperTenant() || tokenAuthorizer.validateParentChildTenantRelationShip(authClaim.getTenantId(), metadata.getOwnerId())) {
+ request = request.toBuilder()
+ .setTenantId(metadata.getOwnerId())
+ .build();
+ } else {
+ throw new UnauthorizedException("Request is not authorized, user not authorized with the requested clientId: " + request.getClientId());
+ }
+ }
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized, token not found");
+ }
+
+ OperationStatus response = tenantManagementService.deleteRole(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/protocol/mapper")
+ public ResponseEntity<OperationStatus> addProtocolMapper(@Valid @RequestBody AddProtocolMapperRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorizeUsingUserToken(headers);
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+
+ if (StringUtils.isBlank(request.getClientId())) {
+ request = request.toBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getCustosId())
+ .build();
+ } else {
+ CredentialMetadata metadata = tokenAuthorizer.getCredentialsFromClientId(request.getClientId());
+ if (authClaim.isSuperTenant() || tokenAuthorizer.validateParentChildTenantRelationShip(authClaim.getTenantId(), metadata.getOwnerId())) {
+ request = request.toBuilder()
+ .setTenantId(metadata.getOwnerId())
+ .build();
+ } else {
+ throw new UnauthorizedException("Request is not authorized, user not authorized with the requested clientId: " + request.getClientId());
+ }
+ }
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized, token not found");
+ }
+ OperationStatus response = tenantManagementService.addProtocolMapper(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/events")
+ public ResponseEntity<OperationStatus> configureEventPersistence(@Valid @RequestBody EventPersistenceRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorizeUsingUserToken(headers);
+ if (claim.isPresent()) {
+ request = request.toBuilder()
+ .setTenantId(claim.get().getTenantId())
+ .setPerformedBy(claim.get().getPerformedBy())
+ .build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized, token not found");
+ }
+ OperationStatus response = tenantManagementService.configureEventPersistence(request);
+ return ResponseEntity.ok(response);
+ }
+
+
+ @PostMapping("/status")
+ public ResponseEntity<UpdateStatusResponse> updateTenantStatus(@Valid @RequestBody UpdateStatusRequest request) {
+ UpdateStatusResponse response = tenantManagementService.updateTenantStatus(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/tenants")
+ public ResponseEntity<GetAllTenantsResponse> getAllTenants(@Valid @RequestBody GetTenantsRequest request) {
+ GetAllTenantsResponse response = tenantManagementService.getAllTenants(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/child/tenants")
+ public ResponseEntity<GetAllTenantsResponse> getChildTenants(@Valid @RequestBody GetTenantsRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorizeUsingUserToken(headers);
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+
+ if (StringUtils.isBlank(request.getParentClientId())) {
+ request = request.toBuilder()
+ .setParentId(authClaim.getTenantId())
+ .build();
+ } else {
+ CredentialMetadata metadata = tokenAuthorizer.getCredentialsFromClientId(request.getParentClientId());
+ if (authClaim.isSuperTenant() || tokenAuthorizer.validateParentChildTenantRelationShip(authClaim.getTenantId(), metadata.getOwnerId())) {
+ request = request.toBuilder()
+ .setParentId(metadata.getOwnerId())
+ .build();
+ } else {
+ throw new UnauthorizedException("Request is not authorized, user not authorized with the requested clientId: " + request.getParentClientId());
+ }
+ }
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized, token not found");
+ }
+ GetAllTenantsResponse response = tenantManagementService.getChildTenants(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/tenants/{requesterEmail}")
+ public ResponseEntity<GetAllTenantsForUserResponse> getAllTenantsForUser(@PathVariable("requesterEmail") String requesterEmail, @RequestHeader HttpHeaders headers) {
+ tokenAuthorizer.authorize(headers);
+ GetAllTenantsForUserResponse response = tenantManagementService.getAllTenantsForUser(GetAllTenantsForUserRequest.newBuilder().setRequesterEmail(requesterEmail).build());
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/audit/status/{tenantId}")
+ public ResponseEntity<GetStatusUpdateAuditTrailResponse> getTenantStatusUpdateAuditTrail(@PathVariable("tenantId") long tenantId) {
+ GetStatusUpdateAuditTrailResponse response = tenantManagementService.getTenantStatusUpdateAuditTrail(GetAuditTrailRequest.newBuilder().setTenantId(tenantId).build());
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/cache/institutions/CILogon")
+ public ResponseEntity<GetInstitutionsResponse> getFromCache(@Valid @RequestBody CacheManipulationRequest request, @RequestHeader HttpHeaders headers) {
+ GetInstitutionsResponse response = tenantManagementService.getFromCache(generateCacheManipulationRequest(request, headers));
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/institutions/CILogon")
+ public ResponseEntity<GetInstitutionsResponse> getInstitutions(@Valid @RequestBody CacheManipulationRequest request, @RequestHeader HttpHeaders headers) {
+ GetInstitutionsResponse response = tenantManagementService.getInstitutions(generateCacheManipulationRequest(request, headers));
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/cache/institutions/CILogon")
+ public ResponseEntity<Status> addToCache(@Valid @RequestBody CacheManipulationRequest request, @RequestHeader HttpHeaders headers) {
+ request = generateCacheManipulationRequest(request, headers);
+ Optional<AuthClaim> userClaim = tokenAuthorizer.validateUserToken(headers);
+ if (userClaim.isPresent()) {
+ request = request.toBuilder()
+ .setPerformedBy(userClaim.get().getUsername())
+ .build();
+ }
+ Status response = tenantManagementService.addToCache(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @DeleteMapping("/cache/institutions/CILogon")
+ public ResponseEntity<Status> removeFromCache(@Valid @RequestBody CacheManipulationRequest request, @RequestHeader HttpHeaders headers) {
+ request = generateCacheManipulationRequest(request, headers);
+ Optional<AuthClaim> userClaim = tokenAuthorizer.validateUserToken(headers);
+ if (userClaim.isPresent()) {
+ request = request.toBuilder()
+ .setPerformedBy(userClaim.get().getUsername())
+ .build();
+ }
+ Status response = tenantManagementService.removeFromCache(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/audit/attributes/{tenantId}")
+ public ResponseEntity<GetAttributeUpdateAuditTrailResponse> getTenantAttributeUpdateAuditTrail(@PathVariable("tenantId") int tenantId) {
+ GetAttributeUpdateAuditTrailResponse response = tenantManagementService.getTenantAttributeUpdateAuditTrail(GetAuditTrailRequest.newBuilder()
+ .setTenantId(tenantId).build());
+ return ResponseEntity.ok(response);
+ }
+
+ @Hidden
+ @PostMapping("/oauth2/tenant/{tenantId}/client")
+ public ResponseEntity<?> configureClient(@PathVariable("tenantId") int tenantId, @RequestBody Map<String, Object> body, @RequestHeader HttpHeaders headers) {
+// tokenAuthorizer.authorize(headers);
+ Map<String, String> response = tenantManagementService.addClient(tenantId, (String) body.get("tenantUrl"), (List<String>) body.get("redirectUris"));
+ return ResponseEntity.ok(response);
+ }
+
+
+ private Credentials getCredentials(AuthClaim claim) {
+ return Credentials.newBuilder()
+ .setCustosClientId(claim.getCustosId())
+ .setCustosClientSecret(claim.getCustosSecret())
+ .setCustosClientIdIssuedAt(claim.getCustosIdIssuedAt())
+ .setCustosClientSecretExpiredAt(claim.getCustosSecretExpiredAt())
+ .setIamClientId(claim.getIamAuthId())
+ .setIamClientSecret(claim.getIamAuthSecret())
+ .setCiLogonClientId(claim.getCiLogonId())
+ .setCiLogonClientSecret(claim.getCiLogonSecret()).build();
+ }
+
+ private CacheManipulationRequest generateCacheManipulationRequest(CacheManipulationRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers);
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ return request.toBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized, token not found");
+ }
+ }
+}
diff --git a/api/src/main/java/org/apache/custos/api/user/UserManagementController.java b/api/src/main/java/org/apache/custos/api/user/UserManagementController.java
new file mode 100644
index 000000000..6cdb23313
--- /dev/null
+++ b/api/src/main/java/org/apache/custos/api/user/UserManagementController.java
@@ -0,0 +1,799 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.custos.api.user;
+
+import org.apache.custos.core.constants.Constants;
+import org.apache.custos.core.iam.api.AddExternalIDPLinksRequest;
+import org.apache.custos.core.iam.api.AddUserAttributesRequest;
+import org.apache.custos.core.iam.api.AddUserRolesRequest;
+import org.apache.custos.core.iam.api.DeleteExternalIDPsRequest;
+import org.apache.custos.core.iam.api.DeleteUserAttributeRequest;
+import org.apache.custos.core.iam.api.DeleteUserRolesRequest;
+import org.apache.custos.core.iam.api.FindUsersRequest;
+import org.apache.custos.core.iam.api.FindUsersResponse;
+import org.apache.custos.core.iam.api.GetExternalIDPsRequest;
+import org.apache.custos.core.iam.api.GetExternalIDPsResponse;
+import org.apache.custos.core.iam.api.OperationStatus;
+import org.apache.custos.core.iam.api.RegisterUserRequest;
+import org.apache.custos.core.iam.api.RegisterUserResponse;
+import org.apache.custos.core.iam.api.RegisterUsersRequest;
+import org.apache.custos.core.iam.api.RegisterUsersResponse;
+import org.apache.custos.core.iam.api.ResetUserPassword;
+import org.apache.custos.core.iam.api.UserAttribute;
+import org.apache.custos.core.iam.api.UserRepresentation;
+import org.apache.custos.core.iam.api.UserSearchMetadata;
+import org.apache.custos.core.iam.api.UserSearchRequest;
+import org.apache.custos.core.identity.api.AuthToken;
+import org.apache.custos.core.user.management.api.LinkUserProfileRequest;
+import org.apache.custos.core.user.management.api.SynchronizeUserDBRequest;
+import org.apache.custos.core.user.management.api.UserProfileRequest;
+import org.apache.custos.core.user.profile.api.GetAllUserProfilesResponse;
+import org.apache.custos.core.user.profile.api.GetUpdateAuditTrailRequest;
+import org.apache.custos.core.user.profile.api.GetUpdateAuditTrailResponse;
+import org.apache.custos.core.user.profile.api.UserProfile;
+import org.apache.custos.service.auth.AuthClaim;
+import org.apache.custos.service.auth.TokenAuthorizer;
+import org.apache.custos.service.management.UserManagementService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.Parameter;
+import io.swagger.v3.oas.annotations.enums.ParameterIn;
+import io.swagger.v3.oas.annotations.media.ArraySchema;
+import io.swagger.v3.oas.annotations.media.Content;
+import io.swagger.v3.oas.annotations.media.Schema;
+import io.swagger.v3.oas.annotations.media.SchemaProperty;
+import io.swagger.v3.oas.annotations.responses.ApiResponse;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import jakarta.validation.Valid;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.server.ResponseStatusException;
+
+import java.util.Map;
+import java.util.Optional;
+
+@RestController
+@RequestMapping("/api/v1/user-management")
+@Tag(name = "User Management")
+public class UserManagementController {
+
+ private final UserManagementService userManagementService;
+ private final TokenAuthorizer tokenAuthorizer;
+
+ public UserManagementController(UserManagementService userManagementService, TokenAuthorizer tokenAuthorizer) {
+ this.userManagementService = userManagementService;
+ this.tokenAuthorizer = tokenAuthorizer;
+ }
+
+ @PostMapping("/user")
+ @Operation(
+ summary = "Register User",
+ description = "This operation registers a new user in the system. The supplied RegisterUserRequest should " +
+ "include all the necessary user information such as username, email, and other user attributes. " +
+ "Upon successful registration, the system generates a unique identifier for the user and returns a " +
+ "RegisterUserResponse enriched with this identifier and other details. Any violation of the user " +
+ "registration policy (e.g., registering with an already existing username) will be handled according " +
+ "to the application's error handling protocol.",
+
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = RegisterUserResponse.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<RegisterUserResponse> registerUser(@RequestParam(value = "client_id", required = false) String clientId, @RequestBody UserRepresentation requestData, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, clientId);
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+
+ RegisterUserRequest request = RegisterUserRequest.newBuilder()
+ .setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .setUser(requestData)
+ .build();
+ RegisterUserResponse response = userManagementService.registerUser(request);
+ return ResponseEntity.ok(response);
+
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+ }
+
+ @PostMapping("/users")
+ @Operation(
+ summary = "Register and Enable Multiple Users",
+ description = "This operation registers and enables multiple users in the system simultaneously. " +
+ "The RegisterUsersRequest should include a list of user entities to be registered. " +
+ "Each entity should have the necessary user information such as username, email, etc. " +
+ "Upon successful registration and enablement, the system generates unique identifiers for the users and returns a " +
+ "RegisterUsersResponse with a boolean indicating all the users got registered. " +
+ "If it false then the response will contain the user representations of the failed users.",
+
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ required = true,
+ content = @Content(
+ schemaProperties = {
+ @SchemaProperty(
+ name = "users",
+ array = @ArraySchema(
+ schema = @Schema(implementation = UserRepresentation.class),
+ arraySchema = @Schema(description = "List of Users")
+ )
+ )
+ }
+ )
+ ),
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = RegisterUsersResponse.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<RegisterUsersResponse> registerAndEnableUsers(@RequestParam(value = "client_id") String clientId, @RequestBody RegisterUsersRequest request, @RequestHeader HttpHeaders headers) {
+ headers = attachUserToken(headers, clientId);
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, clientId);
+
+ if (claim.isPresent()) {
+ Optional<String> userTokenOp = tokenAuthorizer.getUserTokenFromUserTokenHeader(headers);
+ String userToken = userTokenOp.isEmpty()
+ ? tokenAuthorizer.getToken(headers)
+ : userTokenOp.get();
+
+ AuthClaim authClaim = claim.get();
+
+ request = request.toBuilder().setClientId(authClaim.getIamAuthId())
+ .setTenantId(authClaim.getTenantId())
+ .setAccessToken(userToken)
+ .setPerformedBy(authClaim.getPerformedBy()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ RegisterUsersResponse response = userManagementService.registerAndEnableUsers(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/attributes")
+ @Operation(
+ summary = "Add User Attributes",
+ description = "This operation allows adding custom attributes to an existing user. " +
+ "The AddUserAttributesRequest should specify the user and the attributes to add. " +
+ "Upon successful execution, the system adds the new attributes to the user profile and returns an " +
+ "OperationStatus representing the result.",
+
+ requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
+ required = true,
+ content = @Content(
+ schemaProperties = {
+ @SchemaProperty(
+ name = "users",
+ array = @ArraySchema(
+ schema = @Schema(implementation = String.class),
+ arraySchema = @Schema(description = "List of User Names")
+ )
+ ),
+ @SchemaProperty(
+ name = "attributes",
+ array = @ArraySchema(
+ schema = @Schema(implementation = UserAttribute.class),
+ arraySchema = @Schema(description = "List of User Attributes")
+ )
+ )
+ }
+ )
+ ),
+
+ responses = {
+ @ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = OperationStatus.class))),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Request", content = @Content()),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content())
+ }
+ )
+ public ResponseEntity<OperationStatus> addUserAttributes(@RequestParam(value = "client_id") String clientId, @RequestBody AddUserAttributesRequest request, @RequestHeader HttpHeaders headers) {
+ headers = attachUserToken(headers, clientId);
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, clientId);
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ AuthToken authToken = tokenAuthorizer.getSAToken(authClaim.getIamAuthId(), authClaim.getIamAuthSecret(), authClaim.getTenantId());
+
+ if (authToken == null || StringUtils.isBlank(authToken.getAccessToken())) {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized. Service Account token is invalid");
+ }
+
+ request = request.toBuilder().setClientId(authClaim.getIamAuthId())
+ .setTenantId(authClaim.getTenantId())
+ .setAccessToken(authToken.getAccessToken())
+ .setPerformedBy(authClaim.getPerformedBy()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ OperationStatus response = userManagementService.addUserAttributes(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @DeleteMapping("/attributes")
+ @Operation(
+ summary = "Delete User Attributes",
+ description = "This operation allows removing specific attributes from an existing user. " +
+ "The DeleteUserAttributeRequest should specify the user and the attributes to delete. " +
+ "Upon successful execution, the system removes the specified attributes from the user profile and returns " +
+ "an OperationStatus representing the result."
+ )
+ public ResponseEntity<OperationStatus> deleteUserAttributes(@RequestBody DeleteUserAttributeRequest request, @RequestHeader HttpHeaders headers) {
+ headers = attachUserToken(headers, request.getClientId());
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, request.getClientId());
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ AuthToken authToken = tokenAuthorizer.getSAToken(authClaim.getIamAuthId(), authClaim.getIamAuthSecret(), authClaim.getTenantId());
+
+ if (authToken == null || StringUtils.isBlank(authToken.getAccessToken())) {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized. Service Account token is invalid");
+ }
+
+ request = request.toBuilder().setClientId(authClaim.getIamAuthId())
+ .setTenantId(authClaim.getTenantId())
+ .setAccessToken(authToken.getAccessToken())
+ .setPerformedBy(authClaim.getPerformedBy()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ OperationStatus response = userManagementService.deleteUserAttributes(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/user/activation")
+ @Operation(
+ summary = "Enable User",
+ description = "This operation enables a previously disabled user. The UserSearchRequest should specify " +
+ "the criteria to identify the particular user. Upon successful execution, the system changes the user's " +
+ "status to 'enabled' and returns an updated UserRepresentation reflecting this new status."
+ )
+ public ResponseEntity<UserRepresentation> enableUser(@RequestBody UserSearchRequest request, @RequestHeader HttpHeaders headers) {
+ UserRepresentation response = userManagementService.enableUser(generateUserSearchRequestWithoutAdditionalHeader(request.toBuilder(), headers).build());
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/user/deactivation")
+ @Operation(
+ summary = "Disable User",
+ description = "This operation disables a previously enabled user. The UserSearchRequest should specify " +
+ "the criteria to identify the particular user. Upon successful execution, the system changes " +
+ "the user's status to 'disabled' and returns an updated UserRepresentation reflecting this new status."
+ )
+ public ResponseEntity<UserRepresentation> disableUser(@RequestBody UserSearchRequest request, @RequestHeader HttpHeaders headers) {
+ UserRepresentation response = userManagementService.disableUser(generateUserSearchRequestWithoutAdditionalHeader(request.toBuilder(), headers).build());
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/user/admin")
+ @Operation(
+ summary = "Grant Admin Privileges",
+ description = "This operation grants admin privileges to a specified existing user. " +
+ "The UserSearchRequest should specify the criteria to identify the particular user. " +
+ "After successful execution, the system updates the user's profile to include admin privileges " +
+ "and returns an OperationStatus reflecting the result of this operation."
+ )
+ public ResponseEntity<OperationStatus> grantAdminPrivileges(@RequestBody UserSearchRequest request, @RequestHeader HttpHeaders headers) {
+ OperationStatus response = userManagementService.grantAdminPrivileges(generateUserSearchRequest(request.toBuilder(), headers).build());
+ return ResponseEntity.ok(response);
+ }
+
+ @DeleteMapping("/user/admin")
+ @Operation(
+ summary = "Remove Admin Privileges",
+ description = "This operation removes admin privileges from a specified existing user who previously had them. " +
+ "The UserSearchRequest should specify the criteria to identify the particular user. " +
+ "Upon successful execution, the system updates the user's profile to remove admin privileges and returns " +
+ "an OperationStatus reflecting the result."
+ )
+ public ResponseEntity<OperationStatus> removeAdminPrivileges(@RequestBody UserSearchRequest request, @RequestHeader HttpHeaders headers) {
+ OperationStatus response = userManagementService.removeAdminPrivileges(generateUserSearchRequest(request.toBuilder(), headers).build());
+ return ResponseEntity.ok(response);
+ }
+
+ @DeleteMapping("/users/federatedIDPs")
+ @Operation(
+ summary = "Delete External IDPs Of Users",
+ description = "This operation deletes specified external Identity Providers (IDPs) from identified users. " +
+ "The DeleteExternalIDPsRequest should include user identifiers and the list of external IDPs to be removed. " +
+ "Upon successful execution, the system deletes the associated external IDPs from the user profiles " +
+ "and returns an OperationStatus reflecting the result."
+ )
+ public ResponseEntity<OperationStatus> deleteExternalIDPsOfUsers(@RequestBody DeleteExternalIDPsRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, request.getClientId());
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+
+ request = request.toBuilder().setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+ OperationStatus response = userManagementService.deleteExternalIDPsOfUsers(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/users/federatedIDPs")
+ @Operation(
+ summary = "Add External IDPs Of Users",
+ description = "This operation associates specified external Identity Providers (IDPs) with identified users. " +
+ "The AddExternalIDPLinksRequest should include user identifiers and the list of external IDPs to be added. " +
+ "Upon successful execution, the system associates the specified external IDPs with the user profiles and returns " +
+ "an OperationStatus reflecting the result."
+ )
+ public ResponseEntity<OperationStatus> addExternalIDPsOfUsers(@RequestBody AddExternalIDPLinksRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, request.getClientId());
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+
+ request = request.toBuilder().setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ OperationStatus response = userManagementService.addExternalIDPsOfUsers(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/users/federatedIDPs")
+ @Operation(
+ summary = "Get External IDPs Of Users",
+ description = "This operation retrieves associated external Identity Providers (IDPs) of identified users. " +
+ "The GetExternalIDPsRequest should include user identifiers for whom the external IDPs need to be retrieved. " +
+ "Upon successful execution, the system returns a GetExternalIDPsResponse containing the associated external IDPs for each user."
+ )
+ public ResponseEntity<GetExternalIDPsResponse> getExternalIDPsOfUsers(@RequestBody GetExternalIDPsRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, request.getClientId());
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+
+ request = request.toBuilder().setTenantId(authClaim.getTenantId())
+ .setClientId(authClaim.getIamAuthId()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+ GetExternalIDPsResponse response = userManagementService.getExternalIDPsOfUsers(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/users/roles")
+ @Operation(
+ summary = "Add Roles To Users",
+ description = "This operation adds specified roles to identified users. The AddUserRolesRequest " +
+ "should include user identifiers and the list of roles to be added. Upon successful execution, " +
+ "the system associates the specified roles with the user profiles and returns an OperationStatus reflecting the result."
+ )
+ public ResponseEntity<OperationStatus> addRolesToUsers(@Valid @RequestBody AddUserRolesRequest request, @RequestHeader HttpHeaders headers) {
+ headers = attachUserToken(headers, request.getClientId());
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, request.getClientId());
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ AuthToken authToken = tokenAuthorizer.getSAToken(authClaim.getIamAuthId(), authClaim.getIamAuthSecret(), authClaim.getTenantId());
+
+ if (authToken == null || StringUtils.isBlank(authToken.getAccessToken())) {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized. Service Account token is invalid");
+ }
+
+ request = request.toBuilder().setClientId(authClaim.getIamAuthId())
+ .setTenantId(authClaim.getTenantId())
+ .setAccessToken(authToken.getAccessToken())
+ .setPerformedBy(authClaim.getPerformedBy()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ OperationStatus response = userManagementService.addRolesToUsers(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/user/activation/status")
+ @Operation(
+ summary = "Check If User Is Enabled",
+ description = "This operation checks whether a specified user is enabled. The UserSearchRequest " +
+ "should specify the criteria to identify the particular user. Upon successful execution, " +
+ "it returns an OperationStatus that reflects whether the user is enabled."
+ )
+ public ResponseEntity<OperationStatus> isUserEnabled(@RequestBody UserSearchRequest request, @RequestHeader HttpHeaders headers) {
+ OperationStatus response = userManagementService.isUserEnabled(generateUserSearchRequestWithoutAdditionalHeader(request.toBuilder(), headers).build());
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/user/availability")
+ @Operation(
+ summary = "Check If Username Is Available",
+ description = "This operation checks whether a given username is available. The UserSearchRequest " +
+ "should specify the username to check. Upon successful execution, it returns an OperationStatus " +
+ "that reflects whether the username is available for registration."
+ )
+ public ResponseEntity<OperationStatus> isUsernameAvailable(@RequestBody UserSearchRequest request, @RequestHeader HttpHeaders headers) {
+ OperationStatus response = userManagementService.isUsernameAvailable(generateUserSearchRequestWithoutAdditionalHeader(request.toBuilder(), headers).build());
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/user")
+ @Operation(
+ summary = "Retrieve User",
+ description = "This operation retrieves a specified user's profile. The UserSearchRequest should specify " +
+ "the criteria to identify the particular user. It returns a UserRepresentation that includes " +
+ "detailed information about the user."
+ )
+ public ResponseEntity<UserRepresentation> getUser(@Valid @RequestBody UserSearchRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, request.getClientId());
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ request = request.toBuilder().setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .setTenantId(claim.get().getTenantId()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ UserRepresentation response = userManagementService.getUser(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/users")
+ @Operation(
+ summary = "Find Users",
+ description = "This operation searches for users that match the criteria provided in the FindUsersRequest, " +
+ "which can include attributes like username, email, roles, etc. It returns a FindUsersResponse " +
+ "containing the matching users' profiles."
+ )
+ public ResponseEntity<FindUsersResponse> findUsers(@RequestParam(value = "client_id") String clientId,
+ @RequestParam(value = "offset") int offset,
+ @RequestParam(value = "limit") int limit,
+ @RequestParam("user.id") String userId,
+ @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, clientId);
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ UserSearchMetadata userSearchMetadata = UserSearchMetadata.newBuilder()
+ .setId(userId)
+ .build();
+ FindUsersRequest request = FindUsersRequest.newBuilder().setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .setTenantId(claim.get().getTenantId())
+ .setOffset(offset)
+ .setLimit(limit)
+ .setUser(userSearchMetadata)
+ .build();
+
+ FindUsersResponse response = userManagementService.findUsers(request);
+ return ResponseEntity.ok(response);
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+ }
+
+ @PutMapping("/user/password")
+ @Operation(
+ summary = "Update User Password",
+ description = "This operation updates a specified user's password. An UpdatePasswordRequest should include " +
+ "user identifier and new password. Upon successful execution, it returns an OperationStatus " +
+ "reflecting the result of the password update process."
+ )
+ public ResponseEntity<OperationStatus> resetPassword(@RequestBody ResetUserPassword request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, request.getClientId());
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ request = request.toBuilder().setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .setTenantId(claim.get().getTenantId()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+ OperationStatus response = userManagementService.resetPassword(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @DeleteMapping("/user")
+ @Operation(
+ summary = "Delete User",
+ description = "This operation deletes an existing user from the system. The UserSearchRequest should specify " +
+ "the criteria to identify the particular user. Upon successful execution, the system removes " +
+ "the user profile and returns an OperationStatus reflecting the result of the delete operation."
+ )
+ public ResponseEntity<OperationStatus> deleteUser(@RequestBody UserSearchRequest request, @RequestHeader HttpHeaders headers) {
+ OperationStatus response = userManagementService.deleteUser(generateUserSearchRequest(request.toBuilder(), headers).build());
+ return ResponseEntity.ok(response);
+ }
+
+ @DeleteMapping("/user/roles")
+ @Operation(
+ summary = "Delete User Roles",
+ description = "This operation removes specified roles from a identified user. The DeleteUserRolesRequest " +
+ "should include user identifier and a list of roles to be removed. Upon successful execution, the system " +
+ "disassociates the specified roles from the user profile and returns an OperationStatus reflecting the result."
+ )
+ public ResponseEntity<OperationStatus> deleteUserRoles(@Valid @RequestBody DeleteUserRolesRequest request, @RequestHeader HttpHeaders headers) {
+ headers = attachUserToken(headers, request.getClientId());
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, request.getClientId());
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ AuthToken authToken = tokenAuthorizer.getSAToken(authClaim.getIamAuthId(), authClaim.getIamAuthSecret(), authClaim.getTenantId());
+
+ if (authToken == null || StringUtils.isBlank(authToken.getAccessToken())) {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized. Service Account token is invalid");
+ }
+
+ request = request.toBuilder().setClientId(authClaim.getIamAuthId())
+ .setTenantId(authClaim.getTenantId())
+ .setAccessToken(authToken.getAccessToken())
+ .setPerformedBy(authClaim.getPerformedBy().isEmpty() ? Constants.SYSTEM : authClaim.getPerformedBy()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ OperationStatus response = userManagementService.deleteUserRoles(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @PutMapping("/user/profile")
+ @Operation(
+ summary = "Update User Profile",
+ description = "This operation updates profiles of existing users. The UserProfileRequest should specify the updated " +
+ "user details. Upon successful profile update, the system sends back the updated UserProfile wrapped in a ResponseEntity."
+ )
+ public ResponseEntity<UserProfile> updateUserProfile(@RequestBody UserProfileRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, request.getClientId());
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ AuthToken authToken = tokenAuthorizer.getSAToken(authClaim.getIamAuthId(), authClaim.getIamAuthSecret(), authClaim.getTenantId());
+
+ if (authToken == null || StringUtils.isBlank(authToken.getAccessToken())) {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized. Service Account token is invalid");
+ }
+
+ request = request.toBuilder().setClientId(authClaim.getIamAuthId())
+ .setClientSecret(authClaim.getIamAuthSecret())
+ .setTenantId(authClaim.getTenantId())
+ .setAccessToken(authToken.getAccessToken())
+ .setPerformedBy(Constants.SYSTEM).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+
+ UserProfile response = userManagementService.updateUserProfile(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/user/profile")
+ @Operation(
+ summary = "Get User Profile",
+ description = "This operation retrieves the profile of a specified user. The UserProfileRequest should specify which user's " +
+ "profile is to be retrieved. The system would return a ResponseEntity containing the UserProfile for the specified user."
+ )
+ public ResponseEntity<UserProfile> getUserProfile(@Valid @RequestBody UserProfileRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorizeUsingUserToken(headers);
+
+ if (claim.isPresent()) {
+ request = request.toBuilder().setTenantId(claim.get().getTenantId()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ UserProfile response = userManagementService.getUserProfile(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @DeleteMapping("/user/profile")
+ @Operation(
+ summary = "Delete User Profile",
+ description = "This operation deletes the profile of a specified user. The UserProfileRequest should specify which user's " +
+ "profile is to be deleted. Upon successful profile deletion, the system would send back a ResponseEntity."
+ )
+ public ResponseEntity<UserProfile> deleteUserProfile(@RequestBody UserProfileRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, request.getClientId());
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ request = request.toBuilder().setClientId(authClaim.getIamAuthId())
+ .setClientSecret(authClaim.getIamAuthSecret())
+ .setTenantId(authClaim.getTenantId()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ UserProfile response = userManagementService.deleteUserProfile(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/users/profile")
+ @Operation(
+ summary = "Get All User Profiles In Tenant",
+ description = "This operation retrieves the profiles of all users in the tenant. A UserProfileRequest is used to get user profiles. " +
+ "Upon successful execution, the system sends back a ResponseEntity containing GetAllUserProfilesResponse, " +
+ "wrapping all user profiles in the tenant."
+ )
+ public ResponseEntity<GetAllUserProfilesResponse> getAllUserProfilesInTenant(@RequestBody UserProfileRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, request.getClientId());
+
+ if (claim.isPresent()) {
+ request = request.toBuilder().setTenantId(claim.get().getTenantId()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ GetAllUserProfilesResponse response = userManagementService.getAllUserProfilesInTenant(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/user/profile/mapper")
+ @Operation(
+ summary = "Link User Profile",
+ description = "This operation associates or links profiles of different users. The LinkUserProfileRequest should specify " +
+ "which user profiles are to be linked. Upon successful execution, the system gives back an OperationStatus wrapped in a " +
+ "ResponseEntity reflecting the result."
+ )
+ public ResponseEntity<OperationStatus> linkUserProfile(@RequestBody LinkUserProfileRequest request, @RequestHeader HttpHeaders headers) {
+ String token = tokenAuthorizer.getToken(headers);
+ Optional<AuthClaim> claim = tokenAuthorizer.authorizeUsingUserToken(headers);
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+
+ request = request.toBuilder().setIamClientId(authClaim.getIamAuthId())
+ .setIamClientSecret(authClaim.getIamAuthSecret())
+ .setTenantId(authClaim.getTenantId())
+ .setAccessToken(token)
+ .setPerformedBy(authClaim.getPerformedBy()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ OperationStatus response = userManagementService.linkUserProfile(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/user/profile/audit")
+ @Operation(
+ summary = "Get User Profile Audit Trails",
+ description = "This operation retrieves the audit trails of updates to a user's profile. The GetUpdateAuditTrailRequest should specify " +
+ "the user whose audit trails need to be retrieved. Upon successful execution, the system returns a ResponseEntity containing " +
+ "a GetUpdateAuditTrailResponse wrapping the retrieved audit details."
+ )
+ public ResponseEntity<GetUpdateAuditTrailResponse> getUserProfileAuditTrails(@RequestBody GetUpdateAuditTrailRequest request, @RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers);
+
+ if (claim.isPresent()) {
+ request = request.toBuilder().setTenantId(claim.get().getTenantId()).build();
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+
+ GetUpdateAuditTrailResponse response = userManagementService.getUserProfileAuditTrails(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/db/synchronize")
+ @Operation(
+ summary = "Synchronize User Databases",
+ description = "This operation synchronizes user databases. The SynchronizeUserDBRequest should contain the necessary " +
+ "information to perform the synchronization. Upon successful execution, the system provides the synchronization " +
+ "status within an OperationStatus object wrapped in a ResponseEntity."
+ )
+ public ResponseEntity<OperationStatus> synchronizeUserDBs(@Valid @RequestBody SynchronizeUserDBRequest request) {
+ OperationStatus response = userManagementService.synchronizeUserDBs(request);
+ return ResponseEntity.ok(response);
+ }
+
+ @GetMapping("/userinfo")
+ @Operation(
+ summary = "Retrieve User Info",
+ parameters = {
+ @Parameter(
+ name = "client_id",
+ in = ParameterIn.HEADER,
+ description = "The client ID initiating the group membership type removal request",
+ required = true,
+ schema = @Schema(type = "string")
+ )
+ }
+ )
+ public ResponseEntity<Object> userInfo(@RequestHeader HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, headers.getFirst("client_id"));
+
+ if (claim.isPresent()) {
+ Map<String, Object> userInfo = userManagementService.getUserInfo(tokenAuthorizer.getToken(headers), claim.get().getTenantId());
+ return ResponseEntity.ok(userInfo);
+
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+ }
+
+ private HttpHeaders attachUserToken(HttpHeaders headers, String clientId) {
+ if (StringUtils.isBlank(clientId)) {
+ String formattedUserToken = tokenAuthorizer.getToken(headers);
+ headers.add(Constants.USER_TOKEN, formattedUserToken);
+ return headers;
+ }
+
+ return headers;
+ }
+
+ private UserSearchRequest.Builder generateUserSearchRequest(UserSearchRequest.Builder builder, HttpHeaders headers) {
+ headers = attachUserToken(headers, builder.getClientId());
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, builder.getClientId());
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ AuthToken authToken = tokenAuthorizer.getSAToken(authClaim.getIamAuthId(), authClaim.getIamAuthSecret(), authClaim.getTenantId());
+
+ if (authToken == null || StringUtils.isBlank(authToken.getAccessToken())) {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized. Service Account token is invalid");
+ }
+
+ builder.setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .setTenantId(authClaim.getTenantId())
+ .setAccessToken(authToken.getAccessToken())
+ .setPerformedBy(Constants.SYSTEM);
+
+ return builder;
+
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+ }
+
+ private UserSearchRequest.Builder generateUserSearchRequestWithoutAdditionalHeader(UserSearchRequest.Builder builder, HttpHeaders headers) {
+ Optional<AuthClaim> claim = tokenAuthorizer.authorize(headers, builder.getClientId());
+
+ if (claim.isPresent()) {
+ AuthClaim authClaim = claim.get();
+ builder.setClientId(authClaim.getIamAuthId())
+ .setClientSec(authClaim.getIamAuthSecret())
+ .setTenantId(authClaim.getTenantId());
+
+ return builder;
+
+ } else {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Request is not authorized");
+ }
+ }
+}
diff --git a/api/src/main/java/org/apache/custos/api/util/ProtobufJsonUtil.java b/api/src/main/java/org/apache/custos/api/util/ProtobufJsonUtil.java
new file mode 100644
index 000000000..037f56328
--- /dev/null
+++ b/api/src/main/java/org/apache/custos/api/util/ProtobufJsonUtil.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.custos.api.util;
+
+import com.google.protobuf.InvalidProtocolBufferException;
+import com.google.protobuf.Message;
+import com.google.protobuf.util.JsonFormat;
+import org.apache.custos.api.exception.ProtobufConversionException;
+
+public class ProtobufJsonUtil {
+
+ /**
+ * Converts a JSON string to a Protobuf message builder.
+ *
+ * @param json the JSON string
+ * @param builder the Protobuf message builder
+ * @param <T> the type of the Protobuf message
+ * @return the Protobuf message builder
+ * @throws ProtobufConversionException if there is an error during parsing
+ */
+ public static <T extends Message.Builder> T jsonToProtobuf(String json, T builder) {
+ try {
+ JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
+ return builder;
+
+ } catch (InvalidProtocolBufferException e) {
+ throw new ProtobufConversionException("Failed to convert JSON to Protobuf", e);
+ }
+ }
+
+ /**
+ * Converts a Protobuf message to a JSON string.
+ *
+ * @param message the Protobuf message
+ * @param <T> the type of the Protobuf message
+ * @return the JSON string
+ * @throws ProtobufConversionException if there is an error during conversion
+ */
+ public static <T extends Message> String protobufToJson(T message) {
+ try {
+ return JsonFormat.printer().print(message);
+
+ } catch (InvalidProtocolBufferException e) {
+ throw new ProtobufConversionException("Failed to convert Protobuf to JSON", e);
+ }
+ }
+}
diff --git a/custos-services/custos-integration-core/pom.xml b/application/pom.xml
similarity index 58%
rename from custos-services/custos-integration-core/pom.xml
rename to application/pom.xml
index c5e39e724..3f2445e70 100644
--- a/custos-services/custos-integration-core/pom.xml
+++ b/application/pom.xml
@@ -21,15 +21,15 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
<parent>
- <artifactId>custos</artifactId>
<groupId>org.apache.custos</groupId>
- <version>1.1-SNAPSHOT</version>
- <relativePath>../../pom.xml</relativePath>
+ <artifactId>custos</artifactId>
+ <version>1.1-SNAPSHOT</version>
</parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>custos-integration-core</artifactId>
+ <groupId>org.apache</groupId>
+ <artifactId>custos-application</artifactId>
<dependencies>
<dependency>
@@ -37,58 +37,61 @@
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-to-slf4j</artifactId>
</exclusion>
<exclusion>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
+ <groupId>org.slf4j</groupId>
+ <artifactId>jul-to-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
-
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.annotation</groupId>
- <artifactId>javax.annotation-api</artifactId>
+ <groupId>org.apache.custos</groupId>
+ <artifactId>custos-api</artifactId>
+ <version>${project.version}</version>
</dependency>
<dependency>
- <groupId>io.grpc</groupId>
- <artifactId>grpc-stub</artifactId>
- </dependency>
- <dependency>
- <groupId>io.grpc</groupId>
- <artifactId>grpc-protobuf</artifactId>
- <exclusions>
- <exclusion>
- <groupId>com.google.api.grpc</groupId>
- <artifactId>proto-google-common-protos</artifactId>
- </exclusion>
- </exclusions>
+ <groupId>org.slf4j</groupId>
+ <artifactId>jul-to-slf4j</artifactId>
</dependency>
<dependency>
- <groupId>io.grpc</groupId>
- <artifactId>grpc-netty</artifactId>
+ <groupId>mysql</groupId>
+ <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
- <groupId>com.codahale</groupId>
- <artifactId>shamir</artifactId>
+ <groupId>com.google.protobuf</groupId>
+ <artifactId>protobuf-java</artifactId>
</dependency>
+<!-- <dependency>-->
+<!-- <groupId>org.springdoc</groupId>-->
+<!-- <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>-->
+<!-- <version>${springdoc.version}</version>-->
+<!-- </dependency>-->
+<!-- <dependency>-->
+<!-- <groupId>com.github.ben-manes.caffeine</groupId>-->
+<!-- <artifactId>caffeine</artifactId>-->
+<!-- </dependency>-->
</dependencies>
+
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
+ <version>${spring.boot.version}</version>
+ <executions>
+ <execution>
+ <goals>
+ <goal>repackage</goal>
+ </goals>
+ </execution>
+ </executions>
<configuration>
- <skip>true</skip>
+ <executable>true</executable>
</configuration>
</plugin>
</plugins>
-
</build>
</project>
\ No newline at end of file
diff --git a/application/src/main/java/org/apache/custos/CustosApplication.java b/application/src/main/java/org/apache/custos/CustosApplication.java
new file mode 100644
index 000000000..2c92a2318
--- /dev/null
+++ b/application/src/main/java/org/apache/custos/CustosApplication.java
@@ -0,0 +1,13 @@
+package org.apache.custos;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
+
+@SpringBootApplication
+@EnableJpaAuditing
+public class CustosApplication {
+ public static void main(String[] args) {
+ SpringApplication.run(CustosApplication.class, args);
+ }
+}
diff --git a/application/src/main/java/org/apache/custos/config/CacheConfig.java b/application/src/main/java/org/apache/custos/config/CacheConfig.java
new file mode 100644
index 000000000..b20297c83
--- /dev/null
+++ b/application/src/main/java/org/apache/custos/config/CacheConfig.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.custos.config;
+
+import com.github.benmanes.caffeine.cache.Caffeine;
+import org.springframework.cache.CacheManager;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.cache.caffeine.CaffeineCacheManager;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import java.time.Duration;
+
+@Configuration
+@EnableCaching
+public class CacheConfig {
+
+ @Bean
+ public CacheManager cacheManager() {
+ CaffeineCacheManager cacheManager = new CaffeineCacheManager("KCTokenCache");
+ cacheManager.setCaffeine(caffeineCacheBuilder());
+ return cacheManager;
+ }
+
+ Caffeine<Object, Object> caffeineCacheBuilder() {
+ return Caffeine.newBuilder()
+ .initialCapacity(100)
+ .maximumSize(10000)
+ .expireAfterWrite(Duration.ofHours(2));
+ }
+}
diff --git a/application/src/main/java/org/apache/custos/config/OpenAPIConfig.java b/application/src/main/java/org/apache/custos/config/OpenAPIConfig.java
new file mode 100644
index 000000000..635ba91a1
--- /dev/null
+++ b/application/src/main/java/org/apache/custos/config/OpenAPIConfig.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.custos.config;
+
+import io.swagger.v3.oas.models.OpenAPI;
+import io.swagger.v3.oas.models.info.Info;
+import io.swagger.v3.oas.models.security.OAuthFlow;
+import io.swagger.v3.oas.models.security.OAuthFlows;
+import io.swagger.v3.oas.models.security.Scopes;
+import io.swagger.v3.oas.models.security.SecurityRequirement;
+import io.swagger.v3.oas.models.security.SecurityScheme;
+import io.swagger.v3.oas.models.servers.Server;
+import org.springdoc.core.models.GroupedOpenApi;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import java.util.List;
+
+@Configuration
+public class OpenAPIConfig {
+
+ @Bean
+ public GroupedOpenApi publicApi() {
+ return GroupedOpenApi.builder()
+ .group("public")
+ .pathsToMatch("/api/**")
+ .build();
+ }
+
+ @Bean
+ public OpenAPI custosOpenAPI() {
+ return new OpenAPI()
+ .info(new Info()
+ .title("CUSTOS API")
+ .version("1.0.0"))
+ .addSecurityItem(new SecurityRequirement().addList("oauth2-pkce"))
+ .components(new io.swagger.v3.oas.models.Components()
+ .addSecuritySchemes("oauth2-pkce",
+ new SecurityScheme()
+ .type(SecurityScheme.Type.OAUTH2)
+ .flows(new OAuthFlows()
+ .authorizationCode(new OAuthFlow()
+ .authorizationUrl("/api/v1/identity-management/authorize")
+ .tokenUrl("/api/v1/identity-management/token")
+ .scopes(new Scopes()
+ .addString("openid", "openid")
+ .addString("email", "email"))))))
+ .servers(List.of(
+ new Server().url("http://127.0.0.1:8081"),
+ new Server().url("https://api.usecustos.org")
+ ));
+ }
+}
\ No newline at end of file
diff --git a/custos-services/custos-core-services/custos-messaging-core-service/src/main/proto/MessagingService.proto b/application/src/main/java/org/apache/custos/config/ProtobufJsonOpenAPIConfig.java
similarity index 51%
rename from custos-services/custos-core-services/custos-messaging-core-service/src/main/proto/MessagingService.proto
rename to application/src/main/java/org/apache/custos/config/ProtobufJsonOpenAPIConfig.java
index 52c269797..093c38db0 100644
--- a/custos-services/custos-core-services/custos-messaging-core-service/src/main/proto/MessagingService.proto
+++ b/application/src/main/java/org/apache/custos/config/ProtobufJsonOpenAPIConfig.java
@@ -18,46 +18,28 @@
*
*/
-syntax = "proto3";
-
-option java_multiple_files = true;
-package org.apache.custos.messaging.service;
-
-import "google/protobuf/empty.proto";
-
-
-option go_package = "./pb";
-
-
-message Message {
- int64 created_time = 1;
- string service_name = 2;
- string event_type = 3;
- string username = 4;
- string client_id = 5;
- int64 tenant_id = 6;
- map<string, string> properties = 7;
- string message_id = 8;
-}
-
-message MessageEnablingRequest {
- int64 tenant_id = 1;
- string client_id = 2;
+package org.apache.custos.config;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.hubspot.jackson.datatype.protobuf.ProtobufModule;
+import io.swagger.v3.core.jackson.ModelResolver;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ProtobufJsonOpenAPIConfig {
+
+ @Bean
+ public ObjectMapper objectMapper() {
+ final ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.registerModule(new ProtobufPropertiesModule());
+ objectMapper.registerModule(new ProtobufModule());
+
+ return objectMapper;
+ }
+
+ @Bean
+ public ModelResolver modelResolver(final ObjectMapper objectMapper) {
+ return new ModelResolver(objectMapper);
+ }
}
-
-message Status {
- bool status = 1;
-}
-
-message MessageEnablingResponse {
- string topic = 1;
-}
-
-
-service MessagingService {
-
- rpc publish(Message) returns(Status);
-
- rpc enable(MessageEnablingRequest) returns(MessageEnablingResponse);
-
-}
\ No newline at end of file
diff --git a/custos-services/custos-core-services/cluster-management-core-service/src/main/proto/ClusterManagementService.proto b/application/src/main/java/org/apache/custos/config/ProtobufMessageConverterConfig.java
similarity index 51%
rename from custos-services/custos-core-services/cluster-management-core-service/src/main/proto/ClusterManagementService.proto
rename to application/src/main/java/org/apache/custos/config/ProtobufMessageConverterConfig.java
index 6c58702ba..7e6dff4f1 100644
--- a/custos-services/custos-core-services/cluster-management-core-service/src/main/proto/ClusterManagementService.proto
+++ b/application/src/main/java/org/apache/custos/config/ProtobufMessageConverterConfig.java
@@ -18,25 +18,26 @@
*
*/
-syntax = "proto3";
+package org.apache.custos.config;
-option java_multiple_files = true;
-package org.apache.custos.cluster.management.service;
-option go_package = "./pb";
-message GetServerCertificateRequest {
- string secretName = 1;
- string namespace = 2;
-}
-
-message GetServerCertificateResponse {
- string certificate = 1;
-}
+import org.apache.custos.api.ProtobufJsonHttpMessageConverter;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+import java.util.List;
+@Configuration
+public class ProtobufMessageConverterConfig implements WebMvcConfigurer {
+ @Bean
+ public ProtobufJsonHttpMessageConverter protobufHttpMessageConverter() {
+ return new ProtobufJsonHttpMessageConverter();
+ }
-service ClusterManagementService {
-
- rpc getCustosServerCertificate (GetServerCertificateRequest) returns (GetServerCertificateResponse);
-
-}
\ No newline at end of file
+ @Override
+ public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
+ converters.add(protobufHttpMessageConverter());
+ }
+}
diff --git a/application/src/main/java/org/apache/custos/config/ProtobufPropertiesModule.java b/application/src/main/java/org/apache/custos/config/ProtobufPropertiesModule.java
new file mode 100644
index 000000000..b9a152c5a
--- /dev/null
+++ b/application/src/main/java/org/apache/custos/config/ProtobufPropertiesModule.java
@@ -0,0 +1,187 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package org.apache.custos.config;
+
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.annotation.JsonFormat.Shape;
+import com.fasterxml.jackson.core.Version;
+import com.fasterxml.jackson.core.util.VersionUtil;
+import com.fasterxml.jackson.databind.DeserializationConfig;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.Module;
+import com.fasterxml.jackson.databind.PropertyNamingStrategy.PropertyNamingStrategyBase;
+import com.fasterxml.jackson.databind.SerializationConfig;
+import com.fasterxml.jackson.databind.cfg.MapperConfig;
+import com.fasterxml.jackson.databind.introspect.AnnotatedClass;
+import com.fasterxml.jackson.databind.introspect.AnnotatedClassResolver;
+import com.fasterxml.jackson.databind.introspect.BasicBeanDescription;
+import com.fasterxml.jackson.databind.introspect.BasicClassIntrospector;
+import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
+import com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector;
+import com.fasterxml.jackson.databind.introspect.VisibilityChecker;
+import com.google.protobuf.Descriptors.Descriptor;
+import com.google.protobuf.Descriptors.FieldDescriptor;
+import com.google.protobuf.Message;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Module that integrates Protobuf properties with Jackson library for JSON serialization and deserialization.
+ * Handles auto-detection of Protobuf properties and adds necessary annotations for proper serialization/deserialization.
+ * This module provides a customized class introspector to handle Protobuf-specific serialization/deserialization behavior.
+ */
+public class ProtobufPropertiesModule extends Module {
+ private static final Logger log = LoggerFactory.getLogger(ProtobufPropertiesModule.class);
+
+ private final Map<Class<?>, Map<String, FieldDescriptor>> CACHE = new ConcurrentHashMap<>();
+
+ @Override
+ public String getModuleName() {
+ return "ProtobufPropertiesModule";
+ }
+
+ @Override
+ public Version version() {
+ return VersionUtil.versionFor(getClass());
+ }
+
+
+ @Override
+ public void setupModule(SetupContext context) {
+ context.setClassIntrospector(new ProtobufClassIntrospector());
+ context.insertAnnotationIntrospector(annotationIntrospector);
+
+ }
+
+ NopAnnotationIntrospector annotationIntrospector = new NopAnnotationIntrospector() {
+
+ @Override
+ public VisibilityChecker<?> findAutoDetectVisibility(AnnotatedClass ac, VisibilityChecker<?> checker) {
+ if (Message.class.isAssignableFrom(ac.getRawType())) {
+ return checker.withGetterVisibility(Visibility.PUBLIC_ONLY)
+ .withFieldVisibility(Visibility.ANY);
+ }
+ return super.findAutoDetectVisibility(ac, checker);
+ }
+
+
+ @Override
+ public Object findNamingStrategy(AnnotatedClass ac) {
+ if (!Message.class.isAssignableFrom(ac.getRawType())) {
+ return super.findNamingStrategy(ac);
+ }
+
+ return new PropertyNamingStrategyBase() {
+ @Override
+ public String translate(String propertyName) {
+ if (propertyName.endsWith("_")) {
+ return propertyName.substring(0, propertyName.length() - 1);
+ }
+ return propertyName;
+ }
+ };
+ }
+
+ };
+
+
+ class ProtobufClassIntrospector extends BasicClassIntrospector {
+
+ @Override
+ public BasicBeanDescription forDeserialization(DeserializationConfig cfg, JavaType type, MixInResolver r) {
+ BasicBeanDescription desc = super.forDeserialization(cfg, type, r);
+
+ if (Message.class.isAssignableFrom(type.getRawClass())) {
+ return protobufBeanDescription(cfg, type, r, desc);
+ }
+ return desc;
+ }
+
+
+ @Override
+ public BasicBeanDescription forSerialization(SerializationConfig cfg, JavaType type, MixInResolver r) {
+ BasicBeanDescription desc = super.forSerialization(cfg, type, r);
+
+ if (Message.class.isAssignableFrom(type.getRawClass())) {
+ return protobufBeanDescription(cfg, type, r, desc);
+ }
+ return desc;
+ }
+
+ private BasicBeanDescription protobufBeanDescription(MapperConfig<?> cfg, JavaType type, MixInResolver r, BasicBeanDescription baseDesc) {
+ Map<String, FieldDescriptor> types = CACHE.computeIfAbsent(type.getRawClass(), this::getDescriptorForType);
+ AnnotatedClass ac = AnnotatedClassResolver.resolve(cfg, type, r);
+ List<BeanPropertyDefinition> props = new ArrayList<>();
+
+ for (BeanPropertyDefinition p : baseDesc.findProperties()) {
+ String name = p.getName();
+ if (!types.containsKey(name)) {
+ continue;
+ }
+
+ if (p.hasField() && p.getField().getType().isJavaLangObject()
+ && types.get(name).getType().equals(com.google.protobuf.Descriptors.FieldDescriptor.Type.STRING)) {
+ addStringFormatAnnotation(p);
+ }
+
+ props.add(p.withSimpleName(name));
+ }
+ return new BasicBeanDescription(cfg, type, ac, new ArrayList<>(props)) {
+ };
+ }
+
+ @JsonFormat(shape = Shape.STRING)
+ class AnnotationHelper {
+
+ }
+
+ private void addStringFormatAnnotation(BeanPropertyDefinition p) {
+ JsonFormat annotation = AnnotationHelper.class.getAnnotation(JsonFormat.class);
+ p.getField().getAllAnnotations().addIfNotPresent(annotation);
+ }
+
+
+ private Map<String, FieldDescriptor> getDescriptorForType(Class<?> type) {
+ try {
+ Descriptor invoke = (Descriptor) type.getMethod("getDescriptor").invoke(null);
+ Map<String, FieldDescriptor> descriptorsForType = new HashMap<>();
+ invoke.getFields()
+ .forEach(fieldDescriptor -> {
+ descriptorsForType.put(fieldDescriptor.getName(), fieldDescriptor);
+ descriptorsForType.put(fieldDescriptor.getJsonName(), fieldDescriptor);
+ });
+ return descriptorsForType;
+ } catch (Exception e) {
+ log.error("Error getting protobuf descriptor for swagger.", e);
+ return new HashMap<>();
+ }
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/application/src/main/java/org/apache/custos/config/WebConfig.java b/application/src/main/java/org/apache/custos/config/WebConfig.java
new file mode 100644
index 000000000..44a9d5aeb
--- /dev/null
+++ b/application/src/main/java/org/apache/custos/config/WebConfig.java
@@ -0,0 +1,24 @@
+package org.apache.custos.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.CorsRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+@Configuration
+public class WebConfig {
+
+ @Bean
+ public WebMvcConfigurer corsConfigurer() {
+ return new WebMvcConfigurer() {
+ @Override
+ public void addCorsMappings(CorsRegistry registry) {
+ registry.addMapping("/**")
+ .allowedOriginPatterns("*")
+ .allowedMethods("*")
+ .allowedHeaders("*")
+ .allowCredentials(true);
+ }
+ };
+ }
+}
diff --git a/application/src/main/resources/application.yml b/application/src/main/resources/application.yml
new file mode 100644
index 000000000..f15c9d6bb
--- /dev/null
+++ b/application/src/main/resources/application.yml
@@ -0,0 +1,91 @@
+server:
+ port: 8081
+
+custos:
+ region: "local"
+ identity:
+ auth:
+ cache:
+ enabled: false
+ size: 1024
+ credential:
+ prefix: custos-
+ tenant:
+ base:
+ uri: http://localhost/api/v1/tenant-management/oauth2/tenant
+ keys:
+ location:<CHANGE_PATH>/application/src/main/resources/keys
+ api:
+ domain: "http://localhost:8081"
+
+spring:
+ application:
+ name: custos-playground
+ datasource:
+ url: "jdbc:mysql://localhost:3306/custos"
+ username: admin
+ password: admin
+ driver-class-name: com.mysql.cj.jdbc.Driver
+ jpa:
+ hibernate:
+ ddl-auto: update
+ show-sql: false
+ database-platform: org.hibernate.dialect.MySQL8Dialect
+ cloud:
+ vault:
+ token: 00000000-0000-0000-0000-000000000000 # Update this with your token
+ scheme: http
+ kv:
+ enabled: true
+ host: localhost
+ port: 8200
+ authentication: token
+ connection-timeout: 5000
+ read-timeout: 15000
+ profiles:
+ active: local
+
+logging:
+ pattern:
+ level: '%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]'
+ level:
+ root: info
+
+iam:
+ server:
+ client:
+ id: admin-cli
+ url: http://localhost:8080/
+ admin:
+ username: admin
+ password: admin
+ super:
+ admin:
+ realm:
+ id: master
+ federated:
+ cilogon:
+ authorization:
+ endpoint: https://cilogon.org/authorize
+ token:
+ endpoint: https://cilogon.org/oauth2/token
+ userinfo:
+ endpoint: https://cilogon.org/oauth2/userinfo
+ issuer: https://cilogon.org
+ jwksUri: https://cilogon.org/oauth2/certs
+
+ciLogon:
+ admin:
+ client:
+ id: abc
+ secret: 1234
+ auth:
+ endpoint: https://test.cilogon.org/oauth2/oidc-cm
+ institutions:
+ endpoint: https://cilogon.org/idplist/
+
+springdoc:
+ swagger-ui:
+ title: CUSTOS API
+ oauth:
+ use-pkce-with-authorization-code-grant: true
\ No newline at end of file
diff --git a/application/src/main/resources/keys/public_key.pem b/application/src/main/resources/keys/public_key.pem
new file mode 100644
index 000000000..a0cd4531c
--- /dev/null
+++ b/application/src/main/resources/keys/public_key.pem
@@ -0,0 +1,9 @@
+-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzMeDgSU7m9R2Y8dOnGNA
+cFb5cod0Re3w02S04SCs7r1XzNT6APkDSl1YvFWVuRcjmFB1MGDiqUAyHnARruJX
+Zwvy2BlAGhEKc4mRbEkWTBn/y+pPSHPLNJ6YzIN0Pp8f9Wd3P10zzWED91b5tXcJ
+pYdaO+4pZ+rj7eb99A+Rg5mvmeiZDndUQGNORg8ofkJ5Rba5c6GDmgVuqIYvQ9cj
+SCw9mmCWbA9Sa62ulzz0oBG7KiEExyfwZRmcH5hcX4itqg5b2qPMod//VLCdap4I
+b7Jkzz0hGQ2EohBLe6thV4yFJung2yXZFK6bvJjo2WAK9DgBDEGThpx0UWqpksKx
+NwIDAQAB
+-----END PUBLIC KEY-----
diff --git a/application/src/main/resources/logback-spring.xml b/application/src/main/resources/logback-spring.xml
new file mode 100644
index 000000000..b8d3627c4
--- /dev/null
+++ b/application/src/main/resources/logback-spring.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+ <include resource="org/springframework/boot/logging/logback/base.xml"/>
+ <springProperty scope="context" name="appName" source="spring.application.name"/>
+ <springProperty scope="context" name="regionName" source="custos.region"/>
+
+ <!-- Rolling File Appender -->
+ <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>logs/custos-application.log</file>
+ <encoder>
+ <pattern>%date{YYYY-MM-dd HH:mm:ss.SSS} region=${regionName}, app=${appName}, host=${HOSTNAME}, traceID=%X{traceId:-NONE}, level=%-5level, [%thread] %logger{36} - %msg%n</pattern>
+ </encoder>
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ <fileNamePattern>logs/%d{yyyy-MM}/custos-application-log-%d{MM-dd-yyyy}-%i.log.gz</fileNamePattern>
+ <maxFileSize>10MB</maxFileSize>
+ <!-- number of days to keep the log files -->
+ <maxHistory>30</maxHistory>
+ <!-- If the total size of all log files exceeds this value, the oldest files will be removed -->
+ <totalSizeCap>1GB</totalSizeCap>
+ </rollingPolicy>
+ </appender>
+
+ <!-- Asynchronous Rolling File Appender -->
+ <appender name="ASYNC_FILE" class="ch.qos.logback.classic.AsyncAppender">
+ <appender-ref ref="FILE"/>
+ <queueSize>500</queueSize>
+ <discardingThreshold>0</discardingThreshold>
+ <includeCallerData>true</includeCallerData>
+ </appender>
+
+ <logger name="org.hibernate" level="ERROR"/>
+ <logger name="org.springframework" level="INFO"/>
+
+ <root level="INFO">
+ <appender-ref ref="ASYNC_FILE"/>
+ </root>
+</configuration>
diff --git a/custos-services/custos-core-services-client-stubs/messaging-core-service-client-stub/pom.xml b/core/pom.xml
similarity index 66%
rename from custos-services/custos-core-services-client-stubs/messaging-core-service-client-stub/pom.xml
rename to core/pom.xml
index 5b4594965..023a0ebe8 100644
--- a/custos-services/custos-core-services-client-stubs/messaging-core-service-client-stub/pom.xml
+++ b/core/pom.xml
@@ -21,53 +21,37 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
<parent>
- <artifactId>custos-core-services-client-stubs</artifactId>
+ <artifactId>custos</artifactId>
<groupId>org.apache.custos</groupId>
- <version>1.1-SNAPSHOT</version>
- <relativePath>../pom.xml</relativePath>
+ <version>1.1-SNAPSHOT</version>
</parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>messaging-core-service-client-stub</artifactId>
-
- <properties>
- <maven.compiler.source>17</maven.compiler.source>
- <maven.compiler.target>17</maven.compiler.target>
- </properties>
+ <artifactId>custos-core</artifactId>
<dependencies>
-<!-- <dependency>-->
-<!-- <groupId>org.springframework.boot</groupId>-->
-<!-- <artifactId>spring-boot-starter-web</artifactId>-->
-<!-- </dependency>-->
-
- <dependency>
- <groupId>io.grpc</groupId>
- <artifactId>grpc-stub</artifactId>
- </dependency>
<dependency>
- <groupId>io.grpc</groupId>
- <artifactId>grpc-protobuf</artifactId>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
- <groupId>com.google.api.grpc</groupId>
- <artifactId>proto-google-common-protos</artifactId>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-to-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
- <artifactId>grpc-netty</artifactId>
+ <artifactId>grpc-stub</artifactId>
</dependency>
<dependency>
- <groupId>javax.annotation</groupId>
- <artifactId>javax.annotation-api</artifactId>
+ <groupId>io.grpc</groupId>
+ <artifactId>grpc-protobuf</artifactId>
</dependency>
<dependency>
- <groupId>org.apache.custos</groupId>
- <artifactId>custos-integration-core</artifactId>
- <version>${project.version}</version>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
@@ -76,23 +60,24 @@
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
+ <version>1.7.0</version>
</extension>
</extensions>
+
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
+ <version>${protobuf.maven.plugin}</version>
<configuration>
- <protocArtifact>com.google.protobuf:protoc:${com.google.protobuf.util}:exe:${os.detected.classifier}</protocArtifact>
+ <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${io.grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
- <protoSourceRoot>../../custos-core-services/custos-messaging-core-service/src/main/proto</protoSourceRoot>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
- <goal>compile-python</goal>
<goal>compile-custom</goal>
</goals>
</execution>
@@ -101,4 +86,4 @@
</plugins>
</build>
-</project>
+</project>
\ No newline at end of file
diff --git a/custos-services/custos-core-services/custos-core-services-commons/src/main/java/org/apache/custos/core/services/api/commons/StatusUpdater.java b/core/src/main/java/org/apache/custos/core/commons/StatusUpdater.java
similarity index 77%
rename from custos-services/custos-core-services/custos-core-services-commons/src/main/java/org/apache/custos/core/services/api/commons/StatusUpdater.java
rename to core/src/main/java/org/apache/custos/core/commons/StatusUpdater.java
index a4e17c57b..3995c68f6 100644
--- a/custos-services/custos-core-services/custos-core-services-commons/src/main/java/org/apache/custos/core/services/api/commons/StatusUpdater.java
+++ b/core/src/main/java/org/apache/custos/core/commons/StatusUpdater.java
@@ -17,14 +17,13 @@
* under the License.
*/
-package org.apache.custos.core.services.api.commons;
+package org.apache.custos.core.commons;
-import org.apache.custos.core.services.api.commons.persistance.model.OperationStatus;
-import org.apache.custos.core.services.api.commons.persistance.model.StatusEntity;
-import org.apache.custos.core.services.api.commons.persistance.repository.StatusUpdaterRepository;
+import org.apache.custos.core.model.commons.OperationStatus;
+import org.apache.custos.core.model.commons.StatusEntity;
+import org.apache.custos.core.repo.commons.StatusUpdaterRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@@ -35,10 +34,13 @@ public class StatusUpdater {
private final Logger LOGGER = LoggerFactory.getLogger(StatusUpdater.class);
- @Autowired
- private StatusUpdaterRepository repository;
+ private final StatusUpdaterRepository repository;
+ public StatusUpdater(StatusUpdaterRepository repository) {
+ this.repository = repository;
+ }
+
public void updateStatus(String method, OperationStatus status, long traceId, String performedBy) {
try {
StatusEntity statusEntity = new StatusEntity();
@@ -47,14 +49,14 @@ public class StatusUpdater {
statusEntity.setTraceId(traceId);
statusEntity.setPerformedBy(performedBy);
repository.save(statusEntity);
+
} catch (Exception ex) {
LOGGER.error("Status update failed for event " + method + " and traceId " + traceId);
}
-
}
public List<StatusEntity> getOperationStatus(long traceId) {
- return repository.findAllByTraceId(traceId);
+ return repository.findAllByTraceId(traceId);
}
}
diff --git a/custos-services/custos-integration-services/tenant-management-service/src/main/java/org/apache/custos/tenant/management/utils/Constants.java b/core/src/main/java/org/apache/custos/core/constants/Constants.java
similarity index 53%
rename from custos-services/custos-integration-services/tenant-management-service/src/main/java/org/apache/custos/tenant/management/utils/Constants.java
rename to core/src/main/java/org/apache/custos/core/constants/Constants.java
index 21d332cb4..48f7a990e 100644
--- a/custos-services/custos-integration-services/tenant-management-service/src/main/java/org/apache/custos/tenant/management/utils/Constants.java
+++ b/core/src/main/java/org/apache/custos/core/constants/Constants.java
@@ -7,32 +7,39 @@
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.custos.tenant.management.utils;
+package org.apache.custos.core.constants;
-/**
- * This is constant class use for tenant management service
- */
public final class Constants {
- public static final String SYSTEM = "SYSTEM";
- public static final String GATEWAY_ADMIN = "GATEWAY_ADMIN";
- public static final String CLIENT_SECRET_BASIC = "client_secret_basic";
- public static final String TENANT_BASE_URI = "https://custos.scigap.org:32036/tenant-management/v1.0.0/oauth2/tenant";
+
+ public static final String REALM_AGENT = "custos-realm-agent";
+ public static final String AGENT_CLIENT = "agent-client";
+ public static final String OWNER_ID = "ownerId";
+ public static final String DESCRIPTION = "description";
+
+ public static final String ROLE_TYPE_REALM = "realm";
+ public static final String ROLE_TYPE_CLIENT = "client";
+
+
public static final String AUTHORIZATION_CODE = "code";
- public static final String CLIENT_CREDENTIALS = "client-credentials";
+ public static final String AUTHORIZATION_HEADER = "authorization";
public static final String PASSWORD_GRANT_TYPE = "password";
- public static final String REFRESH_TOKEN = "refresh-token";
+ public static final String CLIENT_CREDENTIALS = "client_credentials";
+ public static final String REFRESH_TOKEN = "refresh_token";
+ public static final String CLIENT_ID = "client_id";
+ public static final String CLIENT_SECRET_BASIC = "client_secret_basic";
- public static final String AUTHORIZATION_HEADER = "authorization";
- public static final String USER_TOKEN = "user-token";
+ public static final String SYSTEM = "SYSTEM";
+ public static final String GATEWAY_ADMIN = "GATEWAY_ADMIN";
+ public static final String USER_TOKEN = "user-token";
}
diff --git a/custos-services/custos-federated-services-clients/src/main/java/org/apache/custos/federated/services/clients/keycloak/UnauthorizedException.java b/core/src/main/java/org/apache/custos/core/exception/UnauthorizedException.java
similarity index 83%
rename from custos-services/custos-federated-services-clients/src/main/java/org/apache/custos/federated/services/clients/keycloak/UnauthorizedException.java
rename to core/src/main/java/org/apache/custos/core/exception/UnauthorizedException.java
index 2a818f4f8..354cc7ddf 100644
--- a/custos-services/custos-federated-services-clients/src/main/java/org/apache/custos/federated/services/clients/keycloak/UnauthorizedException.java
+++ b/core/src/main/java/org/apache/custos/core/exception/UnauthorizedException.java
@@ -17,14 +17,18 @@
* under the License.
*/
-package org.apache.custos.federated.services.clients.keycloak;
+package org.apache.custos.core.exception;
/**
* UnAuthorized Exception
*/
-public class UnauthorizedException extends Exception {
+public class UnauthorizedException extends RuntimeException {
public UnauthorizedException(String msg, Throwable throwable) {
super(msg, throwable);
}
+
+ public UnauthorizedException(String message) {
+ super(message);
+ }
}
diff --git a/custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/AuthzCache.java b/core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCache.java
similarity index 95%
rename from custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/AuthzCache.java
rename to core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCache.java
index 634965f45..dd9302a5a 100644
--- a/custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/AuthzCache.java
+++ b/core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCache.java
@@ -16,7 +16,8 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.custos.identity.authzcache;
+
+package org.apache.custos.core.identity.authzcache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -31,7 +32,7 @@ public class AuthzCache extends LinkedHashMap<AuthzCacheIndex, AuthzCacheEntry>
private final static Logger LOGGER = LoggerFactory.getLogger(AuthzCache.class);
- private int MAX_SIZE;
+ private final int MAX_SIZE;
public AuthzCache(@Value("${custos.identity.auth.cache.size:1024}") int initialCapacity) {
super(initialCapacity);
diff --git a/custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/AuthzCacheEntry.java b/core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCacheEntry.java
similarity index 93%
rename from custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/AuthzCacheEntry.java
rename to core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCacheEntry.java
index 9b6840a15..d182b90ed 100644
--- a/custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/AuthzCacheEntry.java
+++ b/core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCacheEntry.java
@@ -16,17 +16,19 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.custos.identity.authzcache;
+
+package org.apache.custos.core.identity.authzcache;
/**
* Cache entry in the default authorization cache.
*/
public class AuthzCacheEntry {
+
//authorization decision for the authorization request associated with this cache entry.
private boolean decision;
//time to live value for the access token in seconds.
private long expiryTime;
- //time stamp in milli seconds at the time this entry is put into the cache
+ //time stamp in milliseconds at the time this entry is put into the cache
private long entryTimestamp;
public AuthzCacheEntry(boolean decision, long expiryTime, long entryTimestamp) {
diff --git a/custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/AuthzCacheIndex.java b/core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCacheIndex.java
similarity index 68%
rename from custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/AuthzCacheIndex.java
rename to core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCacheIndex.java
index db68ac976..8c873fe6e 100644
--- a/custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/AuthzCacheIndex.java
+++ b/core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCacheIndex.java
@@ -16,7 +16,8 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.custos.identity.authzcache;
+
+package org.apache.custos.core.identity.authzcache;
/**
* Cache index of the default authorization cache.
@@ -25,14 +26,12 @@ public class AuthzCacheIndex {
private String subject;
private String oauthAccessToken;
-// private String action;
- private String gatewayId;
+ private String tenantId;
- public AuthzCacheIndex(String userName, String gatewayId, String accessToken) {
+ public AuthzCacheIndex(String userName, String tenantId, String accessToken) {
this.subject = userName;
this.oauthAccessToken = accessToken;
-// this.action = actionString;
- this.gatewayId = gatewayId;
+ this.tenantId = tenantId;
}
public String getSubject() {
@@ -43,14 +42,6 @@ public class AuthzCacheIndex {
this.subject = subject;
}
-// public String getAction() {
-// return action;
-// }
-//
-// public void setAction(String action) {
-// this.action = action;
-// }
-
public String getOauthAccessToken() {
return oauthAccessToken;
}
@@ -59,30 +50,28 @@ public class AuthzCacheIndex {
this.oauthAccessToken = oauthAccessToken;
}
- public String getGatewayId() {
- return gatewayId;
+ public String getTenantId() {
+ return tenantId;
}
- public void setGatewayId(String gatewayId) {
- this.gatewayId = gatewayId;
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
}
/*Equals and hash code methods are overridden since this is being used as an index of a map and that containsKey method
- * should return true if the values of two index objects are equal.*/
+ * should return true if the values of two index objects are equal.*/
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != getClass()) {
return false;
}
return ((this.getSubject().equals(((AuthzCacheIndex) other).getSubject()))
- && (this.getGatewayId().equals(((AuthzCacheIndex) other).getGatewayId()))
+ && (this.getTenantId().equals(((AuthzCacheIndex) other).getTenantId()))
&& (this.getOauthAccessToken().equals(((AuthzCacheIndex) other).getOauthAccessToken())));
- //&& (this.getAction().equals(((AuthzCacheIndex) other).getAction())));
}
@Override
public int hashCode() {
- return this.getSubject().hashCode() + this.getOauthAccessToken().hashCode() + this.getGatewayId().hashCode();
- //+ this.getAction().hashCode();
+ return this.getSubject().hashCode() + this.getOauthAccessToken().hashCode() + this.getTenantId().hashCode();
}
}
diff --git a/core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCacheManager.java b/core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCacheManager.java
new file mode 100644
index 000000000..cbf13b7c2
--- /dev/null
+++ b/core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCacheManager.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.custos.core.identity.authzcache;
+
+
+import org.apache.custos.core.identity.exceptions.AuthSecurityException;
+
+/**
+ * The AuthzCacheManager interface represents a cache manager for authorization decisions.
+ */
+public interface AuthzCacheManager {
+
+ /**
+ * Retrieves the cached status of the authorization for the given AuthzCacheIndex
+ *
+ * @param authzCacheIndex The AuthzCacheIndex representing the authorization request.
+ * @return The AuthzCachedStatus enum indicating the status of the authorization cache.
+ * @throws AuthSecurityException If there is a security exception while retrieving the cached status.
+ */
+ AuthzCachedStatus getAuthzCachedStatus(AuthzCacheIndex authzCacheIndex) throws AuthSecurityException;
+
+ /**
+ * Adds an entry to the authorization cache.
+ *
+ * @param authzCacheIndex The AuthzCacheIndex representing the authorization request.
+ * @param authzCacheEntry The AuthzCacheEntry containing the authorization decision and metadata.
+ * @throws AuthSecurityException If there is a security exception while adding the entry to the cache.
+ */
+ void addToAuthzCache(AuthzCacheIndex authzCacheIndex, AuthzCacheEntry authzCacheEntry) throws AuthSecurityException;
+
+ /**
+ * Checks if the authorization decision is cached for the given AuthzCacheIndex.
+ *
+ * @param authzCacheIndex The AuthzCacheIndex representing the authorization request.
+ * @return true if the authorization decision is cached, false otherwise.
+ * @throws AuthSecurityException If there is a security exception while checking the authorization cache.
+ */
+ boolean isAuthzDecisionCached(AuthzCacheIndex authzCacheIndex) throws AuthSecurityException;
+
+ /**
+ * Retrieves the authorization cache entry for the given AuthzCacheIndex.
+ *
+ * @param authzCacheIndex The AuthzCacheIndex representing the authorization request.
+ * @return The AuthzCacheEntry containing the authorization decision and metadata.
+ * @throws AuthSecurityException If there is a security exception while retrieving the cache entry.
+ */
+ AuthzCacheEntry getAuthzCacheEntry(AuthzCacheIndex authzCacheIndex) throws AuthSecurityException;
+
+ /**
+ * Removes an entry from the authorization cache.
+ *
+ * @param authzCacheIndex The AuthzCacheIndex representing the authorization request.
+ * @throws AuthSecurityException If there is a security exception while removing the entry from the cache.
+ */
+ void removeAuthzCacheEntry(AuthzCacheIndex authzCacheIndex) throws AuthSecurityException;
+
+ /**
+ * Clears the cache used for authorization decisions.
+ *
+ * @throws AuthSecurityException if there is a security exception while clearing the cache.
+ */
+ void clearCache() throws AuthSecurityException;
+
+}
diff --git a/custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/AuthzCachedStatus.java b/core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCachedStatus.java
similarity index 88%
rename from custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/AuthzCachedStatus.java
rename to core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCachedStatus.java
index cded51983..f8a280cdc 100644
--- a/custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/AuthzCachedStatus.java
+++ b/core/src/main/java/org/apache/custos/core/identity/authzcache/AuthzCachedStatus.java
@@ -16,14 +16,16 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.custos.identity.authzcache;
+
+package org.apache.custos.core.identity.authzcache;
/**
* This enum defines the status of the authorization cache returned by the authorization cache manager
* when an authorization status is checked against an authorization request.
*/
public enum AuthzCachedStatus {
- /*Authorization decision is cached for the given authrization request and the decision authorizes the request.*/
+
+ /*Authorization decision is cached for the given authorization request and the decision authorizes the request.*/
AUTHORIZED,
/*Authorization decision is cached for the given authorization request and the decision denies authorization.*/
NOT_AUTHORIZED,
diff --git a/custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/DefaultAuthzCacheManager.java b/core/src/main/java/org/apache/custos/core/identity/authzcache/DefaultAuthzCacheManager.java
similarity index 92%
rename from custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/DefaultAuthzCacheManager.java
rename to core/src/main/java/org/apache/custos/core/identity/authzcache/DefaultAuthzCacheManager.java
index 19f485aef..445abf0a3 100644
--- a/custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/authzcache/DefaultAuthzCacheManager.java
+++ b/core/src/main/java/org/apache/custos/core/identity/authzcache/DefaultAuthzCacheManager.java
@@ -16,7 +16,8 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.custos.identity.authzcache;
+
+package org.apache.custos.core.identity.authzcache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -27,7 +28,6 @@ public class DefaultAuthzCacheManager implements AuthzCacheManager {
@Autowired
private AuthzCache cache;
-
@Override
public AuthzCachedStatus getAuthzCachedStatus(AuthzCacheIndex authzCacheIndex) {
if (isAuthzDecisionCached(authzCacheIndex)) {
@@ -35,18 +35,20 @@ public class DefaultAuthzCacheManager implements AuthzCacheManager {
long expiryTime = cacheEntry.getExpiryTime();
long currentTime = System.currentTimeMillis();
long timePassed = (currentTime - cacheEntry.getEntryTimestamp()) / 1000;
+
if (expiryTime > timePassed) {
- //access token is still valid. Hence, return the cached decision
+ // access token is still valid. Hence, return the cached decision
if (cacheEntry.getDecision()) {
return AuthzCachedStatus.AUTHORIZED;
} else {
return AuthzCachedStatus.NOT_AUTHORIZED;
}
} else {
- //access token has been expired. Hence, remove the entry and return.
+ // access token has been expired. Hence, remove the entry and return.
removeAuthzCacheEntry(authzCacheIndex);
return AuthzCachedStatus.NOT_CACHED;
}
+
} else {
return AuthzCachedStatus.NOT_CACHED;
}
diff --git a/custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/exceptions/CustosSecurityException.java b/core/src/main/java/org/apache/custos/core/identity/exceptions/AuthSecurityException.java
similarity index 84%
rename from custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/exceptions/CustosSecurityException.java
rename to core/src/main/java/org/apache/custos/core/identity/exceptions/AuthSecurityException.java
index 4d380a7c6..c2579c297 100644
--- a/custos-services/custos-core-services/identity-core-service/src/main/java/org/apache/custos/identity/exceptions/CustosSecurityException.java
+++ b/core/src/main/java/org/apache/custos/core/identity/exceptions/AuthSecurityException.java
@@ -17,11 +17,11 @@
* under the License.
*/
-package org.apache.custos.identity.exceptions;
+package org.apache.custos.core.identity.exceptions;
-public class CustosSecurityException extends Exception{
+public class AuthSecurityException extends Exception {
- public CustosSecurityException(String message) {
+ public AuthSecurityException(String message) {
super(message);
}
}
diff --git a/custos-services/custos-core-services/federated-authentication-core-service/src/main/java/org/apache/custos/federated/authentication/mapper/ModelMapper.java b/core/src/main/java/org/apache/custos/core/mapper/federated/InstitutionMapper.java
similarity index 69%
rename from custos-services/custos-core-services/federated-authentication-core-service/src/main/java/org/apache/custos/federated/authentication/mapper/ModelMapper.java
rename to core/src/main/java/org/apache/custos/core/mapper/federated/InstitutionMapper.java
index 3dbb04681..562dd3946 100644
--- a/custos-services/custos-core-services/federated-authentication-core-service/src/main/java/org/apache/custos/federated/authentication/mapper/ModelMapper.java
+++ b/core/src/main/java/org/apache/custos/core/mapper/federated/InstitutionMapper.java
@@ -17,16 +17,14 @@
* under the License.
*/
-package org.apache.custos.federated.authentication.mapper;
+package org.apache.custos.core.mapper.federated;
-import org.apache.custos.federated.authentication.persistance.model.CILogonInstitution;
-import org.apache.custos.federated.authentication.service.Institution;
+import org.apache.custos.core.federated.authentication.api.Institution;
+import org.apache.custos.core.model.federated.CILogonInstitution;
-public class ModelMapper {
+public class InstitutionMapper {
public static CILogonInstitution convert(long tenantId, String institutionId, String type, String performedBy) {
-
-
String id = institutionId + "@" + tenantId;
CILogonInstitution ciLogonInstitution = new CILogonInstitution();
@@ -39,30 +37,13 @@ public class ModelMapper {
}
return ciLogonInstitution;
-
}
-
public static Institution convert(CILogonInstitution cache) {
-
Institution.Builder msg = Institution.newBuilder();
-
msg.setEntityId(cache.getInstitutionId());
-
return msg.build();
}
-
- public static Institution convert(org.apache.custos.federated.services.clients.cilogon.CILogonInstitution ciLogonInstitution) {
-
- Institution.Builder msg = Institution.newBuilder();
-
- msg.setEntityId(ciLogonInstitution.getEntityId());
- msg.setDisplayName(ciLogonInstitution.getDisplayName());
- msg.setOrganizationName(ciLogonInstitution.getOrganizationName());
- msg.setRandS(ciLogonInstitution.isRandS());
- return msg.build();
-
- }
}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/mapper/AttributeUpdateMetadataMapper.java b/core/src/main/java/org/apache/custos/core/mapper/tenant/AttributeUpdateMetadataMapper.java
similarity index 79%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/mapper/AttributeUpdateMetadataMapper.java
rename to core/src/main/java/org/apache/custos/core/mapper/tenant/AttributeUpdateMetadataMapper.java
index b32f02468..cfae93e5b 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/mapper/AttributeUpdateMetadataMapper.java
+++ b/core/src/main/java/org/apache/custos/core/mapper/tenant/AttributeUpdateMetadataMapper.java
@@ -17,29 +17,28 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.mapper;
+package org.apache.custos.core.mapper.tenant;
-import org.apache.custos.tenant.profile.persistance.model.TenantAttributeUpdateMetadata;
-import org.apache.custos.tenant.profile.persistance.model.Contact;
-import org.apache.custos.tenant.profile.persistance.model.RedirectURI;
-import org.apache.custos.tenant.profile.persistance.model.Tenant;
+import org.apache.custos.core.model.tenant.Contact;
+import org.apache.custos.core.model.tenant.RedirectURI;
+import org.apache.custos.core.model.tenant.Tenant;
+import org.apache.custos.core.model.tenant.TenantAttributeUpdateMetadata;
import java.util.HashSet;
import java.util.Set;
/**
- * This class maps attributes between grpc TenantAttributeUpdateMetadata to DB AttributeUpdateMetadata table
+ * This class is responsible for creating and mapping attribute update metadata for a Tenant object.
*/
public class AttributeUpdateMetadataMapper {
-
/**
- * This creates Attribute update entity List from comparing oldTenant and newTenant
+ * Creates a set of TenantAttributeUpdateMetadata entities based on the differences between the old and new Tenant objects.
*
- * @param oldTenant
- * @param newTenant
- * @param updatedBy
- * @return
+ * @param oldTenant The old Tenant object.
+ * @param newTenant The new Tenant object.
+ * @param updatedBy The user who updated the Tenant object.
+ * @return A set of TenantAttributeUpdateMetadata entities representing the attribute updates.
*/
public static Set<TenantAttributeUpdateMetadata> createAttributeUpdateMetadataEntity(Tenant oldTenant, Tenant newTenant, String updatedBy) {
@@ -125,7 +124,7 @@ public class AttributeUpdateMetadataMapper {
metadataSet.add(attributeUpdateMetadata);
}
- Set diff = difference(oldTenant.getRedirectURIS(), newTenant.getRedirectURIS());
+ Set diff = difference(oldTenant.getRedirectURIS(), newTenant.getRedirectURIS());
if (!diff.isEmpty()) {
TenantAttributeUpdateMetadata attributeUpdateMetadata = new TenantAttributeUpdateMetadata();
@@ -150,48 +149,40 @@ public class AttributeUpdateMetadataMapper {
return metadataSet;
}
-
/**
- * create attribute update metadata from db entity
- * @param metadata
- * @return
+ * Creates a TenantAttributeUpdateMetadata object based on the given TenantAttributeUpdateMetadata entity.
+ *
+ * @param metadata The TenantAttributeUpdateMetadata entity to create the TenantAttributeUpdateMetadata object from.
+ * @return A TenantAttributeUpdateMetadata object representing the attribute update metadata.
*/
- public static org.apache.custos.tenant.profile.service.TenantAttributeUpdateMetadata createAttributeUpdateMetadataFromEntity (TenantAttributeUpdateMetadata metadata) {
+ public static org.apache.custos.core.tenant.profile.api.TenantAttributeUpdateMetadata createAttributeUpdateMetadataFromEntity(TenantAttributeUpdateMetadata metadata) {
- return org.apache.custos.tenant.profile.service.TenantAttributeUpdateMetadata.newBuilder()
- .setUpdatedAt(metadata.getUpdatedAt().toString())
+ return org.apache.custos.core.tenant.profile.api.TenantAttributeUpdateMetadata.newBuilder()
+ .setUpdatedAt(metadata.getUpdatedAt().toString())
.setUpdatedBy(metadata.getUpdatedBy())
.setUpdatedAttributeValue(metadata.getUpdatedFieldValue())
.setUpdatedAttribute(metadata.getUpdatedFieldKey())
.build();
}
-
-
private static <T> Set<T> difference(final Set<T> setOne, final Set<T> setTwo) {
Set<T> result = new HashSet<T>(setOne);
result.removeIf(setTwo::contains);
return result;
}
- private static String setToString(Set<Object> result){
- StringBuffer buffer = new StringBuffer();
+ private static String setToString(Set<Object> result) {
+ StringBuilder builder = new StringBuilder();
if (!result.isEmpty()) {
- for (Object t : result){
+ for (Object t : result) {
if (t instanceof RedirectURI) {
- buffer.append(((RedirectURI)t).getRedirectURI());
+ builder.append(((RedirectURI) t).getRedirectURI());
} else {
- buffer.append(((Contact)t).getContactInfo());
+ builder.append(((Contact) t).getContactInfo());
}
- buffer.append(",");
+ builder.append(",");
}
}
- return buffer.toString();
+ return builder.toString();
}
-
-
-
-
-
-
}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/mapper/StatusUpdateMetadataMapper.java b/core/src/main/java/org/apache/custos/core/mapper/tenant/StatusUpdateMetadataMapper.java
similarity index 52%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/mapper/StatusUpdateMetadataMapper.java
rename to core/src/main/java/org/apache/custos/core/mapper/tenant/StatusUpdateMetadataMapper.java
index 5db2b6b5b..8ba433f0e 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/mapper/StatusUpdateMetadataMapper.java
+++ b/core/src/main/java/org/apache/custos/core/mapper/tenant/StatusUpdateMetadataMapper.java
@@ -17,32 +17,29 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.mapper;
+package org.apache.custos.core.mapper.tenant;
-import org.apache.custos.tenant.profile.persistance.model.TenantStatusUpdateMetadata;
-import org.apache.custos.tenant.profile.persistance.model.Tenant;
-import org.apache.custos.tenant.profile.service.TenantStatus;
+import org.apache.custos.core.model.tenant.Tenant;
+import org.apache.custos.core.model.tenant.TenantStatusUpdateMetadata;
+import org.apache.custos.core.tenant.profile.api.TenantStatus;
import java.util.HashSet;
import java.util.Set;
/**
- * This class maps attributes between grpc TenantStatusUpdateMetadata to DB StatusUpdateMetadata table
+ * The StatusUpdateMetadataMapper class provides utility methods to create and convert status update metadata.
*/
public class StatusUpdateMetadataMapper {
-
/**
- * Creates Status update entity for save in DB
+ * Creates a set of TenantStatusUpdateMetadata entity based on the given parameters.
*
- * @param {@link org.apache.custos.tenant.profile.service.Tenant} tenant
- * @param updatedBy
- * @return
+ * @param tenant The Tenant object representing the tenant.
+ * @param updatedBy The username of the user who updated the status.
+ * @return A set of TenantStatusUpdateMetadata representing the status update metadata.
*/
- public static Set<TenantStatusUpdateMetadata> createStatusUpdateMetadataEntity(Tenant tenant, String updatedBy) {
-
+ public static Set<TenantStatusUpdateMetadata> createStatusUpdateMetadataEntity(Tenant tenant, String updatedBy) {
Set<TenantStatusUpdateMetadata> metaDataSet = new HashSet<>();
-
TenantStatusUpdateMetadata metadata = new TenantStatusUpdateMetadata();
metadata.setTenant(tenant);
metadata.setUpdatedBy(updatedBy);
@@ -50,21 +47,19 @@ public class StatusUpdateMetadataMapper {
metaDataSet.add(metadata);
return metaDataSet;
-
}
/**
- * convert TenantStatusUpdateMetadataEntity to gRPC TenantStatusUpdateMetadata
+ * Creates a new instance of {@link org.apache.custos.core.tenant.profile.api.TenantStatusUpdateMetadata}
+ * by converting the given {@link TenantStatusUpdateMetadata} object.
*
- * @param metadata
- * @return TenantStatusUpdateMetadata
+ * @param metadata The {@link TenantStatusUpdateMetadata} object to convert.
+ * @return A new instance of {@link org.apache.custos.core.tenant.profile.api.TenantStatusUpdateMetadata}.
*/
- public static org.apache.custos.tenant.profile.service.TenantStatusUpdateMetadata createTenantStatusMetadataFrom(TenantStatusUpdateMetadata metadata) {
- return org.apache.custos.tenant.profile.service.TenantStatusUpdateMetadata.newBuilder()
+ public static org.apache.custos.core.tenant.profile.api.TenantStatusUpdateMetadata createTenantStatusMetadataFrom(TenantStatusUpdateMetadata metadata) {
+ return org.apache.custos.core.tenant.profile.api.TenantStatusUpdateMetadata.newBuilder()
.setUpdatedAt(metadata.getUpdatedAt().toString())
.setUpdatedBy(metadata.getUpdatedBy())
.setUpdatedStatus(TenantStatus.valueOf(metadata.getUpdatedStatus())).build();
-
}
-
}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/mapper/TenantMapper.java b/core/src/main/java/org/apache/custos/core/mapper/tenant/TenantMapper.java
similarity index 68%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/mapper/TenantMapper.java
rename to core/src/main/java/org/apache/custos/core/mapper/tenant/TenantMapper.java
index f43f5cb23..b8bbbb0a7 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/mapper/TenantMapper.java
+++ b/core/src/main/java/org/apache/custos/core/mapper/tenant/TenantMapper.java
@@ -17,34 +17,31 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.mapper;
+package org.apache.custos.core.mapper.tenant;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.apache.custos.tenant.profile.persistance.model.Contact;
-import org.apache.custos.tenant.profile.persistance.model.RedirectURI;
-import org.apache.custos.tenant.profile.persistance.model.Tenant;
-import org.apache.custos.tenant.profile.service.TenantStatus;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.apache.custos.core.model.tenant.Contact;
+import org.apache.custos.core.model.tenant.RedirectURI;
+import org.apache.custos.core.model.tenant.Tenant;
+import org.apache.custos.core.tenant.profile.api.TenantStatus;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
/**
- * This class maps attributes between grpc Tenant to DB Tenant table
+ * The TenantMapper class provides methods for mapping between Tenant objects and Tenant entity objects.
*/
public class TenantMapper {
- private static final Logger LOGGER = LoggerFactory.getLogger(TenantMapper.class);
-
/**
- * Maps gRPC Tenant Model to DB Layer Tenant Entity
+ * Creates a Tenant entity object from a Tenant object.
*
- * @param {@link org.apache.custos.tenant.profile.service.Tenant} tenant
- * @return Tenant
+ * @param tenant the Tenant object to convert
+ * @return the created Tenant entity object
*/
- public static Tenant createTenantEntityFromTenant(org.apache.custos.tenant.profile.service.Tenant tenant) {
+ public static Tenant createTenantEntityFromTenant(org.apache.custos.core.tenant.profile.api.Tenant tenant) {
Tenant tenantEntity = new Tenant();
tenantEntity.setId(tenant.getTenantId());
tenantEntity.setName(tenant.getClientName());
@@ -61,7 +58,6 @@ public class TenantMapper {
tenantEntity.setUri(tenant.getClientUri());
tenantEntity.setParentId(tenant.getParentTenantId());
tenantEntity.setApplicationType(tenant.getApplicationType());
-// tenantEntity.setJwks(tenant.getJwksCount() > 0 ? getJWKSAsString(tenant.getJwksMap()) : null);
tenantEntity.setJwksUri(tenant.getJwksUri());
tenantEntity.setExample_extension_parameter(tenant.getExampleExtensionParameter());
tenantEntity.setTosUri(tenant.getTosUri());
@@ -70,11 +66,8 @@ public class TenantMapper {
tenantEntity.setSoftwareVersion(tenant.getSoftwareVersion());
tenantEntity.setRefreshTokenLifetime(tenant.getRefeshTokenLifetime());
-
- Set<Contact> contactSet = new HashSet<Contact>();
-
+ Set<Contact> contactSet = new HashSet<>();
for (int i = 0; i < tenant.getContactsCount(); i++) {
-
String contact = tenant.getContacts(i);
Contact contactEntity = new Contact();
contactEntity.setTenant(tenantEntity);
@@ -83,10 +76,8 @@ public class TenantMapper {
}
tenantEntity.setContacts(contactSet);
-
- Set<RedirectURI> redirectURIS = new HashSet<RedirectURI>();
+ Set<RedirectURI> redirectURIS = new HashSet<>();
for (int i = 0; i < tenant.getRedirectUrisCount(); i++) {
-
String uri = tenant.getRedirectUris(i);
RedirectURI redirectURIEntity = new RedirectURI();
redirectURIEntity.setTenant(tenantEntity);
@@ -97,18 +88,15 @@ public class TenantMapper {
tenantEntity.setRedirectURIS(redirectURIS);
return tenantEntity;
-
}
-
/**
- * Transform TenantEntity to Tenant
+ * Converts a Tenant entity object to a Tenant object.
*
- * @param tenantEntity
- * @return tenant
+ * @param tenantEntity the Tenant entity object to convert
+ * @return the created Tenant object
*/
- public static org.apache.custos.tenant.profile.service.Tenant createTenantFromTenantEntity(Tenant tenantEntity) {
-
+ public static org.apache.custos.core.tenant.profile.api.Tenant createTenantFromTenantEntity(Tenant tenantEntity) {
Set<Contact> contacts = tenantEntity.getContacts();
List<String> contactList = new ArrayList<>();
if (contacts != null && !contacts.isEmpty()) {
@@ -117,7 +105,6 @@ public class TenantMapper {
}
}
-
Set<RedirectURI> redirectURIS = tenantEntity.getRedirectURIS();
List<String> uriList = new ArrayList<>();
if (redirectURIS != null && !redirectURIS.isEmpty()) {
@@ -126,13 +113,12 @@ public class TenantMapper {
}
}
-
- return org.apache.custos.tenant.profile.service.Tenant.newBuilder()
+ return org.apache.custos.core.tenant.profile.api.Tenant.newBuilder()
.setAdminEmail(tenantEntity.getAdminEmail())
.setAdminFirstName(tenantEntity.getAdminFirstName())
.setAdminLastName(tenantEntity.getAdminLastName())
.setDomain(tenantEntity.getDomain())
- .setClientUri(tenantEntity.getUri()==null?tenantEntity.getLogoURI():tenantEntity.getUri())
+ .setClientUri(tenantEntity.getUri() == null ? tenantEntity.getLogoURI() : tenantEntity.getUri())
.setRequesterEmail(tenantEntity.getRequesterEmail())
.setScope(tenantEntity.getScope())
.addAllContacts(contactList)
@@ -153,54 +139,39 @@ public class TenantMapper {
.setRefeshTokenLifetime(tenantEntity.getRefreshTokenLifetime())
.setParentTenantId(tenantEntity.getParentId())
.build();
-
-
}
-
- public static String getTenantInfoAsString(org.apache.custos.tenant.profile.service.Tenant tenant) {
+ /**
+ * Retrieves the information of a tenant object as a formatted string.
+ *
+ * @param tenant the tenant object to retrieve the information from
+ * @return the tenant information as a string
+ */
+ public static String getTenantInfoAsString(org.apache.custos.core.tenant.profile.api.Tenant tenant) {
StringBuffer buffer = new StringBuffer();
- buffer.append("tenantName : " + tenant.getClientName());
+ buffer.append("tenantName : ").append(tenant.getClientName());
buffer.append("\n");
- buffer.append("tenantId : " + tenant.getTenantId());
+ buffer.append("tenantId : ").append(tenant.getTenantId());
buffer.append("\n");
- buffer.append("tenantAdminEmail : " + tenant.getAdminEmail());
+ buffer.append("tenantAdminEmail : ").append(tenant.getAdminEmail());
buffer.append("\n");
- buffer.append("tenantAdminFirstName : " + tenant.getAdminFirstName());
+ buffer.append("tenantAdminFirstName : ").append(tenant.getAdminFirstName());
buffer.append("\n");
- buffer.append("tenantAdminLastName : " + tenant.getAdminLastName());
- buffer.append("domain : " + tenant.getDomain());
+ buffer.append("tenantAdminLastName : ").append(tenant.getAdminLastName());
+ buffer.append("domain : ").append(tenant.getDomain());
buffer.append("\n");
- buffer.append("logoURI : " + tenant.getClientUri());
+ buffer.append("logoURI : ").append(tenant.getClientUri());
buffer.append("\n");
buffer.append("\n");
- buffer.append("requesterEmail : " + tenant.getRequesterEmail());
+ buffer.append("requesterEmail : ").append(tenant.getRequesterEmail());
buffer.append("\n");
- buffer.append("tenantScope : " + tenant.getScope());
+ buffer.append("tenantScope : ").append(tenant.getScope());
buffer.append("\n");
- buffer.append("contacts : " + tenant.getContactsList().toString());
+ buffer.append("contacts : ").append(tenant.getContactsList());
buffer.append("\n");
- buffer.append("redirectURIs : " + tenant.getRedirectUrisList().toString());
+ buffer.append("redirectURIs : ").append(tenant.getRedirectUrisList());
buffer.append("\n");
return buffer.toString();
-
- }
-
-
- private static String getJWKSAsString(Map<String, String> jwksMap) {
- ObjectMapper objectMapper = new ObjectMapper();
-
- try {
- return objectMapper.writeValueAsString(jwksMap);
- } catch (JsonProcessingException e) {
- LOGGER.error("Error occurred while printing json ", e);
- return null;
- }
}
-
-
}
-
-
-
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/mapper/AttributeUpdateMetadataMapper.java b/core/src/main/java/org/apache/custos/core/mapper/user/AttributeUpdateMetadataMapper.java
similarity index 77%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/mapper/AttributeUpdateMetadataMapper.java
rename to core/src/main/java/org/apache/custos/core/mapper/user/AttributeUpdateMetadataMapper.java
index f56f37c46..9e720b393 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/mapper/AttributeUpdateMetadataMapper.java
+++ b/core/src/main/java/org/apache/custos/core/mapper/user/AttributeUpdateMetadataMapper.java
@@ -17,35 +17,37 @@
* under the License.
*/
-package org.apache.custos.user.profile.mapper;
+package org.apache.custos.core.mapper.user;
-
-import org.apache.custos.user.profile.persistance.model.AttributeUpdateMetadata;
-import org.apache.custos.user.profile.persistance.model.UserProfile;
-import org.apache.custos.user.profile.service.UserProfileAttributeUpdateMetadata;
+import org.apache.custos.core.model.user.AttributeUpdateMetadata;
+import org.apache.custos.core.model.user.UserProfile;
+import org.apache.custos.core.user.profile.api.UserProfileAttributeUpdateMetadata;
import java.util.HashSet;
+import java.util.Objects;
import java.util.Set;
/**
- * This class maps attributes between grpc TenantAttributeUpdateMetadata to DB AttributeUpdateMetadata table
+ * This class maps attributes between protobuf TenantAttributeUpdateMetadata to DB AttributeUpdateMetadata table
*/
public class AttributeUpdateMetadataMapper {
/**
- * This creates Attribute update entity List from comparing oldTenant and newTenant
+ * Creates a set of AttributeUpdateMetadata objects based on the changes made to a UserProfile object.
*
- * @param updatedBy
- * @return
+ * @param oldProf The old UserProfile object.
+ * @param newProf The new UserProfile object.
+ * @param updatedBy The user who updated the UserProfile.
+ * @return A set of AttributeUpdateMetadata objects representing the updated fields in the UserProfile.
*/
public static Set<AttributeUpdateMetadata> createAttributeUpdateMetadataEntity(UserProfile oldProf, UserProfile newProf, String updatedBy) {
Set<AttributeUpdateMetadata> metadataSet = new HashSet<>();
- if (!(oldProf.getTenantId() == newProf.getTenantId())) {
+ if (!(Objects.equals(oldProf.getTenantId(), newProf.getTenantId()))) {
AttributeUpdateMetadata attributeUpdateMetadata = new AttributeUpdateMetadata();
attributeUpdateMetadata.setUserProfile(newProf);
- attributeUpdateMetadata.setUpdatedFieldKey("tenanId");
+ attributeUpdateMetadata.setUpdatedFieldKey("tenantId");
attributeUpdateMetadata.setUpdatedFieldValue(String.valueOf(newProf.getTenantId()));
attributeUpdateMetadata.setUpdatedBy(updatedBy);
metadataSet.add(attributeUpdateMetadata);
@@ -92,13 +94,12 @@ public class AttributeUpdateMetadataMapper {
/**
- * create attribute update metadata from db entity
+ * Creates a UserProfileAttributeUpdateMetadata object from an AttributeUpdateMetadata object.
*
- * @param metadata
- * @return
+ * @param metadata The AttributeUpdateMetadata object to convert.
+ * @return A UserProfileAttributeUpdateMetadata object with values populated from the metadata parameter.
*/
public static UserProfileAttributeUpdateMetadata createAttributeUpdateMetadataFromEntity(AttributeUpdateMetadata metadata) {
-
return UserProfileAttributeUpdateMetadata.newBuilder()
.setUpdatedAt(metadata.getUpdatedAt().toString())
.setUpdatedBy(metadata.getUpdatedBy())
@@ -106,6 +107,4 @@ public class AttributeUpdateMetadataMapper {
.setUpdatedAttribute(metadata.getUpdatedFieldKey())
.build();
}
-
-
}
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/mapper/GroupMapper.java b/core/src/main/java/org/apache/custos/core/mapper/user/GroupMapper.java
similarity index 78%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/mapper/GroupMapper.java
rename to core/src/main/java/org/apache/custos/core/mapper/user/GroupMapper.java
index 6cd8c5f59..ab45a643d 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/mapper/GroupMapper.java
+++ b/core/src/main/java/org/apache/custos/core/mapper/user/GroupMapper.java
@@ -17,34 +17,39 @@
* under the License.
*/
-package org.apache.custos.user.profile.mapper;
+package org.apache.custos.core.mapper.user;
-import org.apache.custos.user.profile.persistance.model.Group;
-import org.apache.custos.user.profile.persistance.model.GroupAttribute;
-import org.apache.custos.user.profile.persistance.model.GroupRole;
-import org.apache.custos.user.profile.persistance.model.GroupToGroupMembership;
-import org.apache.custos.user.profile.utils.Constants;
+import org.apache.custos.core.constants.Constants;
+import org.apache.custos.core.model.user.Group;
+import org.apache.custos.core.model.user.GroupAttribute;
+import org.apache.custos.core.model.user.GroupRole;
+import org.apache.custos.core.model.user.GroupToGroupMembership;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
/**
- * This class maps persistence data model to gRPC data model
+ * This class maps persistence data model to protobuf data model
*/
public class GroupMapper {
private static final Logger LOGGER = LoggerFactory.getLogger(GroupMapper.class);
- public static Group createGroupEntity(org.apache.custos.user.profile.service.Group group, long tenantId) {
+ public static Group createGroupEntity(org.apache.custos.core.user.profile.api.Group group, long tenantId) {
Group groupEntity = new Group();
String id = group.getId() + "@" + tenantId;
String parentId = group.getParentId();
- if (parentId != null && !parentId.trim().equals("")) {
+ if (!parentId.trim().isEmpty()) {
parentId = group.getParentId() + "@" + tenantId;
}
@@ -55,15 +60,13 @@ public class GroupMapper {
groupEntity.setParentId(parentId);
-
- if (group.getDescription() != null && !group.getDescription().trim().equals("")) {
+ group.getDescription();
+ if (!group.getDescription().trim().isEmpty()) {
groupEntity.setDescription(group.getDescription());
}
Set<GroupAttribute> groupList = new HashSet<>();
if (!group.getAttributesList().isEmpty()) {
-
-
group.getAttributesList().forEach(atr -> {
for (String value : atr.getValueList()) {
@@ -72,39 +75,26 @@ public class GroupMapper {
groupAttribute.setValue(value);
groupAttribute.setGroup(groupEntity);
groupList.add(groupAttribute);
-
}
-
});
-
-
-
}
groupEntity.setGroupAttribute(groupList);
Set<GroupRole> groupRoles = new HashSet<>();
if (!group.getClientRolesList().isEmpty()) {
-
-
group.getClientRolesList().forEach(role -> {
-
GroupRole userRole = new GroupRole();
userRole.setValue(role);
userRole.setType(Constants.ROLE_TYPE_CLIENT);
userRole.setGroup(groupEntity);
groupRoles.add(userRole);
-
});
-
-
}
if (!group.getRealmRolesList().isEmpty()) {
-
group.getRealmRolesList().forEach(role -> {
-
GroupRole userRole = new GroupRole();
userRole.setValue(role);
userRole.setType(Constants.ROLE_TYPE_REALM);
@@ -112,19 +102,16 @@ public class GroupMapper {
groupRoles.add(userRole);
});
-
}
groupEntity.setGroupRole(groupRoles);
-
-
return groupEntity;
}
- public static org.apache.custos.user.profile.service.Group createGroup(Group group, String ownerId) {
+ public static org.apache.custos.core.user.profile.api.Group createGroup(Group group, String ownerId) {
- org.apache.custos.user.profile.service.Group.Builder groupBuilder = org.apache.custos.user.profile.service.Group
+ org.apache.custos.core.user.profile.api.Group.Builder groupBuilder = org.apache.custos.core.user.profile.api.Group
.newBuilder()
.setId(group.getExternalId())
.setName(group.getName())
@@ -150,27 +137,21 @@ public class GroupMapper {
realmRoles.add(role.getValue());
}
});
+ groupBuilder.addAllClientRoles(clientRoles).addAllRealmRoles(realmRoles);
}
- List<org.apache.custos.user.profile.service.GroupAttribute> attributeList = new ArrayList<>();
+ List<org.apache.custos.core.user.profile.api.GroupAttribute> attributeList = new ArrayList<>();
Map<String, List<String>> atrMap = new HashMap<>();
if (group.getGroupAttribute() != null && !group.getGroupAttribute().isEmpty()) {
group.getGroupAttribute().forEach(atr -> {
-
- if (atrMap.get(atr.getKeyValue()) == null) {
- atrMap.put(atr.getKeyValue(), new ArrayList<String>());
- }
+ atrMap.computeIfAbsent(atr.getKeyValue(), k -> new ArrayList<>());
atrMap.get(atr.getKeyValue()).add(atr.getValue());
-
});
-
- groupBuilder = groupBuilder.addAllClientRoles(clientRoles).addAllRealmRoles(realmRoles);
}
atrMap.keySet().forEach(key -> {
- org.apache.custos.user.profile.service.GroupAttribute attribute = org.apache.custos.user.profile.service
- .GroupAttribute
+ org.apache.custos.core.user.profile.api.GroupAttribute attribute = org.apache.custos.core.user.profile.api.GroupAttribute
.newBuilder()
.setKey(key)
.addAllValue(atrMap.get(key))
@@ -179,23 +160,18 @@ public class GroupMapper {
});
return groupBuilder.addAllAttributes(attributeList).build();
-
}
-
public static Group setParentGroupMembership(Group parent, Group child) {
-
GroupToGroupMembership groupToGroupMembership = new GroupToGroupMembership();
groupToGroupMembership.setChild(child);
groupToGroupMembership.setParent(parent);
groupToGroupMembership.setTenantId(child.getTenantId());
-
Set<GroupToGroupMembership> groupList = new HashSet<>();
groupList.add(groupToGroupMembership);
child.setParentGroups(groupList);
return child;
-
}
public static GroupToGroupMembership groupToGroupMembership(Group child, Group parent) {
@@ -204,7 +180,5 @@ public class GroupMapper {
groupToGroupMembership.setParent(parent);
groupToGroupMembership.setTenantId(child.getTenantId());
return groupToGroupMembership;
-
}
-
}
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/mapper/StatusUpdateMetadataMapper.java b/core/src/main/java/org/apache/custos/core/mapper/user/StatusUpdateMetadataMapper.java
similarity index 68%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/mapper/StatusUpdateMetadataMapper.java
rename to core/src/main/java/org/apache/custos/core/mapper/user/StatusUpdateMetadataMapper.java
index 994b0b119..34b509b18 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/mapper/StatusUpdateMetadataMapper.java
+++ b/core/src/main/java/org/apache/custos/core/mapper/user/StatusUpdateMetadataMapper.java
@@ -17,13 +17,13 @@
* under the License.
*/
-package org.apache.custos.user.profile.mapper;
+package org.apache.custos.core.mapper.user;
-import org.apache.custos.user.profile.persistance.model.StatusUpdateMetadata;
-import org.apache.custos.user.profile.persistance.model.UserProfile;
-import org.apache.custos.user.profile.service.UserProfileStatusUpdateMetadata;
-import org.apache.custos.user.profile.service.UserStatus;
+import org.apache.custos.core.model.user.StatusUpdateMetadata;
+import org.apache.custos.core.model.user.UserProfile;
+import org.apache.custos.core.user.profile.api.UserProfileStatusUpdateMetadata;
+import org.apache.custos.core.user.profile.api.UserStatus;
import java.util.HashSet;
import java.util.Set;
@@ -33,16 +33,14 @@ import java.util.Set;
*/
public class StatusUpdateMetadataMapper {
-
/**
- * Creates Status update entity to save in DB
+ * Creates a status update metadata entity for a user profile.
*
- * @param {@link org.apache.custos.user.profile.UserProfile} profile
- * @param updatedBy
- * @return
+ * @param tenant The user profile to create the metadata for.
+ * @param updatedBy The username of the user who updated the status.
+ * @return A set of status update metadata containing the updated status, updated by, and user profile.
*/
public static Set<StatusUpdateMetadata> createStatusUpdateMetadataEntity(UserProfile tenant, String updatedBy) {
-
Set<StatusUpdateMetadata> metaDataSet = new HashSet<>();
StatusUpdateMetadata metadata = new StatusUpdateMetadata();
@@ -56,10 +54,10 @@ public class StatusUpdateMetadataMapper {
}
/**
- * convert TenantStatusUpdateMetadataEntity to gRPC TenantStatusUpdateMetadata
+ * Creates a UserProfileStatusUpdateMetadata object from a StatusUpdateMetadata object.
*
- * @param metadata
- * @return TenantStatusUpdateMetadata
+ * @param metadata The StatusUpdateMetadata object to convert.
+ * @return A UserProfileStatusUpdateMetadata object containing the converted data.
*/
public static UserProfileStatusUpdateMetadata createUserProfileStatusMetadataFrom(StatusUpdateMetadata metadata) {
return UserProfileStatusUpdateMetadata.newBuilder()
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/mapper/UserProfileMapper.java b/core/src/main/java/org/apache/custos/core/mapper/user/UserProfileMapper.java
similarity index 59%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/mapper/UserProfileMapper.java
rename to core/src/main/java/org/apache/custos/core/mapper/user/UserProfileMapper.java
index 78513669d..7ae2c321b 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/mapper/UserProfileMapper.java
+++ b/core/src/main/java/org/apache/custos/core/mapper/user/UserProfileMapper.java
@@ -17,66 +17,63 @@
* under the License.
*/
-package org.apache.custos.user.profile.mapper;
-
-
-import org.apache.custos.user.profile.persistance.model.UserAttribute;
-import org.apache.custos.user.profile.persistance.model.UserProfile;
-import org.apache.custos.user.profile.persistance.model.UserRole;
-import org.apache.custos.user.profile.service.DefaultGroupMembershipTypes;
-import org.apache.custos.user.profile.service.UserStatus;
-import org.apache.custos.user.profile.service.UserTypes;
-import org.apache.custos.user.profile.utils.Constants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.*;
-
+package org.apache.custos.core.mapper.user;
+
+import org.apache.custos.core.constants.Constants;
+import org.apache.custos.core.model.user.UserAttribute;
+import org.apache.custos.core.model.user.UserProfile;
+import org.apache.custos.core.model.user.UserRole;
+import org.apache.custos.core.user.profile.api.UserStatus;
+import org.apache.custos.core.user.profile.api.UserTypes;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
/**
- * This class maps attributes between grpc UserProfile to DB UserProfile table
+ * This class maps attributes between protobuf UserProfile to UserProfile model
*/
public class UserProfileMapper {
- private static final Logger LOGGER = LoggerFactory.getLogger(UserProfileMapper.class);
-
/**
- * Maps gRPC UserProfile Model to DB Layer UserProfile Entity
+ * Creates a UserProfile entity from a UserProfile protobuf
*
- * @param {@link org.apache.custos.user.profile.service.UserProfile} tenant
- * @return Tenant
+ * @param userProfile the UserProfile object to be converted
+ * @return the created UserProfile entity
*/
- public static UserProfile createUserProfileEntityFromUserProfile(org.apache.custos.user.profile.service.UserProfile userProfile) {
+ public static UserProfile createUserProfileEntityFromUserProfile(org.apache.custos.core.user.profile.api.UserProfile userProfile) {
UserProfile entity = new UserProfile();
entity.setUsername(userProfile.getUsername());
- if (userProfile.getEmail() != null && !userProfile.getEmail().trim().equals("")) {
+ userProfile.getEmail();
+ if (!userProfile.getEmail().trim().isEmpty()) {
entity.setEmailAddress(userProfile.getEmail());
}
- if (userProfile.getFirstName() != null && !userProfile.getFirstName().trim().equals("")) {
+ userProfile.getFirstName();
+ if (!userProfile.getFirstName().trim().isEmpty()) {
entity.setFirstName(userProfile.getFirstName());
}
- if (userProfile.getLastName() != null && !userProfile.getLastName().trim().equals("")) {
+ userProfile.getLastName();
+ if (!userProfile.getLastName().trim().isEmpty()) {
entity.setLastName(userProfile.getLastName());
}
- if (userProfile.getType() != null) {
- entity.setType(userProfile.getType().name());
- } else {
- entity.setType(UserTypes.END_USER.name());
- }
+ entity.setType(userProfile.getType().name());
entity.setStatus(userProfile.getStatus().name());
Set<UserAttribute> attributeSet = new HashSet<>();
- if (userProfile.getAttributesList() != null && !userProfile.getAttributesList().isEmpty()) {
+ if (!userProfile.getAttributesList().isEmpty()) {
userProfile.getAttributesList().forEach(atr -> {
- if (atr.getValuesList() != null && !atr.getValuesList().isEmpty()) {
+ if (!atr.getValuesList().isEmpty()) {
for (String value : atr.getValuesList()) {
UserAttribute userAttribute = new UserAttribute();
userAttribute.setKey(atr.getKey());
@@ -85,16 +82,12 @@ public class UserProfileMapper {
attributeSet.add(userAttribute);
}
}
-
});
-
-
}
+
entity.setUserAttribute(attributeSet);
Set<UserRole> userRoleSet = new HashSet<>();
- if (userProfile.getRealmRolesList() != null && !userProfile.getRealmRolesList().isEmpty()) {
-
-
+ if (!userProfile.getRealmRolesList().isEmpty()) {
userProfile.getRealmRolesList().forEach(role -> {
UserRole userRole = new UserRole();
userRole.setValue(role);
@@ -102,11 +95,9 @@ public class UserProfileMapper {
userRole.setUserProfile(entity);
userRoleSet.add(userRole);
});
-
-
}
- if (userProfile.getClientRolesList() != null && !userProfile.getClientRolesList().isEmpty()) {
+ if (!userProfile.getClientRolesList().isEmpty()) {
userProfile.getClientRolesList().forEach(role -> {
UserRole userRole = new UserRole();
userRole.setValue(role);
@@ -114,8 +105,6 @@ public class UserProfileMapper {
userRole.setUserProfile(entity);
userRoleSet.add(userRole);
});
-
-
}
entity.setUserRole(userRoleSet);
@@ -124,17 +113,14 @@ public class UserProfileMapper {
/**
- * Transform UserProfileEntity to Tenant
+ * Creates a protobuf UserProfile object from a UserProfileEntity object.
*
- * @param profileEntity
- * @return tenant
+ * @param profileEntity The UserProfileEntity object to be converted.
+ * @param membershipType The membership type of the user.
+ * @return The created UserProfile object.
*/
- public static org.apache.custos.user.profile.service.UserProfile createUserProfileFromUserProfileEntity(UserProfile profileEntity, String membershipType) {
-
-
- org.apache.custos.user.profile.service.UserProfile.Builder builder =
- org.apache.custos.user.profile.service.UserProfile.newBuilder();
-
+ public static org.apache.custos.core.user.profile.api.UserProfile createUserProfileFromUserProfileEntity(UserProfile profileEntity, String membershipType) {
+ org.apache.custos.core.user.profile.api.UserProfile.Builder builder = org.apache.custos.core.user.profile.api.UserProfile.newBuilder();
if (profileEntity.getUserRole() != null && !profileEntity.getUserRole().isEmpty()) {
@@ -147,24 +133,17 @@ public class UserProfileMapper {
});
}
- List<org.apache.custos.user.profile.service.UserAttribute> attributeList = new ArrayList<>();
+ List<org.apache.custos.core.user.profile.api.UserAttribute> attributeList = new ArrayList<>();
if (profileEntity.getUserAttribute() != null && !profileEntity.getUserAttribute().isEmpty()) {
Map<String, List<String>> atrMap = new HashMap<>();
-
profileEntity.getUserAttribute().forEach(atr -> {
-
- if (atrMap.get(atr.getKey()) == null) {
- atrMap.put(atr.getKey(), new ArrayList<String>());
- }
+ atrMap.computeIfAbsent(atr.getKey(), k -> new ArrayList<>());
atrMap.get(atr.getKey()).add(atr.getValue());
-
});
-
atrMap.keySet().forEach(key -> {
- org.apache.custos.user.profile.service.UserAttribute attribute = org.apache.custos.user.profile.service
- .UserAttribute
+ org.apache.custos.core.user.profile.api.UserAttribute attribute = org.apache.custos.core.user.profile.api.UserAttribute
.newBuilder()
.setKey(key)
.addAllValues(atrMap.get(key))
@@ -173,9 +152,7 @@ public class UserProfileMapper {
});
}
-
- builder
- .setUsername(profileEntity.getUsername())
+ builder.setUsername(profileEntity.getUsername())
.setCreatedAt(profileEntity.getCreatedAt().getTime())
.setLastModifiedAt(profileEntity.getLastModifiedAt() != null ? profileEntity.getLastModifiedAt().getTime() : 0)
.setStatus(UserStatus.valueOf(profileEntity.getStatus()))
@@ -194,7 +171,7 @@ public class UserProfileMapper {
builder.setLastName(profileEntity.getLastName());
}
- if (membershipType != null ) {
+ if (membershipType != null) {
builder.setMembershipType(membershipType);
}
@@ -205,28 +182,16 @@ public class UserProfileMapper {
}
return builder.build();
-
-
}
-
- public static String getUserInfoInfoAsString(org.apache.custos.user.profile.service.UserProfile userProfile) {
- StringBuffer buffer = new StringBuffer();
- buffer.append("username : " + userProfile.getUsername());
- buffer.append("\n");
- buffer.append("emailAddress : " + userProfile.getEmail());
- buffer.append("\n");
- buffer.append("firstName : " + userProfile.getFirstName());
- buffer.append("\n");
- buffer.append("lastName : " + userProfile.getLastName());
- buffer.append("\n");
-
- return buffer.toString();
-
+ public static String getUserInfoInfoAsString(org.apache.custos.core.user.profile.api.UserProfile userProfile) {
+ return "username : " + userProfile.getUsername() +
+ "\n" +
+ "emailAddress : " + userProfile.getEmail() +
+ "\n" +
+ "firstName : " + userProfile.getFirstName() +
+ "\n" +
+ "lastName : " + userProfile.getLastName() +
+ "\n";
}
-
-
}
-
-
-
diff --git a/custos-services/custos-core-services/custos-core-services-commons/src/main/java/org/apache/custos/core/services/api/commons/persistance/model/OperationStatus.java b/core/src/main/java/org/apache/custos/core/model/commons/OperationStatus.java
similarity index 92%
rename from custos-services/custos-core-services/custos-core-services-commons/src/main/java/org/apache/custos/core/services/api/commons/persistance/model/OperationStatus.java
rename to core/src/main/java/org/apache/custos/core/model/commons/OperationStatus.java
index 4fafedeb2..84bb090c3 100644
--- a/custos-services/custos-core-services/custos-core-services-commons/src/main/java/org/apache/custos/core/services/api/commons/persistance/model/OperationStatus.java
+++ b/core/src/main/java/org/apache/custos/core/model/commons/OperationStatus.java
@@ -17,7 +17,7 @@
* under the License.
*/
-package org.apache.custos.core.services.api.commons.persistance.model;
+package org.apache.custos.core.model.commons;
public enum OperationStatus {
diff --git a/custos-services/custos-core-services/custos-core-services-commons/src/main/java/org/apache/custos/core/services/api/commons/persistance/model/StatusEntity.java b/core/src/main/java/org/apache/custos/core/model/commons/StatusEntity.java
similarity index 85%
rename from custos-services/custos-core-services/custos-core-services-commons/src/main/java/org/apache/custos/core/services/api/commons/persistance/model/StatusEntity.java
rename to core/src/main/java/org/apache/custos/core/model/commons/StatusEntity.java
index d9ce3c857..19b40b82f 100644
--- a/custos-services/custos-core-services/custos-core-services-commons/src/main/java/org/apache/custos/core/services/api/commons/persistance/model/StatusEntity.java
+++ b/core/src/main/java/org/apache/custos/core/model/commons/StatusEntity.java
@@ -17,12 +17,20 @@
* under the License.
*/
-package org.apache.custos.core.services.api.commons.persistance.model;
-
+package org.apache.custos.core.model.commons;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
/**
@@ -52,11 +60,9 @@ public class StatusEntity {
@Column(nullable = false)
private Long traceId;
-
private String performedBy;
-
public Long getId() {
return id;
}
@@ -89,7 +95,6 @@ public class StatusEntity {
this.state = state;
}
-
public Long getTraceId() {
return traceId;
}
diff --git a/custos-services/custos-core-services/credential-store-core-service/src/main/java/org/apache/custos/credential/store/persistance/model/AgentCredentialEntity.java b/core/src/main/java/org/apache/custos/core/model/credential/store/AgentCredentialEntity.java
similarity index 85%
rename from custos-services/custos-core-services/credential-store-core-service/src/main/java/org/apache/custos/credential/store/persistance/model/AgentCredentialEntity.java
rename to core/src/main/java/org/apache/custos/core/model/credential/store/AgentCredentialEntity.java
index 792c46aa8..2dc92ed76 100644
--- a/custos-services/custos-core-services/credential-store-core-service/src/main/java/org/apache/custos/credential/store/persistance/model/AgentCredentialEntity.java
+++ b/core/src/main/java/org/apache/custos/core/model/credential/store/AgentCredentialEntity.java
@@ -17,12 +17,22 @@
* under the License.
*/
-package org.apache.custos.credential.store.persistance.model;
-
+package org.apache.custos.core.model.credential.store;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
@Entity
diff --git a/custos-services/custos-core-services/credential-store-core-service/src/main/java/org/apache/custos/credential/store/persistance/model/CredentialEntity.java b/core/src/main/java/org/apache/custos/core/model/credential/store/CredentialEntity.java
similarity index 76%
rename from custos-services/custos-core-services/credential-store-core-service/src/main/java/org/apache/custos/credential/store/persistance/model/CredentialEntity.java
rename to core/src/main/java/org/apache/custos/core/model/credential/store/CredentialEntity.java
index 148637bdd..b1e1f6c66 100644
--- a/custos-services/custos-core-services/credential-store-core-service/src/main/java/org/apache/custos/credential/store/persistance/model/CredentialEntity.java
+++ b/core/src/main/java/org/apache/custos/core/model/credential/store/CredentialEntity.java
@@ -17,42 +17,55 @@
* under the License.
*/
-package org.apache.custos.credential.store.persistance.model;
-
+package org.apache.custos.core.model.credential.store;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
-import java.util.Set;
@Entity
@Table(name = "custos_credentials")
@EntityListeners(AuditingEntityListener.class)
public class CredentialEntity {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
@Column(nullable = false)
private String clientId;
-
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date issuedAt;
- @Column(nullable = false)
+ @Column(nullable = false)
private long clientSecretExpiredAt;
- @Id
@Column(nullable = false)
private long ownerId;
- @Column(nullable = false)
- private String type;
+ @Column(nullable = false)
+ private String type;
- @OneToMany(mappedBy = "credentialEntity", cascade = CascadeType.ALL)
- Set<AgentCredentialEntity> agentCredentialEntities;
+ public Long getId() {
+ return id;
+ }
+ public void setId(Long id) {
+ this.id = id;
+ }
public String getClientId() {
return clientId;
@@ -93,13 +106,4 @@ public class CredentialEntity {
public void setType(String type) {
this.type = type;
}
-
-
- public Set<AgentCredentialEntity> getAgentCredentialEntities() {
- return agentCredentialEntities;
- }
-
- public void setAgentCredentialEntities(Set<AgentCredentialEntity> agentCredentialEntities) {
- this.agentCredentialEntities = agentCredentialEntities;
- }
}
diff --git a/custos-services/custos-core-services/federated-authentication-core-service/src/main/java/org/apache/custos/federated/authentication/persistance/model/CILogonInstitution.java b/core/src/main/java/org/apache/custos/core/model/federated/CILogonInstitution.java
similarity index 87%
rename from custos-services/custos-core-services/federated-authentication-core-service/src/main/java/org/apache/custos/federated/authentication/persistance/model/CILogonInstitution.java
rename to core/src/main/java/org/apache/custos/core/model/federated/CILogonInstitution.java
index bb4d4d2d3..8c822b875 100644
--- a/custos-services/custos-core-services/federated-authentication-core-service/src/main/java/org/apache/custos/federated/authentication/persistance/model/CILogonInstitution.java
+++ b/core/src/main/java/org/apache/custos/core/model/federated/CILogonInstitution.java
@@ -17,17 +17,23 @@
* under the License.
*/
-package org.apache.custos.federated.authentication.persistance.model;
-
+package org.apache.custos.core.model.federated;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
/**
- * Keeps track of whitelisted and blacklisted institutions
+ * The CILogonInstitution class represents a CILogon institution in the system.
*/
@Entity
@Table(name = "cilogon_institution_cache")
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/Contact.java b/core/src/main/java/org/apache/custos/core/model/tenant/Contact.java
similarity index 69%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/Contact.java
rename to core/src/main/java/org/apache/custos/core/model/tenant/Contact.java
index 7c9eedf3c..a1fd993a4 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/Contact.java
+++ b/core/src/main/java/org/apache/custos/core/model/tenant/Contact.java
@@ -17,13 +17,18 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.persistance.model;
+package org.apache.custos.core.model.tenant;
-import jakarta.persistence.*;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
+
+import java.util.Objects;
-/**
- * This class represents the contact information of Tenant
- */
@Entity
@Table(name = "contact")
public class Contact {
@@ -38,7 +43,6 @@ public class Contact {
@JoinColumn(name = "tenant_id")
private Tenant tenant;
-
public String getContactInfo() {
return contactInfo;
}
@@ -64,7 +68,15 @@ public class Contact {
}
@Override
- public boolean equals(Object obj) {
- return this.contactInfo.equals(((Contact)obj).getContactInfo());
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Contact contact = (Contact) o;
+ return Objects.equals(contactInfo, contact.contactInfo);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(contactInfo);
}
}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/RedirectURI.java b/core/src/main/java/org/apache/custos/core/model/tenant/RedirectURI.java
similarity index 68%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/RedirectURI.java
rename to core/src/main/java/org/apache/custos/core/model/tenant/RedirectURI.java
index 780dcfadd..2d28a4210 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/RedirectURI.java
+++ b/core/src/main/java/org/apache/custos/core/model/tenant/RedirectURI.java
@@ -17,16 +17,23 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.persistance.model;
+package org.apache.custos.core.model.tenant;
-import jakarta.persistence.*;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
+
+import java.util.Objects;
-/**
- * This represents the redirectURIs of a tenants
- */
@Entity
@Table(name = "redirect_uri")
public class RedirectURI {
+
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id ;
@@ -38,7 +45,6 @@ public class RedirectURI {
@JoinColumn(name = "tenant_id")
private Tenant tenant;
-
public String getRedirectURI() {
return redirectURI;
}
@@ -63,9 +69,16 @@ public class RedirectURI {
this.id = id;
}
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ RedirectURI that = (RedirectURI) o;
+ return Objects.equals(redirectURI, that.redirectURI);
+ }
@Override
- public boolean equals(Object obj) {
- return this.redirectURI.equals(((RedirectURI)obj).getRedirectURI());
+ public int hashCode() {
+ return Objects.hash(redirectURI);
}
}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/Tenant.java b/core/src/main/java/org/apache/custos/core/model/tenant/Tenant.java
similarity index 92%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/Tenant.java
rename to core/src/main/java/org/apache/custos/core/model/tenant/Tenant.java
index 3f50467fa..e220b4960 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/Tenant.java
+++ b/core/src/main/java/org/apache/custos/core/model/tenant/Tenant.java
@@ -17,19 +17,27 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.persistance.model;
-
-
+package org.apache.custos.core.model.tenant;
+
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.SequenceGenerator;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
import java.util.Set;
-/**
- * Represents tenant table at DB
- */
@Entity
@Table(name = "tenant")
@EntityListeners(AuditingEntityListener.class)
@@ -64,7 +72,6 @@ public class Tenant {
@Column(nullable = false)
private String adminUsername;
-
@Column(name = "tenant_uri")
private String logoURI;
@@ -101,8 +108,7 @@ public class Tenant {
private long refreshTokenLifetime = 0;
-
- @OneToMany(mappedBy = "tenant", cascade = CascadeType.ALL,orphanRemoval = true, fetch = FetchType.EAGER)
+ @OneToMany(mappedBy = "tenant", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
private Set<Contact> contacts;
@OneToMany(mappedBy = "tenant", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@@ -114,7 +120,6 @@ public class Tenant {
@OneToMany(mappedBy = "tenant", cascade = CascadeType.ALL)
private Set<TenantStatusUpdateMetadata> statusUpdateMetadata;
-
public Long getId() {
return id;
}
@@ -179,7 +184,6 @@ public class Tenant {
this.adminEmail = adminEmail;
}
-
public String getLogoURI() {
return logoURI;
}
@@ -236,7 +240,6 @@ public class Tenant {
this.adminUsername = adminUsername;
}
-
public String getUri() {
return uri;
}
@@ -269,7 +272,6 @@ public class Tenant {
this.applicationType = applicationType;
}
-
public String getJwksUri() {
return jwksUri;
}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/TenantAttributeUpdateMetadata.java b/core/src/main/java/org/apache/custos/core/model/tenant/TenantAttributeUpdateMetadata.java
similarity index 82%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/TenantAttributeUpdateMetadata.java
rename to core/src/main/java/org/apache/custos/core/model/tenant/TenantAttributeUpdateMetadata.java
index 426985265..35e346ea9 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/TenantAttributeUpdateMetadata.java
+++ b/core/src/main/java/org/apache/custos/core/model/tenant/TenantAttributeUpdateMetadata.java
@@ -17,12 +17,24 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.persistance.model;
-
+package org.apache.custos.core.model.tenant;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.Lob;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
/**
@@ -56,7 +68,6 @@ public class TenantAttributeUpdateMetadata {
@JoinColumn(name = "tenant_id")
private Tenant tenant;
-
public Long getId() {
return id;
}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/TenantStatusUpdateMetadata.java b/core/src/main/java/org/apache/custos/core/model/tenant/TenantStatusUpdateMetadata.java
similarity index 81%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/TenantStatusUpdateMetadata.java
rename to core/src/main/java/org/apache/custos/core/model/tenant/TenantStatusUpdateMetadata.java
index 4737d8660..332cfabd5 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/model/TenantStatusUpdateMetadata.java
+++ b/core/src/main/java/org/apache/custos/core/model/tenant/TenantStatusUpdateMetadata.java
@@ -17,12 +17,23 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.persistance.model;
-
+package org.apache.custos.core.model.tenant;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
/**
@@ -72,8 +83,6 @@ public class TenantStatusUpdateMetadata {
return updatedAt;
}
-
-
public String getUpdatedBy() {
return updatedBy;
}
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/AttributeUpdateMetadata.java b/core/src/main/java/org/apache/custos/core/model/user/AttributeUpdateMetadata.java
similarity index 84%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/AttributeUpdateMetadata.java
rename to core/src/main/java/org/apache/custos/core/model/user/AttributeUpdateMetadata.java
index c15c44bae..a415ad1a2 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/AttributeUpdateMetadata.java
+++ b/core/src/main/java/org/apache/custos/core/model/user/AttributeUpdateMetadata.java
@@ -17,12 +17,23 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.model;
-
+package org.apache.custos.core.model.user;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
/**
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/Group.java b/core/src/main/java/org/apache/custos/core/model/user/Group.java
similarity index 91%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/Group.java
rename to core/src/main/java/org/apache/custos/core/model/user/Group.java
index 3c384dcad..b17684702 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/Group.java
+++ b/core/src/main/java/org/apache/custos/core/model/user/Group.java
@@ -17,19 +17,25 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.model;
-
+package org.apache.custos.core.model.user;
+
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
import java.util.Set;
-/**
- * Group Entity
- */
@Entity
@Table(name = "group_entity")
@EntityListeners(AuditingEntityListener.class)
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/GroupAttribute.java b/core/src/main/java/org/apache/custos/core/model/user/GroupAttribute.java
similarity index 83%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/GroupAttribute.java
rename to core/src/main/java/org/apache/custos/core/model/user/GroupAttribute.java
index f4dbf144b..310dfec5e 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/GroupAttribute.java
+++ b/core/src/main/java/org/apache/custos/core/model/user/GroupAttribute.java
@@ -17,13 +17,16 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.model;
-
-import jakarta.persistence.*;
-
-/**
- * Group attribute
- */
+package org.apache.custos.core.model.user;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "group_attribute")
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/GroupRole.java b/core/src/main/java/org/apache/custos/core/model/user/GroupRole.java
similarity index 82%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/GroupRole.java
rename to core/src/main/java/org/apache/custos/core/model/user/GroupRole.java
index 12d4d426e..4e39c0913 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/GroupRole.java
+++ b/core/src/main/java/org/apache/custos/core/model/user/GroupRole.java
@@ -17,13 +17,17 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.model;
+package org.apache.custos.core.model.user;
-import jakarta.persistence.*;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
-/**
- * Group roles
- */
@Entity
@Table(name = "group_role")
public class GroupRole {
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/GroupToGroupMembership.java b/core/src/main/java/org/apache/custos/core/model/user/GroupToGroupMembership.java
similarity index 84%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/GroupToGroupMembership.java
rename to core/src/main/java/org/apache/custos/core/model/user/GroupToGroupMembership.java
index c39922988..707de4fd0 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/GroupToGroupMembership.java
+++ b/core/src/main/java/org/apache/custos/core/model/user/GroupToGroupMembership.java
@@ -17,14 +17,23 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.model;
-
+package org.apache.custos.core.model.user;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
-import javax.validation.constraints.NotNull;
import java.util.Date;
@Entity
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/StatusUpdateMetadata.java b/core/src/main/java/org/apache/custos/core/model/user/StatusUpdateMetadata.java
similarity index 82%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/StatusUpdateMetadata.java
rename to core/src/main/java/org/apache/custos/core/model/user/StatusUpdateMetadata.java
index eca4f37ca..0934a2951 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/StatusUpdateMetadata.java
+++ b/core/src/main/java/org/apache/custos/core/model/user/StatusUpdateMetadata.java
@@ -17,12 +17,23 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.model;
-
+package org.apache.custos.core.model.user;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
/**
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserAttribute.java b/core/src/main/java/org/apache/custos/core/model/user/UserAttribute.java
similarity index 83%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserAttribute.java
rename to core/src/main/java/org/apache/custos/core/model/user/UserAttribute.java
index f7ce64036..e4ff844c0 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserAttribute.java
+++ b/core/src/main/java/org/apache/custos/core/model/user/UserAttribute.java
@@ -17,9 +17,16 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.model;
-
-import jakarta.persistence.*;
+package org.apache.custos.core.model.user;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "user_attribute")
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserGroupMembership.java b/core/src/main/java/org/apache/custos/core/model/user/UserGroupMembership.java
similarity index 86%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserGroupMembership.java
rename to core/src/main/java/org/apache/custos/core/model/user/UserGroupMembership.java
index 27d8539aa..8c220bb3c 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserGroupMembership.java
+++ b/core/src/main/java/org/apache/custos/core/model/user/UserGroupMembership.java
@@ -17,13 +17,23 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.model;
-
+package org.apache.custos.core.model.user;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
@Entity
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserGroupMembershipType.java b/core/src/main/java/org/apache/custos/core/model/user/UserGroupMembershipType.java
similarity index 85%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserGroupMembershipType.java
rename to core/src/main/java/org/apache/custos/core/model/user/UserGroupMembershipType.java
index c96e30a63..2808e1665 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserGroupMembershipType.java
+++ b/core/src/main/java/org/apache/custos/core/model/user/UserGroupMembershipType.java
@@ -17,20 +17,24 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.model;
-
+package org.apache.custos.core.model.user;
+
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
import java.util.Set;
-
-/**
- * Group Membership Type
- */
@Entity
@Table(name = "user_group_membership_type")
@EntityListeners(AuditingEntityListener.class)
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserProfile.java b/core/src/main/java/org/apache/custos/core/model/user/UserProfile.java
similarity index 91%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserProfile.java
rename to core/src/main/java/org/apache/custos/core/model/user/UserProfile.java
index 81cc73d9f..ae5389843 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserProfile.java
+++ b/core/src/main/java/org/apache/custos/core/model/user/UserProfile.java
@@ -17,19 +17,25 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.model;
-
+package org.apache.custos.core.model.user;
+
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EntityListeners;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-import jakarta.persistence.*;
import java.util.Date;
import java.util.Set;
-/**
- * User profile entity model
- */
@Entity
@Table(name = "user_profile")
@EntityListeners(AuditingEntityListener.class)
@@ -85,7 +91,7 @@ public class UserProfile {
@OneToMany(mappedBy = "userProfile", cascade = CascadeType.ALL)
- Set<UserGroupMembership> userGroupMemberships;
+ private Set<UserGroupMembership> userGroupMemberships;
public String getId() {
@@ -193,7 +199,6 @@ public class UserProfile {
this.userGroupMemberships = userGroupMemberships;
}
-
public Date getLastModifiedAt() {
return lastModifiedAt;
}
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserRole.java b/core/src/main/java/org/apache/custos/core/model/user/UserRole.java
similarity index 83%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserRole.java
rename to core/src/main/java/org/apache/custos/core/model/user/UserRole.java
index 4992a9be8..3a5fb32e4 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/model/UserRole.java
+++ b/core/src/main/java/org/apache/custos/core/model/user/UserRole.java
@@ -17,9 +17,16 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.model;
+package org.apache.custos.core.model.user;
-import jakarta.persistence.*;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "user_role")
@@ -39,7 +46,6 @@ public class UserRole {
@JoinColumn(name = "user_profile_id")
private UserProfile userProfile;
-
public Long getId() {
return id;
}
diff --git a/custos-services/custos-core-services/custos-core-services-commons/src/main/java/org/apache/custos/core/services/api/commons/persistance/repository/StatusUpdaterRepository.java b/core/src/main/java/org/apache/custos/core/repo/commons/StatusUpdaterRepository.java
similarity index 82%
rename from custos-services/custos-core-services/custos-core-services-commons/src/main/java/org/apache/custos/core/services/api/commons/persistance/repository/StatusUpdaterRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/commons/StatusUpdaterRepository.java
index bb7eae5f0..d77ca67f6 100644
--- a/custos-services/custos-core-services/custos-core-services-commons/src/main/java/org/apache/custos/core/services/api/commons/persistance/repository/StatusUpdaterRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/commons/StatusUpdaterRepository.java
@@ -17,9 +17,9 @@
* under the License.
*/
-package org.apache.custos.core.services.api.commons.persistance.repository;
+package org.apache.custos.core.repo.commons;
-import org.apache.custos.core.services.api.commons.persistance.model.StatusEntity;
+import org.apache.custos.core.model.commons.StatusEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
@@ -28,5 +28,5 @@ import java.util.List;
public interface StatusUpdaterRepository extends JpaRepository<StatusEntity, Long> {
@Transactional
- public List<StatusEntity> findAllByTraceId(long traceId);
+ List<StatusEntity> findAllByTraceId(long traceId);
}
diff --git a/custos-services/custos-core-services/credential-store-core-service/src/main/java/org/apache/custos/credential/store/persistance/repository/AgentCredentialRepository.java b/core/src/main/java/org/apache/custos/core/repo/credential/store/AgentCredentialRepository.java
similarity index 83%
rename from custos-services/custos-core-services/credential-store-core-service/src/main/java/org/apache/custos/credential/store/persistance/repository/AgentCredentialRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/credential/store/AgentCredentialRepository.java
index d7dc3848a..1ecc6bc77 100644
--- a/custos-services/custos-core-services/credential-store-core-service/src/main/java/org/apache/custos/credential/store/persistance/repository/AgentCredentialRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/credential/store/AgentCredentialRepository.java
@@ -17,10 +17,9 @@
* under the License.
*/
-package org.apache.custos.credential.store.persistance.repository;
+package org.apache.custos.core.repo.credential.store;
-import org.apache.custos.credential.store.persistance.model.AgentCredentialEntity;
-import org.apache.custos.credential.store.persistance.model.CredentialEntity;
+import org.apache.custos.core.model.credential.store.AgentCredentialEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
diff --git a/custos-services/custos-core-services/credential-store-core-service/src/main/java/org/apache/custos/credential/store/persistance/repository/CredentialRepository.java b/core/src/main/java/org/apache/custos/core/repo/credential/store/CredentialRepository.java
similarity index 76%
rename from custos-services/custos-core-services/credential-store-core-service/src/main/java/org/apache/custos/credential/store/persistance/repository/CredentialRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/credential/store/CredentialRepository.java
index 10d0b4095..8cb5e4b78 100644
--- a/custos-services/custos-core-services/credential-store-core-service/src/main/java/org/apache/custos/credential/store/persistance/repository/CredentialRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/credential/store/CredentialRepository.java
@@ -17,14 +17,19 @@
* under the License.
*/
-package org.apache.custos.credential.store.persistance.repository;
+package org.apache.custos.core.repo.credential.store;
-import org.apache.custos.credential.store.persistance.model.CredentialEntity;
+import org.apache.custos.core.model.credential.store.CredentialEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
+import java.util.Optional;
+
public interface CredentialRepository extends JpaRepository<CredentialEntity, Long> {
@Transactional
- public CredentialEntity findByClientId(String clientId);
+ CredentialEntity findByClientId(String clientId);
+
+ @Transactional
+ Optional<CredentialEntity> findByOwnerIdAndClientId(long ownerId, String clientId);
}
diff --git a/custos-services/custos-core-services/federated-authentication-core-service/src/main/java/org/apache/custos/federated/authentication/persistance/repository/CiLogonInstitutionCacheRepository.java b/core/src/main/java/org/apache/custos/core/repo/federated/CiLogonInstitutionCacheRepository.java
similarity index 79%
rename from custos-services/custos-core-services/federated-authentication-core-service/src/main/java/org/apache/custos/federated/authentication/persistance/repository/CiLogonInstitutionCacheRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/federated/CiLogonInstitutionCacheRepository.java
index 561a4a2cb..4c7ef7cbc 100644
--- a/custos-services/custos-core-services/federated-authentication-core-service/src/main/java/org/apache/custos/federated/authentication/persistance/repository/CiLogonInstitutionCacheRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/federated/CiLogonInstitutionCacheRepository.java
@@ -17,15 +17,15 @@
* under the License.
*/
-package org.apache.custos.federated.authentication.persistance.repository;
+package org.apache.custos.core.repo.federated;
-import org.apache.custos.federated.authentication.persistance.model.CILogonInstitution;
+import org.apache.custos.core.model.federated.CILogonInstitution;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface CiLogonInstitutionCacheRepository extends JpaRepository<CILogonInstitution, String> {
- public List<CILogonInstitution> findAllByTenantIdAndType(long tenantId, String type);
+ List<CILogonInstitution> findAllByTenantIdAndType(long tenantId, String type);
}
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/GroupRoleRepository.java b/core/src/main/java/org/apache/custos/core/repo/tenant/ContactRepository.java
similarity index 80%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/GroupRoleRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/tenant/ContactRepository.java
index acbd1f664..0151e2233 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/GroupRoleRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/tenant/ContactRepository.java
@@ -17,12 +17,14 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.repository;
+package org.apache.custos.core.repo.tenant;
-import org.apache.custos.user.profile.persistance.model.GroupRole;
+import org.apache.custos.core.model.tenant.Contact;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
-public interface GroupRoleRepository extends JpaRepository<GroupRole,Long> {
+public interface ContactRepository extends JpaRepository<Contact, Long> {
+ @Transactional
+ void deleteAllByTenantId(Long tenantId);
}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/ContactRepository.java b/core/src/main/java/org/apache/custos/core/repo/tenant/RedirectURIRepository.java
similarity index 78%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/ContactRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/tenant/RedirectURIRepository.java
index fe4564831..64669a884 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/ContactRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/tenant/RedirectURIRepository.java
@@ -17,14 +17,14 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.persistance.respository;
+package org.apache.custos.core.repo.tenant;
-import org.apache.custos.tenant.profile.persistance.model.Contact;
+import org.apache.custos.core.model.tenant.RedirectURI;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
-public interface ContactRepository extends JpaRepository<Contact, Long> {
+public interface RedirectURIRepository extends JpaRepository<RedirectURI, Long> {
@Transactional
- public void deleteAllByTenantId(Long tenantId);
+ void deleteAllByTenantId(Long tenantId);
}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/SearchTenantRepository.java b/core/src/main/java/org/apache/custos/core/repo/tenant/SearchTenantRepository.java
similarity index 88%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/SearchTenantRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/tenant/SearchTenantRepository.java
index 586d73ccd..17278b624 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/SearchTenantRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/tenant/SearchTenantRepository.java
@@ -17,15 +17,13 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.persistance.respository;
+package org.apache.custos.core.repo.tenant;
-
-import org.apache.custos.tenant.profile.persistance.model.Tenant;
+import org.apache.custos.core.model.tenant.Tenant;
import java.util.List;
public interface SearchTenantRepository {
-
List<Tenant> searchTenants(String requestEmail, String status, long parentId, int limit, int offset, String type);
}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/SearchTenantRepositoryImpl.java b/core/src/main/java/org/apache/custos/core/repo/tenant/SearchTenantRepositoryImpl.java
similarity index 80%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/SearchTenantRepositoryImpl.java
rename to core/src/main/java/org/apache/custos/core/repo/tenant/SearchTenantRepositoryImpl.java
index 07c9e1dd2..e5afe7969 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/SearchTenantRepositoryImpl.java
+++ b/core/src/main/java/org/apache/custos/core/repo/tenant/SearchTenantRepositoryImpl.java
@@ -17,17 +17,15 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.persistance.respository;
-
-import org.apache.custos.tenant.profile.persistance.model.Tenant;
-import org.apache.custos.tenant.profile.service.TenantStatus;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Repository;
+package org.apache.custos.core.repo.tenant;
+import org.apache.custos.core.model.tenant.Tenant;
+import org.apache.custos.core.tenant.profile.api.TenantStatus;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
+import org.springframework.stereotype.Repository;
+
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -35,8 +33,6 @@ import java.util.Map;
@Repository
public class SearchTenantRepositoryImpl implements SearchTenantRepository {
- private static final Logger LOGGER = LoggerFactory.getLogger(SearchTenantRepositoryImpl.class);
-
@PersistenceContext
EntityManager entityManager;
@@ -49,35 +45,30 @@ public class SearchTenantRepositoryImpl implements SearchTenantRepository {
for (String key : valueMap.keySet()) {
q.setParameter(key, valueMap.get(key));
}
-
return q.getResultList();
}
-
- private String createSQLQuery(String requestEmail, String status, String type, long parentId, int limit, int offset,
- Map<String, Object> valueMap) {
+ private String createSQLQuery(String requestEmail, String status, String type, long parentId, int limit, int offset, Map<String, Object> valueMap) {
String query = "SELECT * FROM tenant E WHERE ";
if (requestEmail != null && !requestEmail.isEmpty()) {
query = query + "E.requester_email = :" + "requester_email" + " AND ";
valueMap.put("requester_email", requestEmail);
-
}
- if (status != null && !status.isEmpty()) {
+ if (status != null && !status.isEmpty()) {
query = query + "E.status LIKE :" + "status" + " AND ";
valueMap.put("status", status);
} else {
- String defaultStatus = "'"+TenantStatus.REQUESTED.name()+ "'"+ "," +
- "'"+TenantStatus.ACTIVE.name()+"'" + "," + "'"+TenantStatus.DENIED.name()+"'";
+ String defaultStatus = "'" + TenantStatus.REQUESTED.name() + "'" + "," +
+ "'" + TenantStatus.ACTIVE.name() + "'" + "," + "'" + TenantStatus.DENIED.name() + "'";
query = query + "E.status IN (" + defaultStatus + ") AND ";
}
if (parentId > 0) {
query = query + "E.parent_id = :" + "parent_id" + " AND ";
valueMap.put("parent_id", parentId);
-
}
if (type != null && type.equals("ADMIN")) {
@@ -89,7 +80,6 @@ public class SearchTenantRepositoryImpl implements SearchTenantRepository {
query = query + " ORDER BY E.created_at DESC";
-
if (limit > 0) {
query = query + " LIMIT " + ":limit" + " OFFSET " + ":offset";
valueMap.put("limit", limit);
@@ -98,6 +88,4 @@ public class SearchTenantRepositoryImpl implements SearchTenantRepository {
return query;
}
-
-
}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/TenantAttributeUpdateMetadataRepository.java b/core/src/main/java/org/apache/custos/core/repo/tenant/TenantAttributeUpdateMetadataRepository.java
similarity index 81%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/TenantAttributeUpdateMetadataRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/tenant/TenantAttributeUpdateMetadataRepository.java
index 7aeb7a66f..924adfab8 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/TenantAttributeUpdateMetadataRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/tenant/TenantAttributeUpdateMetadataRepository.java
@@ -17,14 +17,14 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.persistance.respository;
+package org.apache.custos.core.repo.tenant;
-import org.apache.custos.tenant.profile.persistance.model.TenantAttributeUpdateMetadata;
+import org.apache.custos.core.model.tenant.TenantAttributeUpdateMetadata;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface TenantAttributeUpdateMetadataRepository extends JpaRepository<TenantAttributeUpdateMetadata, Long> {
- public List<TenantAttributeUpdateMetadata> findAllByTenantId(Long tenant);
+ List<TenantAttributeUpdateMetadata> findAllByTenantId(Long tenant);
}
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/StatusUpdateMetadataRepository.java b/core/src/main/java/org/apache/custos/core/repo/tenant/TenantRepository.java
similarity index 73%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/StatusUpdateMetadataRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/tenant/TenantRepository.java
index 2bdebe2e3..cb5533ee7 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/StatusUpdateMetadataRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/tenant/TenantRepository.java
@@ -17,15 +17,16 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.repository;
+package org.apache.custos.core.repo.tenant;
-import org.apache.custos.user.profile.persistance.model.StatusUpdateMetadata;
+import org.apache.custos.core.model.tenant.Tenant;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
-public interface StatusUpdateMetadataRepository extends JpaRepository<StatusUpdateMetadata, Long> {
+public interface TenantRepository extends JpaRepository<Tenant, Long>, SearchTenantRepository {
+ List<Tenant> findByRequesterEmail(String requesterEmail);
- public List<StatusUpdateMetadata> findAllByUserProfileId(String userId);
+ List<Tenant> findByDomainAndName(String domain, String name);
}
diff --git a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/TenantStatusUpdateMetadataRepository.java b/core/src/main/java/org/apache/custos/core/repo/tenant/TenantStatusUpdateMetadataRepository.java
similarity index 81%
rename from custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/TenantStatusUpdateMetadataRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/tenant/TenantStatusUpdateMetadataRepository.java
index 8f25f06f3..6e0ff81fc 100644
--- a/custos-services/custos-core-services/tenant-profile-core-service/src/main/java/org/apache/custos/tenant/profile/persistance/respository/TenantStatusUpdateMetadataRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/tenant/TenantStatusUpdateMetadataRepository.java
@@ -17,15 +17,14 @@
* under the License.
*/
-package org.apache.custos.tenant.profile.persistance.respository;
+package org.apache.custos.core.repo.tenant;
-import org.apache.custos.tenant.profile.persistance.model.TenantStatusUpdateMetadata;
+import org.apache.custos.core.model.tenant.TenantStatusUpdateMetadata;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface TenantStatusUpdateMetadataRepository extends JpaRepository<TenantStatusUpdateMetadata, Long> {
-
- public List<TenantStatusUpdateMetadata> findAllByTenantId(Long tenant);
+ List<TenantStatusUpdateMetadata> findAllByTenantId(Long tenant);
}
diff --git a/custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/persistance/repository/EntityTypeRepository.java b/core/src/main/java/org/apache/custos/core/repo/user/AttributeUpdateMetadataRepository.java
similarity index 75%
copy from custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/persistance/repository/EntityTypeRepository.java
copy to core/src/main/java/org/apache/custos/core/repo/user/AttributeUpdateMetadataRepository.java
index a420005ee..303d00b73 100644
--- a/custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/persistance/repository/EntityTypeRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/AttributeUpdateMetadataRepository.java
@@ -17,15 +17,14 @@
* under the License.
*/
-package org.apache.custos.sharing.core.persistance.repository;
+package org.apache.custos.core.repo.user;
-import org.apache.custos.sharing.core.persistance.model.EntityType;
+import org.apache.custos.core.model.user.AttributeUpdateMetadata;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
-public interface EntityTypeRepository extends JpaRepository<EntityType, String> {
+public interface AttributeUpdateMetadataRepository extends JpaRepository<AttributeUpdateMetadata, Long> {
-
- public List<EntityType> findAllByTenantId(String tenantId);
+ List<AttributeUpdateMetadata> findAllByUserProfileId(String userId);
}
diff --git a/custos-services/custos-core-services/custos-logging/src/main/java/org/apache/custos/logging/persistance/repository/LogEventRepository.java b/core/src/main/java/org/apache/custos/core/repo/user/GroupAttributeRepository.java
similarity index 80%
rename from custos-services/custos-core-services/custos-logging/src/main/java/org/apache/custos/logging/persistance/repository/LogEventRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/user/GroupAttributeRepository.java
index 87f933d11..a45febb64 100644
--- a/custos-services/custos-core-services/custos-logging/src/main/java/org/apache/custos/logging/persistance/repository/LogEventRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/GroupAttributeRepository.java
@@ -17,12 +17,10 @@
* under the License.
*/
-package org.apache.custos.logging.persistance.repository;
+package org.apache.custos.core.repo.user;
-import org.apache.custos.logging.persistance.model.LogEvent;
+import org.apache.custos.core.model.user.GroupAttribute;
import org.springframework.data.jpa.repository.JpaRepository;
-public interface LogEventRepository extends JpaRepository<LogEvent, Long>, LogEventRepo {
-
-
+public interface GroupAttributeRepository extends JpaRepository<GroupAttribute, Long> {
}
diff --git a/custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/persistance/repository/PermissionTypeRepository.java b/core/src/main/java/org/apache/custos/core/repo/user/GroupMembershipRepository.java
similarity index 56%
rename from custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/persistance/repository/PermissionTypeRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/user/GroupMembershipRepository.java
index bd38c5819..847c61f2e 100644
--- a/custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/persistance/repository/PermissionTypeRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/GroupMembershipRepository.java
@@ -17,18 +17,22 @@
* under the License.
*/
-package org.apache.custos.sharing.core.persistance.repository;
+package org.apache.custos.core.repo.user;
-
-import org.apache.custos.sharing.core.persistance.model.PermissionType;
+import org.apache.custos.core.model.user.UserGroupMembership;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
-import java.util.Optional;
-public interface PermissionTypeRepository extends JpaRepository<PermissionType, String> {
+public interface GroupMembershipRepository extends JpaRepository<UserGroupMembership, String> {
+
+ List<UserGroupMembership> findAllByGroupId(String id);
+
+ List<UserGroupMembership> findAllByUserProfileId(String id);
+
+ List<UserGroupMembership> findAllByGroupIdAndUserProfileId(String groupEntityId, String userProfileId);
- public List<PermissionType> findAllByTenantId(String tenantId);
+ List<UserGroupMembership> findAllByGroupIdAndUserProfileIdAndUserGroupMembershipTypeId(String groupId, String userProfileId, String groupMembershipId);
- public Optional<PermissionType> findByExternalIdAndTenantId(String externalId, String tenantId);
+ List<UserGroupMembership> findAllByGroupIdAndUserGroupMembershipTypeId(String id, String groupMembershipId);
}
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/GroupMembershipTypeRepository.java b/core/src/main/java/org/apache/custos/core/repo/user/GroupMembershipTypeRepository.java
similarity index 87%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/GroupMembershipTypeRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/user/GroupMembershipTypeRepository.java
index feafa804b..4c0353fff 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/GroupMembershipTypeRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/GroupMembershipTypeRepository.java
@@ -17,12 +17,10 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.repository;
+package org.apache.custos.core.repo.user;
-import org.apache.custos.user.profile.persistance.model.UserGroupMembershipType;
+import org.apache.custos.core.model.user.UserGroupMembershipType;
import org.springframework.data.jpa.repository.JpaRepository;
public interface GroupMembershipTypeRepository extends JpaRepository<UserGroupMembershipType, String> {
-
-
}
diff --git a/custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/persistance/repository/EntityTypeRepository.java b/core/src/main/java/org/apache/custos/core/repo/user/GroupRepository.java
similarity index 76%
rename from custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/persistance/repository/EntityTypeRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/user/GroupRepository.java
index a420005ee..ae484b28e 100644
--- a/custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/persistance/repository/EntityTypeRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/GroupRepository.java
@@ -17,15 +17,16 @@
* under the License.
*/
-package org.apache.custos.sharing.core.persistance.repository;
+package org.apache.custos.core.repo.user;
-import org.apache.custos.sharing.core.persistance.model.EntityType;
+import org.apache.custos.core.model.user.Group;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
-public interface EntityTypeRepository extends JpaRepository<EntityType, String> {
+public interface GroupRepository extends JpaRepository<Group, String>, SearchGroupsRepository {
+ List<Group> findByParentId(String s);
- public List<EntityType> findAllByTenantId(String tenantId);
+ List<Group> findAllByTenantId(long tenantId);
}
diff --git a/custos-services/custos-core-services/custos-messaging-core-service/src/main/java/org/apache/custos/messaging/persistance/repository/EmailReceiversRepository.java b/core/src/main/java/org/apache/custos/core/repo/user/GroupRoleRepository.java
similarity index 80%
rename from custos-services/custos-core-services/custos-messaging-core-service/src/main/java/org/apache/custos/messaging/persistance/repository/EmailReceiversRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/user/GroupRoleRepository.java
index 2a2128f4e..e689709b2 100644
--- a/custos-services/custos-core-services/custos-messaging-core-service/src/main/java/org/apache/custos/messaging/persistance/repository/EmailReceiversRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/GroupRoleRepository.java
@@ -17,10 +17,10 @@
* under the License.
*/
-package org.apache.custos.messaging.persistance.repository;
+package org.apache.custos.core.repo.user;
-import org.apache.custos.messaging.persistance.model.EmailReceivers;
+import org.apache.custos.core.model.user.GroupRole;
import org.springframework.data.jpa.repository.JpaRepository;
-public interface EmailReceiversRepository extends JpaRepository<EmailReceivers,Long> {
+public interface GroupRoleRepository extends JpaRepository<GroupRole, Long> {
}
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/GroupToGroupMembershipRepository.java b/core/src/main/java/org/apache/custos/core/repo/user/GroupToGroupMembershipRepository.java
similarity index 71%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/GroupToGroupMembershipRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/user/GroupToGroupMembershipRepository.java
index a87201181..403efe234 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/GroupToGroupMembershipRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/GroupToGroupMembershipRepository.java
@@ -17,19 +17,16 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.repository;
+package org.apache.custos.core.repo.user;
-import org.apache.custos.user.profile.persistance.model.GroupToGroupMembership;
+import org.apache.custos.core.model.user.GroupToGroupMembership;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface GroupToGroupMembershipRepository extends JpaRepository<GroupToGroupMembership, String> {
- public List<GroupToGroupMembership> findByChildIdAndParentId(String childId, String parentId);
-
- public List<GroupToGroupMembership> findAllByChildId(String childId);
-
- public List<GroupToGroupMembership> findAllByParentId(String parentId);
-
+ List<GroupToGroupMembership> findAllByChildId(String childId);
+ List<GroupToGroupMembership> findByChildIdAndParentId(String childId, String parentId);
+ List<GroupToGroupMembership> findAllByParentId(String parentId);
}
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/SearchGroupsRepository.java b/core/src/main/java/org/apache/custos/core/repo/user/SearchGroupsRepository.java
similarity index 81%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/SearchGroupsRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/user/SearchGroupsRepository.java
index 2c9694420..04bac85b8 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/SearchGroupsRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/SearchGroupsRepository.java
@@ -17,14 +17,14 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.repository;
+package org.apache.custos.core.repo.user;
-import org.apache.custos.user.profile.persistance.model.Group;
+
+import org.apache.custos.core.model.user.Group;
import java.util.List;
public interface SearchGroupsRepository {
- List<Group> searchEntities(long tenantId, org.apache.custos.user.profile.service.Group group,int offset,
- int limit);
+ List<Group> searchEntities(long tenantId, org.apache.custos.core.user.profile.api.Group group, int offset, int limit);
}
diff --git a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/SearchGroupsRepositoryImpl.java b/core/src/main/java/org/apache/custos/core/repo/user/SearchGroupsRepositoryImpl.java
similarity index 79%
rename from custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/SearchGroupsRepositoryImpl.java
rename to core/src/main/java/org/apache/custos/core/repo/user/SearchGroupsRepositoryImpl.java
index 94f99e6df..52aa57187 100644
--- a/custos-services/custos-core-services/user-profile-core-service/src/main/java/org/apache/custos/user/profile/persistance/repository/SearchGroupsRepositoryImpl.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/SearchGroupsRepositoryImpl.java
@@ -17,16 +17,15 @@
* under the License.
*/
-package org.apache.custos.user.profile.persistance.repository;
-
-import org.apache.custos.user.profile.persistance.model.Group;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Repository;
+package org.apache.custos.core.repo.user;
+import org.apache.custos.core.model.user.Group;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Repository;
+
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@@ -35,58 +34,42 @@ import java.util.Map;
@Repository
public class SearchGroupsRepositoryImpl implements SearchGroupsRepository {
- private static final Logger LOGGER = LoggerFactory.getLogger(SearchGroupsRepositoryImpl.class);
-
@PersistenceContext
EntityManager entityManager;
@Override
- public List<Group> searchEntities(long tenantId, org.apache.custos.user.profile.service.Group group, int offset,
- int limit) {
+ public List<Group> searchEntities(long tenantId, org.apache.custos.core.user.profile.api.Group group, int offset, int limit) {
Map<String, Object> valueMap = new HashMap<>();
- String query = createSQLQuery(tenantId, group, valueMap, offset, limit);
-
+ String query = createSQLQuery(tenantId, group, valueMap, offset, limit);
Query q = entityManager.createNativeQuery(query, Group.class);
- for (String key : valueMap.keySet()) {
- q.setParameter(key, valueMap.get(key));
- }
+ valueMap.forEach(q::setParameter);
return q.getResultList();
}
- private String createSQLQuery(long tenantId, org.apache.custos.user.profile.service.Group group,
- Map<String, Object> valueMap, int offset, int limit) {
-
+ private String createSQLQuery(long tenantId, org.apache.custos.core.user.profile.api.Group group, Map<String, Object> valueMap, int offset, int limit) {
String query = "SELECT * FROM group_entity E WHERE ";
if (!group.getName().isBlank()) {
-
- query = query + "E.name LIKE :" + "name" + " AND ";
-
+ query = query + "E.name LIKE :" + "name" + " AND ";
valueMap.put("name", group.getName());
}
- if (!group.getDescription().isBlank()) {
-
+ if (StringUtils.isNotBlank(group.getDescription())) {
query = query + "E.description LIKE :" + "description" + " AND ";
-
valueMap.put("description", group.getDescription());
}
- if (!group.getId().isBlank()) {
+ if (StringUtils.isNotBlank(group.getId())) {
query = query + "E.external_id = :" + "external_id" + " AND ";
-
valueMap.put("external_id", group.getId());
}
if (group.getCreatedTime() != 0) {
-
Date date = new Date(group.getCreatedTime());
-
query = query + "E.created_at >= :" + "created_at" + " AND ";
-
valueMap.put("created_at", date);
}
@@ -96,16 +79,13 @@ public class SearchGroupsRepositoryImpl implements SearchGroupsRepository {
valueMap.put("last_modified_at", date);
}
- if (tenantId != 0) {
+ if (tenantId != 0) {
query = query + "E.tenant_id = :" + "tenant_id" + " AND ";
-
valueMap.put("tenant_id", tenantId);
}
-
query = query.substring(0, query.length() - 5);
-
query = query + " ORDER BY E.created_at DESC";
if (limit > 0) {
diff --git a/custos-services/custos-core-services/custos-logging/src/main/java/org/apache/custos/logging/persistance/repository/LoggingEnabledStatusRepository.java b/core/src/main/java/org/apache/custos/core/repo/user/StatusUpdateMetadataRepository.java
similarity index 74%
rename from custos-services/custos-core-services/custos-logging/src/main/java/org/apache/custos/logging/persistance/repository/LoggingEnabledStatusRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/user/StatusUpdateMetadataRepository.java
index 837b1cb58..df1484602 100644
--- a/custos-services/custos-core-services/custos-logging/src/main/java/org/apache/custos/logging/persistance/repository/LoggingEnabledStatusRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/StatusUpdateMetadataRepository.java
@@ -17,11 +17,14 @@
* under the License.
*/
-package org.apache.custos.logging.persistance.repository;
+package org.apache.custos.core.repo.user;
-import org.apache.custos.logging.persistance.model.LoggingEnabledStatus;
+import org.apache.custos.core.model.user.StatusUpdateMetadata;
import org.springframework.data.jpa.repository.JpaRepository;
-public interface LoggingEnabledStatusRepository extends JpaRepository<LoggingEnabledStatus, Long> {
+import java.util.List;
+public interface StatusUpdateMetadataRepository extends JpaRepository<StatusUpdateMetadata, Long> {
+
+ List<StatusUpdateMetadata> findAllByUserProfileId(String userId);
}
diff --git a/custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/persistance/repository/EntityRepository.java b/core/src/main/java/org/apache/custos/core/repo/user/UserAttributeRepository.java
similarity index 65%
rename from custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/persistance/repository/EntityRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/user/UserAttributeRepository.java
index 4d48b61d8..a54cb4437 100644
--- a/custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/persistance/repository/EntityRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/UserAttributeRepository.java
@@ -17,18 +17,17 @@
* under the License.
*/
-package org.apache.custos.sharing.core.persistance.repository;
+package org.apache.custos.core.repo.user;
-
-import org.apache.custos.sharing.core.persistance.model.Entity;
+import org.apache.custos.core.model.user.UserAttribute;
+import org.apache.custos.core.model.user.UserProfile;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
import java.util.List;
-public interface EntityRepository extends JpaRepository<Entity, String>, SearchEntityRepository {
-
- public List<Entity> findAllByExternalParentIdAndTenantId(String externalParentId, String tenantId);
-
- public List<Entity> findAllByTenantId(String tenantId);
+public interface UserAttributeRepository extends JpaRepository<UserAttribute, Long> {
+ @Query("SELECT DISTINCT atr.userProfile from UserAttribute atr where atr.keyValue = ?1 and atr.value =?2")
+ List<UserProfile> findFilteredUserProfiles(String key, String value);
}
diff --git a/custos-services/custos-core-services/custos-messaging-core-service/src/main/java/org/apache/custos/messaging/persistance/repository/EmailTemplateRepository.java b/core/src/main/java/org/apache/custos/core/repo/user/UserProfileRepository.java
similarity index 63%
rename from custos-services/custos-core-services/custos-messaging-core-service/src/main/java/org/apache/custos/messaging/persistance/repository/EmailTemplateRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/user/UserProfileRepository.java
index 7c8af639d..5ceb5e49f 100644
--- a/custos-services/custos-core-services/custos-messaging-core-service/src/main/java/org/apache/custos/messaging/persistance/repository/EmailTemplateRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/UserProfileRepository.java
@@ -17,19 +17,19 @@
* under the License.
*/
-package org.apache.custos.messaging.persistance.repository;
+package org.apache.custos.core.repo.user;
-import org.apache.custos.messaging.persistance.model.EmailTemplate;
+import org.apache.custos.core.model.user.UserProfile;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
import java.util.List;
-import java.util.Optional;
-public interface EmailTemplateRepository extends JpaRepository<EmailTemplate, Long> {
- public Optional<EmailTemplate> findByTenantIdAndCustosEvent(long tenantId, String custosEvent);
+public interface UserProfileRepository extends JpaRepository<UserProfile, String> {
- public List<EmailTemplate> findByTenantId(long tenantId);
-
-}
+ List<UserProfile> findByTenantId(long tenantId);
+ @Query(value = "SELECT * FROM user_profile t WHERE t.tenant_id LIKE ?1 ORDER BY t.id limit ?2 OFFSET ?3", nativeQuery = true)
+ List<UserProfile> findByTenantIdWithPagination(long tenantId, long limit, long offset);
+}
diff --git a/custos-services/custos-core-services/custos-messaging-core-service/src/main/java/org/apache/custos/messaging/persistance/repository/EmailBodyParamsRepository.java b/core/src/main/java/org/apache/custos/core/repo/user/UserRoleRepository.java
similarity index 79%
rename from custos-services/custos-core-services/custos-messaging-core-service/src/main/java/org/apache/custos/messaging/persistance/repository/EmailBodyParamsRepository.java
rename to core/src/main/java/org/apache/custos/core/repo/user/UserRoleRepository.java
index 1634d3e55..fd9887f72 100644
--- a/custos-services/custos-core-services/custos-messaging-core-service/src/main/java/org/apache/custos/messaging/persistance/repository/EmailBodyParamsRepository.java
+++ b/core/src/main/java/org/apache/custos/core/repo/user/UserRoleRepository.java
@@ -17,10 +17,10 @@
* under the License.
*/
-package org.apache.custos.messaging.persistance.repository;
+package org.apache.custos.core.repo.user;
-import org.apache.custos.messaging.persistance.model.EmailBodyParams;
+import org.apache.custos.core.model.user.UserRole;
import org.springframework.data.jpa.repository.JpaRepository;
-public interface EmailBodyParamsRepository extends JpaRepository<EmailBodyParams, Long> {
+public interface UserRoleRepository extends JpaRepository<UserRole, Long> {
}
diff --git a/custos-services/custos-integration-core/src/main/java/org/apache/custos/integration/core/ServiceCallback.java b/core/src/main/java/org/apache/custos/core/task/ServiceCallback.java
similarity index 89%
rename from custos-services/custos-integration-core/src/main/java/org/apache/custos/integration/core/ServiceCallback.java
rename to core/src/main/java/org/apache/custos/core/task/ServiceCallback.java
index 8d78f67b1..30ee3279a 100644
--- a/custos-services/custos-integration-core/src/main/java/org/apache/custos/integration/core/ServiceCallback.java
+++ b/core/src/main/java/org/apache/custos/core/task/ServiceCallback.java
@@ -17,10 +17,10 @@
* under the License.
*/
-package org.apache.custos.integration.core;
+package org.apache.custos.core.task;
/**
- * An interface represents callback for async communication
+ * A callback interface for service completion and error handling
*/
public interface ServiceCallback {
diff --git a/core/src/main/java/org/apache/custos/core/task/ServiceChain.java b/core/src/main/java/org/apache/custos/core/task/ServiceChain.java
new file mode 100644
index 000000000..ea575fadd
--- /dev/null
+++ b/core/src/main/java/org/apache/custos/core/task/ServiceChain.java
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.custos.core.task;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A class represents the set of services that needs to be invoked to complete a full operation
+ */
+public final class ServiceChain {
+
+ private final List<ServiceTask> serviceTasks;
+
+
+ private ServiceChain(ServiceChainBuilder serviceChainBuilder) {
+ this.serviceTasks = serviceChainBuilder.serviceTasks;
+ }
+
+ public void serve(Object data) {
+ if (!serviceTasks.isEmpty()) {
+ serviceTasks.get(0).invokeService(data);
+ }
+ }
+
+ public static class ServiceChainBuilder {
+
+ private ServiceCallback serviceCallback;
+ private List<ServiceTask> serviceTasks = new ArrayList();
+ private ServiceTask latestTask;
+
+ private ServiceChainBuilder(ServiceTask firstTask, ServiceCallback serviceCallback) {
+ this.latestTask = firstTask;
+ this.serviceCallback = serviceCallback;
+ this.latestTask.setServiceCallback(serviceCallback);
+ this.serviceTasks.add(this.latestTask);
+ }
+
+ public ServiceChainBuilder nextTask(ServiceTask serviceTask) {
+ this.latestTask.setNextTask(serviceTask);
+ this.latestTask = serviceTask;
+ this.latestTask.setServiceCallback(serviceCallback);
+ this.serviceTasks.add(this.latestTask);
+ return this;
+ }
+
+ public ServiceChain build() {
+ ServiceChain serviceChain = new ServiceChain(this);
+ return serviceChain;
+ }
+ }
+
+ public static ServiceChainBuilder newBuilder(ServiceTask firstTask, ServiceCallback serviceCallback) {
+ return new ServiceChainBuilder(firstTask, serviceCallback);
+ }
+}
diff --git a/custos-services/custos-integration-core/src/main/java/org/apache/custos/integration/core/ServiceException.java b/core/src/main/java/org/apache/custos/core/task/ServiceException.java
similarity index 71%
rename from custos-services/custos-integration-core/src/main/java/org/apache/custos/integration/core/ServiceException.java
rename to core/src/main/java/org/apache/custos/core/task/ServiceException.java
index e348f4213..69de90167 100644
--- a/custos-services/custos-integration-core/src/main/java/org/apache/custos/integration/core/ServiceException.java
+++ b/core/src/main/java/org/apache/custos/core/task/ServiceException.java
@@ -17,18 +17,21 @@
* under the License.
*/
-package org.apache.custos.integration.core;
+package org.apache.custos.core.task;
/**
- * This class wraps exceptions arising in custos message flow and
- * has a local error code
+ * ServiceException represents an exception that is thrown when an error occurs in a service.
*/
-public class ServiceException extends Exception{
+public class ServiceException extends Exception {
- private String code;
+ private final String code;
- public ServiceException (String message, Throwable cause, String code) {
+ public ServiceException(String message, Throwable cause, String code) {
super(message, cause);
this.code = code;
}
+
+ public String getCode() {
+ return code;
+ }
}
diff --git a/custos-services/custos-integration-core/src/main/java/org/apache/custos/integration/core/ServiceTask.java b/core/src/main/java/org/apache/custos/core/task/ServiceTask.java
similarity index 68%
rename from custos-services/custos-integration-core/src/main/java/org/apache/custos/integration/core/ServiceTask.java
rename to core/src/main/java/org/apache/custos/core/task/ServiceTask.java
index 4409bf520..53ca518d9 100644
--- a/custos-services/custos-integration-core/src/main/java/org/apache/custos/integration/core/ServiceTask.java
+++ b/core/src/main/java/org/apache/custos/core/task/ServiceTask.java
@@ -17,11 +17,16 @@
* under the License.
*/
-package org.apache.custos.integration.core;
+package org.apache.custos.core.task;
/**
- * Interface represents service task for invoking core services
- * Service task is bind to a single operation of one client
+ * The ServiceTask interface represents a task that can be invoked and chained
+ * with other tasks. It provides methods for invoking the service, invoking the
+ * next task in the chain, setting the next task in the chain, and setting a
+ * service callback.
+ *
+ * @param <T> the type of data input to the service
+ * @param <U> the type of data output from the service
*/
public interface ServiceTask<T, U> {
@@ -29,7 +34,7 @@ public interface ServiceTask<T, U> {
void invokeNextTask(U data);
- void setNextTask(ServiceTask serviceTask);
+ void setNextTask(ServiceTask<T, U> serviceTask);
void setServiceCallback(ServiceCallback serviceCallback);
diff --git a/custos-services/custos-integration-core/src/main/java/org/apache/custos/integration/core/ServiceTaskImpl.java b/core/src/main/java/org/apache/custos/core/task/ServiceTaskImpl.java
similarity index 67%
rename from custos-services/custos-integration-core/src/main/java/org/apache/custos/integration/core/ServiceTaskImpl.java
rename to core/src/main/java/org/apache/custos/core/task/ServiceTaskImpl.java
index dda18b743..76c6d1baf 100644
--- a/custos-services/custos-integration-core/src/main/java/org/apache/custos/integration/core/ServiceTaskImpl.java
+++ b/core/src/main/java/org/apache/custos/core/task/ServiceTaskImpl.java
@@ -17,19 +17,22 @@
* under the License.
*/
-package org.apache.custos.integration.core;
+package org.apache.custos.core.task;
/**
- *An abstract class of ServiceTaskImpl classes, which implements invokeNextTask logic
+ * ServiceTaskImpl is an abstract class that implements the ServiceTask interface.
+ * This implements invokeNextTask logic
+ *
+ * @param <T> the type of data input to the service
+ * @param <U> the type of data output from the service
*/
public abstract class ServiceTaskImpl<T, U> implements ServiceTask<T, U> {
private ServiceCallback serviceCallback;
- private ServiceTask nextTask;
-
- private String taskStatus= "Success";
+ private ServiceTask<T, U> nextTask;
+ private final String SUCCESS_TASK_STATUS = "Success";
public void setServiceCallback(ServiceCallback serviceCallback) {
@@ -40,23 +43,21 @@ public abstract class ServiceTaskImpl<T, U> implements ServiceTask<T, U> {
return serviceCallback;
}
- public void setNextTask(ServiceTask nextTask) {
+ public void setNextTask(ServiceTask<T, U> nextTask) {
this.nextTask = nextTask;
}
- public ServiceTask getNextTask() {
+ public ServiceTask<T, U> getNextTask() {
return nextTask;
}
@Override
- public void invokeNextTask(U output){
- if (nextTask != null){
- nextTask.invokeService(output);
+ public void invokeNextTask(U output) {
+ if (nextTask != null) {
+ nextTask.invokeService((T) output);
} else {
System.out.println("Calling Parent Callback");
- serviceCallback.onCompleted(taskStatus);
+ serviceCallback.onCompleted(SUCCESS_TASK_STATUS);
}
-
}
-
}
diff --git a/core/src/main/proto/CredentialStore.proto b/core/src/main/proto/CredentialStore.proto
new file mode 100644
index 000000000..2caf6ffa3
--- /dev/null
+++ b/core/src/main/proto/CredentialStore.proto
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+package org.apache.custos.core.credential.store.api;
+
+
+enum Type {
+ CUSTOS = 0;
+ IAM = 1;
+ CILOGON = 2;
+ INDIVIDUAL = 3;
+ AGENT_CLIENT = 4;
+ AGENT = 5;
+}
+
+message CredentialMetadata {
+ int64 owner_id = 1;
+ string id = 2;
+ string secret = 3;
+ int64 client_secret_expired_at = 4;
+ int64 client_id_issued_at = 5;
+ Type type = 6;
+ bool super_tenant = 7;
+ bool super_admin = 8;
+ string internal_sec = 11;
+}
+
+message GetCredentialRequest {
+ int64 ownerId = 1;
+ string id = 2;
+ Type type = 3;
+}
+
+message GetAllCredentialsRequest {
+ int64 ownerId = 1;
+}
+
+message GetAllCredentialsResponse {
+ repeated CredentialMetadata secret_list = 1;
+ string requester_user_email = 2;
+ string requester_username = 3;
+}
+
+message OperationStatus {
+ bool state = 1;
+}
+
+message DeleteCredentialRequest {
+ int64 owner_id = 1;
+ Type type = 2;
+}
+
+message GetOperationsMetadataRequest {
+ int64 trace_id = 1;
+}
+
+message OperationMetadata {
+ string event = 1;
+ string status = 2;
+ string time_stamp = 3;
+ string performed_by = 4;
+}
+message GetOperationsMetadataResponse {
+ repeated OperationMetadata metadata = 1;
+}
+
+message GetNewCustosCredentialRequest {
+ int64 owner_id = 1;
+ string performed_by = 2;
+ bool is_super_tenant = 3;
+}
+
+message GetNewCustosCredentialResponse {
+ string client_id = 1;
+ string client_secret = 2;
+}
+
+message TokenRequest {
+ string token = 1;
+ string parent_client_id = 2;
+}
+
+message GetOwnerIdResponse {
+ int64 owner_id = 2;
+}
+
+message Credentials {
+ string iam_client_id = 1;
+ string iam_client_secret = 2;
+ string ci_logon_client_id = 3;
+ string ci_logon_client_secret = 4;
+ string custos_client_id = 5;
+ string custos_client_secret = 6;
+ double custos_client_id_issued_at = 7;
+ double custos_client_secret_expired_at = 8;
+}
diff --git a/core/src/main/proto/FederatedAuthentication.proto b/core/src/main/proto/FederatedAuthentication.proto
new file mode 100644
index 000000000..578c744cc
--- /dev/null
+++ b/core/src/main/proto/FederatedAuthentication.proto
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+package org.apache.custos.core.federated.authentication.api;
+
+
+enum InstitutionCacheType {
+ ALLOWLIST = 0;
+ BLOCKLIST = 1;
+}
+
+
+message ClientMetadata {
+ int64 tenant_id = 1;
+ string tenant_name = 2;
+ repeated string scope = 3;
+ string tenant_uRI = 4;
+ repeated string contacts = 5;
+ string comment = 6;
+ repeated string redirect_uRIs = 7;
+ string client_id = 8;
+ string performed_by = 9;
+}
+
+
+message RegisterClientResponse {
+ string client_id = 1;
+ string client_secret = 2;
+ int64 client_id_issued_at = 3;
+ int64 client_secret_expires_at = 4;
+ string client_registration_uri = 5;
+}
+
+
+message GetClientRequest {
+ int64 tenant_id = 1;
+ string client_id = 2;
+}
+
+message GetClientResponse {
+ string client_id = 1;
+ string client_name = 2;
+ repeated string redirect_uRIs = 3;
+ repeated string grant_types = 4;
+ repeated string scope = 5;
+ int64 client_id_issued_at = 6;
+ string comment = 7;
+ string client_secret = 8;
+ int64 client_secret_expires_at = 9;
+ string client_registration_uri = 10;
+}
+
+message DeleteClientRequest {
+ int64 tenant_id = 1;
+ string client_id = 2;
+ string performed_by = 3;
+}
+
+message Empty {
+
+}
+
+message GetOperationsMetadataRequest {
+ int64 trace_id = 1;
+}
+
+message OperationMetadata {
+ string event = 1;
+ string status = 2;
+ string time_stamp = 3;
+ string performed_by = 4;
+}
+message GetOperationsMetadataResponse {
+ repeated OperationMetadata metadata = 1;
+}
+
+
+message CacheManipulationRequest {
+ int64 tenant_id = 1;
+ repeated string institution_ids = 2;
+ InstitutionCacheType type = 3;
+ string performedBy = 4;
+}
+
+message Status {
+ bool status = 1;
+}
+
+message InstitutionOperationResponse {
+
+}
+
+message Institution {
+ string entity_id = 1;
+ string organization_name = 2;
+ string display_name = 3;
+ bool rand_s = 4;
+}
+
+message GetInstitutionsIdsAsResponse {
+ repeated string entity_ids = 1;
+}
+
+
+message GetInstitutionsResponse {
+ repeated Institution institutions = 2;
+}
diff --git a/core/src/main/proto/IamAdmin.proto b/core/src/main/proto/IamAdmin.proto
new file mode 100644
index 000000000..e6c783687
--- /dev/null
+++ b/core/src/main/proto/IamAdmin.proto
@@ -0,0 +1,434 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+package org.apache.custos.core.iam.api;
+
+
+enum FederatedIDPs {
+ CILOGON = 0;
+ FACEBOOK = 1;
+ GOOGLE = 2;
+ LINKEDIN = 3;
+ TWITTER = 4;
+ CUSTOM_OIDC = 5;
+}
+
+
+message SetUpTenantRequest {
+ int64 tenant_id = 1;
+ string tenant_name = 2;
+ string admin_username = 3;
+ string admin_firstname = 4;
+ string admin_lastname = 5;
+ string admin_email = 6;
+ string admin_password = 7;
+ string tenant_uRL = 8;
+ string requester_email = 9;
+ repeated string redirect_uRIs = 10;
+ string custos_client_id = 11;
+
+}
+
+message ConfigureFederateIDPRequest {
+ int64 tenant_id = 1;
+ FederatedIDPs type = 2;
+ string client_iD = 3;
+ string client_sec = 4;
+ map<string, string> config_map = 5;
+ string requester_email = 6;
+ string idp_id = 7;
+ string scope = 8;
+}
+
+
+message FederateIDPResponse {
+ bool status = 1;
+}
+
+message SetUpTenantResponse {
+ string client_id = 1;
+ string client_secret = 2;
+}
+
+message IsUsernameAvailableRequest {
+ int64 tenant_id = 1;
+ string access_token = 2;
+ string user_name = 3;
+
+}
+
+message CheckingResponse {
+ bool is_exist = 1;
+}
+
+
+message UserRepresentation {
+ string id = 1;
+ string username = 3;
+ string first_name = 4;
+ string last_name = 5;
+ string password = 6;
+ string email = 7;
+ bool temporary_password = 8;
+ repeated string realm_roles = 9;
+ repeated string client_roles = 10;
+ repeated UserAttribute attributes = 11;
+ string state = 12;
+ double creation_time = 13;
+ double last_login_at = 14;
+}
+
+
+message GroupRepresentation {
+ string name = 1;
+ string id = 2;
+ repeated string realm_roles = 3;
+ repeated string client_roles = 4;
+ repeated UserAttribute attributes = 5;
+ repeated UserRepresentation users = 6;
+ repeated GroupRepresentation sub_groups = 7;
+ string description = 8;
+ string ownerId = 9;
+}
+
+
+message RegisterUserRequest {
+ int64 tenant_id = 1;
+ string access_token = 2;
+ string client_id = 3;
+ string client_sec = 4;
+ UserRepresentation user = 5;
+ string performed_by = 6;
+}
+
+
+message RegisterUsersRequest {
+ repeated UserRepresentation users = 1;
+ int64 tenant_id = 2;
+ string access_token = 3;
+ string client_id = 4;
+ string performed_by = 5;
+}
+
+message RegisterUserResponse {
+ bool is_registered = 1;
+}
+
+message RegisterUsersResponse {
+ bool all_useres_registered = 1;
+ repeated UserRepresentation failed_users = 2;
+}
+
+
+message UserSearchMetadata {
+ string username = 1;
+ string first_name = 2;
+ string last_name = 3;
+ string email = 4;
+ string id = 5;
+}
+
+message FindUsersRequest {
+ UserSearchMetadata user = 3;
+ int32 offset = 4;
+ int32 limit = 5;
+ int64 tenant_id = 1;
+ string access_token = 2;
+ string client_id = 6;
+ string client_sec = 7;
+
+}
+
+message UserSearchRequest {
+ UserSearchMetadata user = 1;
+ int64 tenant_id = 2;
+ string access_token = 3;
+ string client_id = 4;
+ string client_sec = 5;
+ string performed_by = 6;
+}
+
+message FindUsersResponse {
+ repeated UserRepresentation users = 1;
+}
+
+message ResetUserPassword {
+ string username = 1;
+ string password = 2;
+ int64 tenant_id = 3;
+ string access_token = 4;
+ string client_id = 5;
+ string client_sec = 6;
+ string old_password = 7;
+}
+
+
+message DeleteUserRolesRequest {
+ int64 tenant_id = 1;
+ string username = 2;
+ repeated string client_roles = 3;
+ repeated string roles = 4;
+ string access_token = 5;
+ string client_id = 6;
+ string performed_by = 7;
+ string id = 8;
+}
+
+message AddUserRolesRequest {
+ int64 tenant_id = 1;
+ repeated string usernames = 2;
+ repeated string roles = 3;
+ string access_token = 4;
+ string client_id = 5;
+ bool client_level = 6;
+ string performed_by = 7;
+ repeated string agents = 8;
+}
+
+message UpdateUserProfileRequest {
+ string access_token = 1;
+ int64 tenant_id = 2;
+ UserRepresentation user = 3;
+
+}
+
+message AddUserResponse {
+ string code = 1;
+}
+
+message GetOperationsMetadataRequest {
+ int64 trace_id = 1;
+}
+
+message OperationMetadata {
+ string event = 1;
+ string status = 2;
+ string time_stamp = 3;
+ string performed_by = 4;
+}
+message GetOperationsMetadataResponse {
+ repeated OperationMetadata metadata = 1;
+}
+
+message DeleteTenantRequest {
+ int64 tenant_id = 1;
+}
+
+message AddRolesRequest {
+ repeated RoleRepresentation roles = 1;
+ bool client_level = 2;
+ int64 tenant_id = 3;
+ string client_id = 4;
+}
+
+message GetRolesRequest {
+ bool client_level = 1;
+ int64 tenant_id = 2;
+ string client_id = 3;
+}
+
+message RoleRepresentation {
+ string name = 1;
+ string description = 2;
+ bool composite = 3;
+ string id = 4;
+}
+
+message DeleteRoleRequest {
+ bool client_level = 1;
+ int64 tenant_id = 2;
+ string client_id = 3;
+ RoleRepresentation role = 4;
+}
+
+message AllRoles {
+ repeated RoleRepresentation roles = 1;
+ string scope = 2;
+}
+
+message AddProtocolMapperRequest {
+ string name = 1;
+ string attribute_name = 2;
+ string claim_name = 3;
+ ClaimJSONTypes claim_type = 4;
+ int64 tenant_id = 6;
+ string client_id = 7;
+ MapperTypes mapper_type = 8;
+ bool add_to_id_token = 9;
+ bool add_to_access_token = 10;
+ bool add_to_user_info = 11;
+ bool multi_valued = 12;
+ bool aggregate_attribute_values = 13;
+}
+
+enum MapperTypes {
+ USER_ATTRIBUTE = 0;
+ USER_REALM_ROLE = 1;
+ USER_CLIENT_ROLE = 2;
+}
+
+enum ClaimJSONTypes {
+ STRING = 0;
+ LONG = 1;
+ INTEGER = 2;
+ BOOLEAN = 3;
+ JSON = 4;
+}
+
+enum ResourceTypes {
+ USER = 0;
+ AGENT = 1;
+}
+
+message OperationStatus {
+ bool status = 1;
+}
+
+message AddUserAttributesRequest {
+ repeated UserAttribute attributes = 1;
+ repeated string users = 2;
+ int64 tenant_id = 3;
+ string client_id = 4;
+ string access_token = 5;
+ string performedBy = 6;
+ repeated string agents = 7;
+}
+
+message DeleteUserAttributeRequest {
+ repeated UserAttribute attributes = 1;
+ repeated string users = 2;
+ int64 tenant_id = 3;
+ string client_id = 4;
+ string access_token = 5;
+ string performedBy = 6;
+ repeated string agents = 7;
+}
+
+message UserAttribute {
+ string key = 1;
+ repeated string values = 2;
+}
+
+message EventPersistenceRequest {
+ int64 tenantId = 1;
+ bool admin_event = 2;
+ string event = 3;
+ bool enable = 4;
+ int64 persistence_time = 5;
+ string performedBy = 6;
+}
+
+
+message GroupsRequest {
+ int64 tenantId = 1;
+ string accessToken = 2;
+ string performedBy = 3;
+ string clientId = 4;
+ string clientSec = 5;
+ repeated GroupRepresentation groups = 6;
+}
+
+message GroupRequest {
+ int64 tenantId = 1;
+ string accessToken = 2;
+ string performedBy = 3;
+ string clientId = 4;
+ string clientSec = 5;
+ string id = 6;
+ GroupRepresentation group = 7;
+}
+
+message GroupsResponse {
+ repeated GroupRepresentation groups = 1;
+}
+
+message UserGroupMappingRequest {
+ int64 tenantId = 1;
+ string accessToken = 2;
+ string performedBy = 3;
+ string clientId = 4;
+ string clientSec = 5;
+ string username = 6;
+ string group_id = 7;
+ string membership_type = 8;
+}
+
+message AgentClientMetadata {
+ int64 tenantId = 1;
+ string tenantURL = 2;
+ repeated string redirectURIs = 3;
+ string clientName = 4;
+ int64 access_token_life_time = 5;
+ string performedBy = 6;
+ string access_token = 7;
+}
+
+message Agent {
+ string id = 1;
+ repeated string realm_roles = 2;
+ repeated UserAttribute attributes = 3;
+ bool isEnabled = 4;
+ double creation_time = 5;
+ double last_modified_at = 6;
+ repeated string client_roles = 7;
+}
+
+
+message GetAllResources {
+ int64 tenantId = 1;
+ string clientId = 2;
+ ResourceTypes resource_type = 3;
+}
+
+message GetAllResourcesResponse {
+ repeated Agent agents = 1;
+ repeated UserRepresentation users = 2;
+}
+
+message DeleteExternalIDPsRequest {
+ int64 tenant_id = 1;
+ string client_id = 2;
+ repeated string user_id = 3;
+}
+
+message GetExternalIDPsRequest {
+ int64 tenant_id = 1;
+ string client_id = 2;
+ string user_id = 3;
+}
+
+message ExternalIDPLink {
+ string provider_alias = 1;
+ string provider_user_id = 2;
+ string provider_username = 3;
+}
+
+message GetExternalIDPsResponse {
+ repeated ExternalIDPLink idp_links = 1;
+}
+
+message AddExternalIDPLinksRequest {
+ repeated ExternalIDPLink idp_links = 1;
+ int64 tenant_id = 2;
+ string client_id = 3;
+}
diff --git a/core/src/main/proto/Identity.proto b/core/src/main/proto/Identity.proto
new file mode 100644
index 000000000..66a81509e
--- /dev/null
+++ b/core/src/main/proto/Identity.proto
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+package org.apache.custos.core.identity.api;
+
+
+message AuthToken {
+ string access_token = 1;
+ repeated Claim claims = 2;
+}
+
+message Claim {
+ string key = 1;
+ string value = 2;
+}
+
+message User {
+ string sub = 1;
+ string full_name = 2;
+ string first_name = 3;
+ string last_name = 4;
+ string email_address = 5;
+ string username = 6;
+ string client_id = 7;
+}
+
+
+message GetTokenRequest {
+ int64 tenant_id = 1;
+ string client_id = 2;
+ string client_secret = 3;
+ string redirect_uri = 4;
+ string code = 6;
+ string username = 7;
+ string password = 8;
+ string refresh_token = 9;
+ string grant_type = 10;
+ string code_verifier = 11;
+}
+
+message TokenResponse {
+ string access_token = 1;
+ int32 expires_in = 2;
+ int32 refresh_expires_in = 3;
+ string refresh_token = 4;
+ string token_type = 5;
+ string id_token = 6;
+ int32 not_before_policy = 7;
+ string session_state = 8;
+ string scope = 9;
+}
+
+message OIDCConfiguration {
+ string issuer = 1;
+ string authorization_endpoint = 2;
+ string token_endpoint = 3;
+ string userinfo_endpoint = 4;
+ string jwks_uri = 5;
+ repeated string response_types_supported = 6;
+ repeated string subject_types_supported = 7;
+ repeated string id_token_signing_alg_values_supported = 8;
+ repeated string scopes_supported = 9;
+ repeated string token_endpoint_auth_methods_supported = 10;
+ repeated string claims_supported = 11;
+ repeated string introspection_endpoint_auth_signing_alg_values_supported = 12;
+ bool request_parameter_supported = 13;
+ string pushed_authorization_request_endpoint = 14;
+ string introspection_endpoint = 15;
+ bool claims_parameter_supported = 16;
+ repeated string id_token_encryption_enc_values_supported = 17;
+ repeated string userinfo_encryption_enc_values_supported = 18;
+ repeated string introspection_endpoint_auth_methods_supported = 19;
+ repeated string authorization_encryption_alg_values_supported = 20;
+ bool tls_client_certificate_bound_access_tokens = 21;
+ repeated string response_modes_supported = 22;
+ bool backchannel_logout_session_supported = 23;
+ repeated string backchannel_authentication_request_signing_alg_values_supported = 24;
+ repeated string authorization_encryption_enc_values_supported = 25;
+ repeated string revocation_endpoint_auth_signing_alg_values_supported = 26;
+ repeated string backchannel_token_delivery_modes_supported = 27;
+ repeated string revocation_endpoint_auth_methods_supported = 28;
+ bool request_uri_parameter_supported = 29;
+ repeated string grant_types_supported = 30;
+ bool require_request_uri_registration = 31;
+ repeated string code_challenge_methods_supported = 32;
+ repeated string id_token_encryption_alg_values_supported = 33;
+ bool frontchannel_logout_session_supported = 34;
+ repeated string authorization_signing_alg_values_supported = 35;
+ repeated string request_object_signing_alg_values_supported = 36;
+ repeated string request_object_encryption_alg_values_supported = 37;
+ string check_session_iframe = 38;
+ bool backchannel_logout_supported = 40;
+ repeated string acr_values_supported = 41;
+ repeated string request_object_encryption_enc_values_supported = 42;
+ string device_authorization_endpoint = 43;
+ repeated string userinfo_signing_alg_values_supported = 44;
+ bool require_pushed_authorization_requests = 45;
+ repeated string claim_types_supported = 46;
+ repeated string userinfo_encryption_alg_values_supported = 47;
+ string end_session_endpoint = 48;
+ string revocation_endpoint = 49;
+ string backchannel_authentication_endpoint = 50;
+ bool frontchannel_logout_supported = 51;
+ repeated string token_endpoint_auth_signing_alg_values_supported = 52;
+ string registration_endpoint = 53;
+}
+
+message AuthenticationRequest {
+ string client_id = 1;
+ string client_secret = 2;
+ int64 tenant_id = 3;
+ string username = 4;
+ string password = 5;
+}
+
+message IsAuthenticatedResponse {
+ bool authenticated = 1;
+}
+
+message GetUserManagementSATokenRequest {
+ string client_id = 1;
+ string client_secret = 2;
+ int64 tenant_id = 3;
+}
+
+message GetAuthorizationEndpointRequest {
+ int64 tenant_id = 1;
+}
+
+message AuthorizationResponse {
+ string authorization_endpoint = 2;
+}
+
+message GetOIDCConfiguration {
+ string client_id = 1;
+ string client_secret = 2;
+ int64 tenant_id = 3;
+}
+
+message GetJWKSRequest {
+ string client_id = 1;
+ string client_secret = 2;
+ int64 tenant_id = 3;
+}
+
+message EndSessionRequest {
+ string client_id = 1;
+ string client_secret = 2;
+ int64 tenant_id = 3;
+ string refresh_token = 4;
+}
+
+message OperationStatus {
+ bool status = 1;
+}
diff --git a/core/src/main/proto/IdentityManagement.proto b/core/src/main/proto/IdentityManagement.proto
new file mode 100644
index 000000000..2cc7e9bcf
--- /dev/null
+++ b/core/src/main/proto/IdentityManagement.proto
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+package org.apache.custos.core.identity.management.api;
+
+import "Identity.proto";
+import "CredentialStore.proto";
+
+
+message AuthorizationRequest {
+ int64 tenant_id = 1;
+ string client_id = 2;
+ string client_secret = 3;
+ string redirect_uri = 4;
+ string response_type = 5;
+ string scope = 6;
+ string state = 7;
+ string code_challenge = 8;
+ string code_challenge_method = 9;
+}
+
+message AuthorizationResponse {
+ string redirect_uri = 1;
+}
+
+message GetCredentialsRequest {
+ string client_id = 1;
+ org.apache.custos.core.credential.store.api.Credentials credentials = 2;
+}
+
+message GetAgentTokenRequest {
+ int64 tenant_id = 1;
+ string agent_client_id = 2;
+ string agent_client_secret = 3;
+ string agentId = 4;
+ string agentPassword = 5;
+ string client_id = 6;
+ string grant_type = 7;
+ string refresh_token = 8;
+}
+
+message EndSessionRequest {
+ string client_id = 1;
+ org.apache.custos.core.identity.api.EndSessionRequest body = 2;
+}
\ No newline at end of file
diff --git a/core/src/main/proto/TenantManagement.proto b/core/src/main/proto/TenantManagement.proto
new file mode 100644
index 000000000..e2ebae37a
--- /dev/null
+++ b/core/src/main/proto/TenantManagement.proto
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+package org.apache.custos.core.tenant.management.api;
+
+import "TenantProfile.proto";
+
+
+message CreateTenantResponse {
+ string client_id = 1;
+ string client_secret = 2;
+ bool is_activated = 3;
+ double client_id_issued_at = 4;
+ double client_secret_expires_at = 5;
+ string registration_client_uri = 6;
+ string token_endpoint_auth_method = 17;
+ string msg = 7;
+}
+
+message GetTenantResponse {
+ string client_id = 1;
+ string client_name = 2;
+ string requester_email = 3;
+ string admin_first_name = 4;
+ string admin_last_name = 5;
+ string admin_email = 6;
+ repeated string contacts = 7;
+ repeated string redirect_uris = 8;
+ repeated string grant_types = 9;
+ double client_id_issued_at = 10;
+ string client_uri = 11;
+ string scope = 12;
+ string domain = 13;
+ string comment = 14;
+ string logo_uri = 15;
+ string application_type = 16;
+ string jwks_uri = 17;
+ string example_extension_parameter = 18;
+ string tos_uri = 19;
+ string policy_uri = 20;
+ map<string, string> jwks = 21;
+ string software_id = 22;
+ string software_version = 23;
+ string admin_username = 24;
+}
+
+
+message GetTenantRequest {
+ string client_id = 1;
+ int64 tenant_id = 2;
+ org.apache.custos.core.tenant.profile.api.Tenant tenant = 4;
+ Credentials credentials = 5;
+}
+
+
+message Credentials {
+ string iam_client_id = 1;
+ string iam_client_secret = 2;
+ string ci_logon_client_id = 3;
+ string ci_logon_client_secret = 4;
+ string custos_client_id = 5;
+ string custos_client_secret = 6;
+ double custos_client_id_issued_at = 7;
+ double custos_client_secret_expired_at = 8;
+}
+
+message UpdateTenantRequest {
+ string client_id = 1;
+ int64 tenant_id = 2;
+ Credentials credentials = 3;
+ org.apache.custos.core.tenant.profile.api.Tenant body = 4;
+}
+
+message DeleteTenantRequest {
+ string client_id = 1;
+ int64 tenant_id = 2;
+ Credentials credentials = 3;
+ org.apache.custos.core.tenant.profile.api.Tenant body = 4;
+}
+
+message GetCredentialsRequest {
+ int64 tenant_id = 1;
+}
+
+message GetCredentialsResponse {
+ string iam_client_id = 1;
+ string iam_client_secret = 2;
+ string ci_logon_client_id = 3;
+ string ci_logon_client_secret = 4;
+}
+
+message TenantValidationRequest {
+ string client_id = 1;
+ string client_sec = 2;
+}
diff --git a/core/src/main/proto/TenantProfile.proto b/core/src/main/proto/TenantProfile.proto
new file mode 100644
index 000000000..413a1bfc9
--- /dev/null
+++ b/core/src/main/proto/TenantProfile.proto
@@ -0,0 +1,162 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+package org.apache.custos.core.tenant.profile.api;
+
+
+message Tenant {
+ int64 tenant_id = 1;
+ string client_name = 2;
+ string requester_email = 4;
+ string admin_first_name = 5;
+ string admin_last_name = 6;
+ string admin_email = 7;
+ string admin_username = 8;
+ string admin_password = 9;
+ TenantStatus tenant_status = 10;
+ repeated string contacts = 11;
+ repeated string redirect_uris = 12;
+ string client_uri = 13;
+ string scope = 14;
+ string domain = 15;
+ string comment = 16;
+ string logo_uri = 17;
+ int64 parent_tenant_id = 18;
+ string application_type = 19;
+ string token_endpoint_auth_method = 20;
+ string jwks_uri = 21;
+ string example_extension_parameter = 22;
+ string tos_uri = 23;
+ string policy_uri = 24;
+ map<string, string> jwks = 25;
+ string software_id = 26;
+ string software_version = 27;
+ int64 refesh_token_lifetime = 28;
+ string client_id = 29;
+ string parent_client_id = 30;
+}
+
+enum TenantStatus {
+ UNKNOWN = 0;
+ REQUESTED = 1;
+ APPROVED = 2;
+ DENIED = 3;
+ CANCELLED = 4;
+ ACTIVE = 5;
+ DEACTIVATED = 6;
+}
+
+enum TenantType {
+ UNSPECIFIED = 0;
+ ADMIN = 1;
+}
+
+message TenantAttributeUpdateMetadata {
+ string updated_attribute = 1;
+ string updated_attributeValue = 2;
+ string updated_by = 3;
+ string updated_at = 4;
+}
+
+message TenantStatusUpdateMetadata {
+ TenantStatus updated_status = 1;
+ string updated_by = 2;
+ string updated_at = 3;
+}
+
+
+message AddTenantResponse {
+ int64 tenant_id = 1;
+}
+
+
+message UpdateTenantResponse {
+ Tenant tenant = 1;
+
+}
+
+message GetTenantRequest {
+ int64 tenant_id = 1;
+}
+
+message GetTenantResponse {
+ Tenant tenant = 1;
+}
+
+
+message GetAllTenantsResponse {
+ repeated Tenant tenant = 1;
+ int32 total_num_of_tenants =2;
+}
+
+message IsTenantExistRequest {
+ int64 tenant_id = 1;
+}
+
+message IsTenantExistResponse {
+ bool is_exist = 1;
+}
+
+message GetAllTenantsForUserRequest {
+ string requester_email = 1;
+}
+
+message GetAllTenantsForUserResponse {
+ repeated Tenant tenant = 1;
+}
+
+message UpdateStatusRequest {
+ string client_id = 1;
+ TenantStatus status = 2;
+ string updated_by = 3;
+ int64 tenant_id = 4;
+ bool super_tenant = 5;
+ string access_token = 6;
+}
+
+message UpdateStatusResponse {
+ int64 tenant_id = 1;
+ TenantStatus status = 2;
+}
+
+message GetAuditTrailRequest {
+ int64 tenant_id = 1;
+}
+
+message GetStatusUpdateAuditTrailResponse {
+ repeated TenantStatusUpdateMetadata metadata = 1;
+}
+
+message GetAttributeUpdateAuditTrailResponse {
+ repeated TenantAttributeUpdateMetadata metadata = 2;
+}
+
+message GetTenantsRequest {
+ int32 offset = 1;
+ int32 limit = 2;
+ int64 parent_id = 3;
+ TenantStatus status = 4;
+ string requester_email = 5;
+ string parent_client_id = 6;
+ TenantType type= 7;
+}
diff --git a/core/src/main/proto/UserManagement.proto b/core/src/main/proto/UserManagement.proto
new file mode 100644
index 000000000..94642c7c6
--- /dev/null
+++ b/core/src/main/proto/UserManagement.proto
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+package org.apache.custos.core.user.management.api;
+
+import "UserProfile.proto";
+import "IamAdmin.proto";
+
+
+message UserProfileRequest {
+ org.apache.custos.core.user.profile.api.UserProfile user_profile = 1;
+ string client_id = 2;
+ int64 tenant_id = 3;
+ string access_token = 4;
+ string client_secret = 5;
+ string performed_by = 6;
+ int32 limit = 7;
+ int32 offset = 8;
+}
+
+message GetUserRequest {
+ string username = 1;
+ org.apache.custos.core.iam.api.UserSearchRequest user_search_request = 2;
+}
+
+message GetUsersRequest {
+ int64 tenant_id = 1;
+ string email = 2;
+ string username = 3;
+ int32 offset = 4;
+ int32 limit = 5;
+ string search = 6;
+ string iam_client_id = 7;
+ string iam_client_secret = 8;
+}
+
+message ResetPassword {
+ int64 tenant_id = 1;
+ string access_token = 2;
+ string username = 3;
+ string password = 4;
+ string iam_client_id = 5;
+ string iam_client_secret = 6;
+}
+
+message ResetPasswordRequest {
+ ResetPassword password_metadata = 1;
+}
+
+message LinkUserProfileRequest {
+ string current_username = 1;
+ string previous_username = 2;
+ repeated string linking_attributes = 3;
+ int64 tenantId = 4;
+ string iam_client_id = 5;
+ string iam_client_secret = 6;
+ string access_token = 7;
+ string performed_by = 8;
+}
+
+message SynchronizeUserDBRequest {
+ int64 tenant_id = 2;
+ string client_id = 4;
+}
diff --git a/core/src/main/proto/UserProfile.proto b/core/src/main/proto/UserProfile.proto
new file mode 100644
index 000000000..6719a660a
--- /dev/null
+++ b/core/src/main/proto/UserProfile.proto
@@ -0,0 +1,171 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+package org.apache.custos.core.user.profile.api;
+
+
+enum UserStatus {
+ ACTIVE = 0;
+ CONFIRMED = 1;
+ APPROVED = 2;
+ DELETED = 3;
+ DUPLICATE = 4;
+ GRACE_PERIOD = 5;
+ INVITED = 6;
+ DENIED = 7;
+ PENDING = 8;
+ PENDING_APPROVAL = 9;
+ PENDING_CONFIRMATION = 10;
+ SUSPENDED = 11;
+ DECLINED = 12;
+ EXPIRED = 13;
+}
+
+enum DefaultGroupMembershipTypes {
+ OWNER = 0;
+ ADMIN = 1;
+ MEMBER = 2;
+}
+
+enum UserTypes {
+ END_USER = 0;
+ COMMUNITY = 1;
+}
+
+message UserProfile {
+ string username = 1;
+ string email = 2;
+ string first_name = 3;
+ string last_name = 4;
+ int64 created_at = 5;
+ UserStatus status = 6;
+ repeated UserAttribute attributes = 7;
+ repeated string client_roles = 8;
+ repeated string realm_roles = 9;
+ int64 last_modified_at = 10;
+ UserTypes type = 11;
+ string membership_type = 12;
+}
+
+message UserProfileRequest {
+ int64 tenantId = 1;
+ UserProfile profile = 2;
+ string performed_by = 3;
+ string client_id = 4;
+ int32 offset=5;
+ int32 limit=6;
+}
+
+message UserAttribute {
+ int64 id = 1;
+ string key = 2;
+ repeated string values = 3;
+}
+
+message GetAllUserProfilesResponse {
+ repeated UserProfile profiles = 1;
+}
+
+message GetUpdateAuditTrailRequest {
+ int64 tenantId = 1;
+ string username = 2;
+}
+
+message UserProfileAttributeUpdateMetadata {
+ string updated_attribute = 1;
+ string updated_attribute_value = 2;
+ string updated_by = 3;
+ string updated_at = 4;
+}
+
+message UserProfileStatusUpdateMetadata {
+ UserStatus updated_status = 1;
+ string updated_by = 2;
+ string updated_at = 3;
+}
+
+message GetUpdateAuditTrailResponse {
+ repeated UserProfileAttributeUpdateMetadata attribute_audit = 1;
+ repeated UserProfileStatusUpdateMetadata status_audit = 2;
+}
+
+message GroupRequest {
+ int64 tenant_id = 1;
+ Group group = 2;
+ string performed_by = 3;
+ string client_id = 4;
+ string membership_type = 5;
+ string id = 6;
+ string client_sec =7;
+ int32 offset =8;
+ int32 limit=9;
+}
+
+message GetAllGroupsResponse {
+ repeated Group groups = 1;
+}
+
+message Group {
+ string id = 1;
+ string name = 2;
+ repeated string realm_roles = 3;
+ repeated string client_roles = 4;
+ string parent_id = 5;
+ int64 created_time = 6;
+ int64 last_modified_time = 7;
+ repeated GroupAttribute attributes = 8;
+ string description = 9;
+ string owner_id = 10;
+}
+
+message GroupAttribute {
+ int64 id = 1;
+ string key = 2;
+ repeated string value = 3;
+}
+
+message GroupMembership {
+ int64 tenant_id = 1;
+ string group_id = 2;
+ string username = 3;
+ string type = 4;
+ string clientId = 5;
+ string clientSec = 6;
+}
+
+message GroupToGroupMembership {
+ int64 tenant_id = 1;
+ string parent_id = 2;
+ string child_id = 3;
+ string client_id = 4;
+}
+
+message Status {
+ bool status = 1;
+}
+
+message UserGroupMembershipTypeRequest {
+ string type = 1;
+ int64 tenant_id = 2;
+ string client_id = 3;
+}
diff --git a/custos-core/pom.xml b/custos-core/pom.xml
deleted file mode 100644
index 3621df60f..000000000
--- a/custos-core/pom.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one
- ~ or more contributor license agreements. See the NOTICE file
- ~ distributed with this work for additional information
- ~ regarding copyright ownership. The ASF licenses this file
- ~ to you under the Apache License, Version 2.0 (the
- ~ "License"); you may not use this file except in compliance
- ~ with the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing,
- ~ software distributed under the License is distributed on an
- ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- ~ KIND, either express or implied. See the License for the
- ~ specific language governing permissions and limitations
- ~ under the License.
- -->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <artifactId>custos</artifactId>
- <groupId>org.apache.custos</groupId>
- <version>1.1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <packaging>pom</packaging>
-
- <artifactId>custos-core</artifactId>
-
- <modules>
- <module>sharing-core-impl</module>
- </modules>
-
- <properties>
- <maven.compiler.source>17</maven.compiler.source>
- <maven.compiler.target>17</maven.compiler.target>
- </properties>
-
-</project>
\ No newline at end of file
diff --git a/custos-core/sharing-core-impl/pom.xml b/custos-core/sharing-core-impl/pom.xml
deleted file mode 100644
index 17db62bbd..000000000
--- a/custos-core/sharing-core-impl/pom.xml
+++ /dev/null
@@ -1,48 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <artifactId>custos-core</artifactId>
- <groupId>org.apache.custos</groupId>
- <version>1.1-SNAPSHOT</version>
- <relativePath>../pom.xml</relativePath>
- </parent>
- <modelVersion>4.0.0</modelVersion>
-
- <artifactId>sharing-core-impl</artifactId>
-
- <properties>
- <maven.compiler.source>17</maven.compiler.source>
- <maven.compiler.target>17</maven.compiler.target>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- <exclusions>
- <exclusion>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>io.grpc</groupId>
- <artifactId>grpc-protobuf</artifactId>
- <exclusions>
- <exclusion>
- <groupId>com.google.api.grpc</groupId>
- <artifactId>proto-google-common-protos</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>jakarta.persistence</groupId>
- <artifactId>jakarta.persistence-api</artifactId>
- <version>3.1.0</version>
- </dependency>
- </dependencies>
-
-</project>
diff --git a/custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/SharingAPI.java b/custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/SharingAPI.java
deleted file mode 100644
index 1323f2e61..000000000
--- a/custos-core/sharing-core-impl/src/main/java/org/apache/custos/sharing/core/SharingAPI.java
+++ /dev/null
@@ -1,287 +0,0 @@
-package org.apache.custos.sharing.core;
-
-import org.apache.custos.sharing.core.exceptions.CustosSharingException;
-
-import java.util.List;
-import java.util.Optional;
-
-/**
- * Custos Shraing API.All sharing implementations should implement
- */
-public interface SharingAPI {
-
- /**
- * Create an Entity Type
- *
- * @param entityType
- */
- public void createEntityType(String tenantId, EntityType entityType) throws CustosSharingException;
-
- /**
- * Update a given Entity Type
- *
- * @param entityType
- */
- public void updateEntityType(String tenantId, EntityType entityType) throws CustosSharingException;
-
- ;
-
- /**
- * Delete a given Entity
- *
- * @param tenantId
- * @param entityTypeId
- */
- public void deleteEntityType(String tenantId, String entityTypeId) throws CustosSharingException;
-
- ;
-
- /**
- * Get given Entity Type
- *
- * @param tenantId
- * @param entityTypeId
- * @return
- */
- public Optional<EntityType> getEntityType(String tenantId, String entityTypeId) throws CustosSharingException;
-
- ;
-
- /**
- * Get Entity Types
- *
- * @param tenantId
- * @return
- */
- public List<EntityType> getEntityTypes(String tenantId) throws CustosSharingException;
-
- ;
-
-
- /**
- * Create a given Permission Type
- *
- * @param permissionType
- */
- public void createPermissionType(PermissionType permissionType, String tenantId) throws CustosSharingException;
-
- ;
-
- /**
- * Update a given Permission Type
- *
- * @param permissionType
- */
- public void updatePermissionType(PermissionType permissionType, String tenantId) throws CustosSharingException;
-
- ;
-
- /**
- * Delete a given Permission Type
- *
- * @param tenantId
- * @param permissionTypeId
- */
- public void deletePermissionType(String tenantId, String permissionTypeId) throws CustosSharingException;
-
- ;
-
- /**
- * Get a permission Type
- *
- * @param tenantId
- * @param permissionTypeId
- * @return
- */
- public Optional<PermissionType> getPermissionType(String tenantId, String permissionTypeId) throws CustosSharingException;
-
- ;
-
- /**
- * Get all permission Types
- *
- * @param tenantId
- * @return
- */
- public List<PermissionType> getPermissionTypes(String tenantId) throws CustosSharingException;
-
- ;
-
-
- /**
- * Create an Entity
- *
- * @param entity
- */
- public void createEntity(Entity entity, String tenantId) throws CustosSharingException;
-
- ;
-
- /**
- * Update an given Entity
- *
- * @param entity
- */
- public void updateEntity(Entity entity, String tenantId) throws CustosSharingException;
-
- ;
-
- /**
- * Delete an given Entity
- *
- * @param tenantId
- * @param entityId
- */
- public void deleteEntity(String tenantId, String entityId) throws CustosSharingException;
-
- ;
-
- /**
- * Returns true is Entity is exist
- *
- * @param tenantId
- * @param entityId
- * @return
- */
- public boolean isEntityExists(String tenantId, String entityId) throws CustosSharingException;
-
- ;
-
- /**
- * Get Entity wit given ID
- *
- * @param tenantId
- * @param entityId
- * @return
- */
- public Optional<Entity> getEntity(String tenantId, String entityId) throws CustosSharingException;
-
- ;
-
- /**
- * Search entities according to search criteria
- *
- * @param tenantId
- * @param searchCriteriaList
- * @param associatingIdList
- * @param limit
- * @param offset
- * @param searchPermBottomUp
- * @return
- * @throws CustosSharingException
- */
- public List<Entity> searchEntities(String tenantId, List<SearchCriteria> searchCriteriaList, List<String> associatingIdList,
- int limit, int offset,
- boolean searchPermBottomUp)
- throws CustosSharingException;
-
- ;
-
- /**
- * Get list of shared users for given permission for given entityId
- *
- * @param tenantId
- * @param entityId
- * @param permissionTypeId
- * @return
- */
- public List<String> getListOfSharedUsers(String tenantId, String entityId, String permissionTypeId)
- throws CustosSharingException;
-
- ;
-
- /**
- * Get list of directly (DIRECT CASCADING, DIRECT NON CASCADING, INDIRECT CASCADING) shared users of given entity id for given permission type id.
- *
- * @param tenantId
- * @param entityId
- * @param permissionTypeId
- * @return
- */
- public List<String> getListOfDirectlySharedUsers(String tenantId, String entityId, String permissionTypeId)
- throws CustosSharingException;
-
- ;
-
-
- /**
- * Get list of directly (DIRECT CASCADING, DIRECT NON CASCADING)shared groups of given entity id for given permission type id.
- *
- * @param tenantId
- * @param entityId
- * @param permissionTypeId
- * @return
- */
- public List<String> getListOfSharedGroups(String tenantId, String entityId, String permissionTypeId)
- throws CustosSharingException;
-
- ;
-
- /**
- * Get list of directly shared groups
- *
- * @param tenantId
- * @param entityId
- * @param permissionTypeId
- * @return
- */
- public List<String> getListOfDirectlySharedGroups(String tenantId, String entityId, String permissionTypeId)
- throws CustosSharingException;
-
- ;
-
- /**
- * Revoke permissions of user for given Entity
- *
- * @param tenantId
- * @param entityId
- * @param permissionType
- * @param usersList
- * @return
- */
- public boolean revokePermission(String tenantId, String entityId, String permissionType, List<String> usersList)
- throws CustosSharingException;
-
- ;
-
- /**
- * Share Entity with given user or group
- * @param tenantId
- * @param entityId
- * @param permissionType
- * @param associatingIds
- * @param cascade
- * @param ownerType
- * @param sharedBy
- * @throws CustosSharingException
- */
- public void shareEntity(String tenantId, String entityId, String permissionType,
- List<String> associatingIds,boolean cascade,String ownerType, String sharedBy) throws CustosSharingException;
-
-
-
-
- public List<SharingMetadata> getAllDirectSharings(String tenantId) throws CustosSharingException;
-
-
-
-
- public List<SharingMetadata> getAllSharings(String tenantId, String entityId) throws CustosSharingException;
-
-
... 87693 lines suppressed ...