Compare commits

..

1 Commits

Author SHA1 Message Date
Andrei Isvoran
3d9fca1419 RED-7239 Add logs and remove id from SMTPConfiguration 2023-08-28 15:31:39 +03:00
145 changed files with 1460 additions and 7089 deletions

View File

@ -1,40 +0,0 @@
### Hot to run locally and test
1. Start docker compose from this dir
2. Start persistence-service with profile: dev
* this will create the tenant sync exchange
* startup might fail due to tenant-usermanagement not being up. but you need the tenant sync queue first)
3. Start tenant-user-management with profiles: dev, redaction, migration
* this will migrate the master DB and sync KC
* it will also send a message to persistence service to run the migration
* in case the message doesn't arrive - restart persistence and/or this service - the tenant migration in this service is idempotent
4. Persistence service should now queue 1869 files to layout-parser
5. Start layout-parser with profile: dev
6. Start redaction-service with profile: dev
7. Debug issues & repeat
8. UI is available at htpp://localhost:4200/ui -> login with manageradmin/OsloImWinter!23
9. To start clean. docker compose down and up again.
Useful info:
* This docker compose contains a dump from staging from ~2 weeks ago
* KC credentials are: admin / secretPasswordForAdmin1234
* To use different data you need a tenant-manager database dump from an environment of your choice
* this can be obtained via kubectl port forward like so: `kubectl -n <namespace> port-forward services/main-db-postgresql 5432`
* followed by a dump: `pg_dumpall -U tenantmanager -h 127.0.0.1 > main.sql`
* And a tenant database:
* this can be obtained via kubectl port forward like so: `kubectl -n <namespace> port-forward services/tenant-db-postgresql 5432`
* followed by a dump: `pg_dumpall -U tenantmanager -h 127.0.0.1 > tenant.sql`
* And a KC database:
* this can be obtained via kubectl port forward like so: `kubectl -n <namespace> port-forward services/keycloak-postgresql 5432`
* followed by a dump: `pg_dumpall -U tenantmanager -h 127.0.0.1 > tenant.sql`
* You can now use the migration/utils/database Dockerfile to create a fat DB image with the data ( replace data.sql with your dump and tag accordingly)
* For a minio dump you need a similar command ( port fwd sometimes crashes sine clone command uses a lot of connections ):
* open port forward `while true; do kubectl -n redaction-staging port-forward statefulset/redaction-staging-minio 9000 --request-timeout=10m; done`
* Install mc minio command line utility
* create an alias `mc alias set <mirror_name> http://localhost:9000 minioadminuser minioadminpassword`
* run: `while true; do mc mirror <mirror_name>/<bucket_name> ./<bucket_name>; done`
* use migration/utils/minio/Dockerfile to create an image -> you need to copy it to where the export is.
* After you have the images, replace the images in compose with the ones you want

View File

@ -1,86 +0,0 @@
version: '3.9'
services:
tenant-database:
pull_policy: always
image: nexus.knecon.com:5001/migration/redtenant-db-staging-multi-arch
ports:
- 15432:5432
environment:
- POSTGRES_PASSWORD=r3dact3d
- POSTGRES_USER=tenant
- POSTGRES_DB=red-tenant
main-database:
image: nexus.knecon.com:5001/migration/tenantmanager-db-staging-multi-arch
pull_policy: always
ports:
- 25432:5432
environment:
- POSTGRES_PASSWORD=r3dact3d
- POSTGRES_USER=tenantmanager
- POSTGRES_DB=tenantmanager
keycloak-database:
image: nexus.knecon.com:5001/migration/keycloak-db-multi-arch
pull_policy: always
ports:
- 35432:5432
environment:
- POSTGRES_PASSWORD=some-password
- POSTGRES_USER=bn_keycloak
- POSTGRES_DB=bitnami_keycloak
keycloak:
command: ['start']
volumes:
- /tmp/export:/opt/export
depends_on:
- "keycloak-database"
image: quay.io/keycloak/keycloak:20.0.1
environment:
JAVA_OPTS_APPEND: -Dkeycloak.profile.feature.upload_scripts=enabled
KC_HOSTNAME: localhost
KC_HTTP_ENABLED: true
KC_HOSTNAME_STRICT_HTTPS: false
KC_DB: postgres
KC_DB_URL: jdbc:postgresql://keycloak-database:5432/bitnami_keycloak
KC_DB_USERNAME: bn_keycloak
KC_DB_PASSWORD: some-password
ports:
- "8080:8080"
redis:
image: redis
ports:
- "6379:6379"
rabbitmq:
image: 'rabbitmq:3.9-alpine'
environment:
- RABBITMQ_DEFAULT_USER=user
- RABBITMQ_DEFAULT_PASS=rabbitmq
ports:
- 5672:5672
- 15672:15672
minio:
pull_policy: always
image: nexus.knecon.com:5001/migration/minio-staging-multi-arch
ports:
- "9001:9001"
- "9000:9000"
adminer:
image: adminer:latest
ports:
- "58080:8080"
ui:
pull_policy: always
image: nexus.knecon.com:5001/migration/test-ui-csp
environment:
API_URL: http://localhost:4200
APP_NAME: Local
FRONTEND_APP_VERSION: 42
OAUTH_URL: http://localhost:8080
OAUTH_CLIENT_ID: redaction
BASE_TRANSLATIONS_DIRECTORY: /assets/i18n/redact/
THEME: redact
ports:
- "4200:8080"
# pg_dump bitnami_keycloak -U bn_keycloak -h 127.0.0.1 -p 35432 > data.sql
# pg_dump tenantmanager -U tenantmanager -h 127.0.0.1 -p 25432 > data.sql
# pg_dump red-tenant -U tenant -h 127.0.0.1 -p 15432 > data.sql

View File

@ -1,2 +0,0 @@
FROM postgres:16.0
COPY data.sql /docker-entrypoint-initdb.d/

View File

@ -1,16 +0,0 @@
FROM docker.io/minio/minio:latest
COPY ./redaction /tmp/redaction
COPY --from=docker.io/minio/mc:latest /usr/bin/mc /usr/bin/mc
RUN mkdir /buckets
RUN minio server /buckets & \
server_pid=$!; \
until mc alias set local http://localhost:9000 minioadmin minioadmin; do \
sleep 1; \
done; \
mc mb local/redaction; \
mc mirror /tmp/redaction local/redaction; \
kill $server_pid
RUN rm -Rf /tmp/redaction
CMD ["minio", "server", "/buckets", "--address", ":9000", "--console-address", ":9001"]

View File

@ -2,7 +2,7 @@ version: '2'
services:
keycloak:
image: quay.io/keycloak/keycloak:latest
image: quay.io/keycloak/keycloak:20.0
command: start-dev
environment:
KEYCLOAK_ADMIN: admin
@ -24,7 +24,7 @@ services:
POSTGRES_PASSWORD: fforesight
POSTGRES_DB: master
rabbitmq:
image: 'rabbitmq:3.9-management-alpine'
image: 'rabbitmq:3.9-alpine'
mem_limit: 500m
environment:
- RABBITMQ_DEFAULT_USER=user

View File

@ -1,21 +0,0 @@
# Tenant User Management Micro-Service: tenant-user-management
## Introduction
The tenant-user-management micro-service profiles with storing and providing everything about the tenant environment. It makes use of tools like Spring Boot 3, Keycloak, Microsoft Azure and AWS S3 to keep your data consistent and secure according to the latest standards.
### Key features in the Tenant User Management Service
* **Tenant Management:**
This service gives you the option to do CRUD operations to manage your tenants.
You can also select between different storage platforms to store your tenants.
Some general configurations complements the settings options.
* **User Administration:**
Another feature is the handling of your users. You can manage the profiles, activate/deactivate them and give roles as you require.
If you wish you can administrate the users for each tenant separately.
Or just give a user the needed preferences.
* **SMTP configuration:**
Further you can adjust your SMTP settings and set properties as you aimed best for your company.

View File

@ -2,20 +2,15 @@ import org.springframework.boot.gradle.tasks.bundling.BootBuildImage
plugins {
java
id("org.springframework.boot") version "3.1.5"
id("org.springframework.boot") version "3.0.6"
id("io.spring.dependency-management") version "1.1.0"
id("org.sonarqube") version "4.0.0.2929"
id("io.freefair.lombok") version "8.4"
pmd
`maven-publish`
checkstyle
jacoco
}
pmd {
isConsoleOutput = true
}
configurations {
compileOnly {
extendsFrom(configurations.annotationProcessor.get())
@ -39,8 +34,8 @@ publishing {
maven {
url = uri("https://nexus.knecon.com/repository/red-platform-releases/")
credentials {
username = providers.gradleProperty("mavenUser").getOrNull()
password = providers.gradleProperty("mavenPassword").getOrNull()
username = providers.gradleProperty("mavenUser").getOrNull();
password = providers.gradleProperty("mavenPassword").getOrNull();
}
}
}
@ -52,10 +47,10 @@ repositories {
mavenLocal()
mavenCentral()
maven {
url = uri("https://nexus.knecon.com/repository/gindev/")
url = uri("https://nexus.knecon.com/repository/gindev/");
credentials {
username = providers.gradleProperty("mavenUser").getOrNull()
password = providers.gradleProperty("mavenPassword").getOrNull()
username = providers.gradleProperty("mavenUser").getOrNull();
password = providers.gradleProperty("mavenPassword").getOrNull();
}
}
}
@ -86,30 +81,13 @@ tasks.named<BootBuildImage>("bootBuildImage") {
}
configurations {
all {
exclude(group = "commons-logging", module = "commons-logging")
exclude(group = "org.springframework.boot", module = "spring-boot-starter-log4j2")
exclude(group = "com.iqser.red.commons", module = "logging-commons")
}
}
val persistenceServiceVersion = "2.589.1-RED10196.2"
dependencies {
implementation("com.iqser.red.service:persistence-service-internal-api-v1:${persistenceServiceVersion}")
implementation("com.knecon.fforesight:database-tenant-commons:0.28.0-RED10196.0")
implementation("com.knecon.fforesight:keycloak-commons:0.28.0")
implementation("com.knecon.fforesight:swagger-commons:0.7.0")
implementation("com.knecon.fforesight:tracing-commons:0.5.0")
implementation("com.knecon.fforesight:lifecycle-commons:0.6.0")
implementation("net.logstash.logback:logstash-logback-encoder:7.4")
implementation("ch.qos.logback:logback-classic")
implementation("com.knecon.fforesight:keycloak-commons:0.18.0")
implementation("com.knecon.fforesight:swagger-commons:0.5.0")
implementation("org.postgresql:postgresql:42.5.4")
implementation("com.google.guava:guava:33.0.0-jre")
implementation("org.liquibase:liquibase-core:4.20.0")
implementation("org.keycloak:keycloak-admin-client:23.0.6")
implementation("com.google.guava:guava:31.1-jre")
implementation("org.liquibase:liquibase-core:4.17.2")
implementation("org.keycloak:keycloak-admin-client:21.0.1")
implementation("org.springframework.boot:spring-boot-starter-amqp")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.retry:spring-retry")
@ -118,27 +96,29 @@ dependencies {
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
implementation("org.apache.commons:commons-lang3:3.12.0")
implementation("commons-validator:commons-validator:1.8.0")
implementation("commons-validator:commons-validator:1.7")
implementation("org.springframework.boot:spring-boot-configuration-processor")
implementation("com.iqser.red.commons:storage-commons:2.45.0")
implementation("jakarta.mail:jakarta.mail-api:2.1.2")
implementation("org.eclipse.angus:angus-mail:2.0.2")
implementation("com.iqser.red.commons:storage-commons:2.22.0")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.cloud:spring-cloud-starter-openfeign")
testImplementation("org.projectlombok:lombok")
compileOnly("org.projectlombok:lombok")
developmentOnly("org.springframework.boot:spring-boot-devtools")
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
annotationProcessor("org.projectlombok:lombok")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.amqp:spring-rabbit-test")
testImplementation("org.testcontainers:postgresql:1.19.7")
testImplementation("org.testcontainers:testcontainers:1.19.7")
testImplementation("org.testcontainers:junit-jupiter:1.19.7")
testImplementation("com.github.dasniko:testcontainers-keycloak:3.2.0")
testImplementation("org.testcontainers:postgresql:1.18.3")
testImplementation("com.github.dasniko:testcontainers-keycloak:2.5.0")
testImplementation("org.testcontainers:testcontainers:1.18.3")
testImplementation("org.testcontainers:junit-jupiter:1.18.3")
testAnnotationProcessor("org.projectlombok:lombok")
}
extra["springCloudVersion"] = "2022.0.4"
extra["testcontainersVersion"] = "1.19.7"
extra["springCloudVersion"] = "2022.0.2"
extra["testcontainersVersion"] = "1.17.6"
group = "com.knecon.fforesight"

View File

@ -1,19 +1,15 @@
<?xml version="1.0"?>
<ruleset name="Custom ruleset"
<ruleset name="Custom Rules"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
<description>
Knecon ruleset checks the code for bad stuff
</description>
<description>Knecon main pmd rules</description>
<rule ref="category/java/errorprone.xml">
<exclude name="DataflowAnomalyAnalysis"/>
<exclude name="MissingSerialVersionUID"/>
<exclude name="AvoidLiteralsInIfCondition"/>
<exclude name="AvoidDuplicateLiterals"/>
<exclude name="NullAssignment"/>
<exclude name="AssignmentInOperand"/>
<exclude name="AvoidLiteralsInIfCondition"/>
</rule>
</ruleset>

View File

@ -1,22 +1,17 @@
<?xml version="1.0"?>
<ruleset name="Custom ruleset"
<ruleset name="Custom Rules"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
<description>
Knecon test ruleset checks the code for bad stuff
</description>
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
<description>Knecon test pmd rules</description>
<rule ref="category/java/errorprone.xml">
<exclude name="DataflowAnomalyAnalysis"/>
<exclude name="MissingSerialVersionUID"/>
<exclude name="AvoidLiteralsInIfCondition"/>
<exclude name="NonSerializableClass"/>
<exclude name="AvoidDuplicateLiterals"/>
<exclude name="NullAssignment"/>
<exclude name="AssignmentInOperand"/>
<exclude name="AvoidLiteralsInIfCondition"/>
<exclude name="TestClassWithoutTestCases"/>
<exclude name="BeanMembersShouldSerialize"/>
</rule>
</ruleset>

View File

@ -1,8 +0,0 @@
#!/bin/bash
dir=${PWD##*/}
gradle assemble
buildNumber=${1:-1}
gradle bootBuildImage --cleanCache --publishImage -PbuildbootDockerHostNetwork=true -Pversion=$USER-$buildNumber
echo "nexus.knecon.com:5001/ff/${dir}:$USER-$buildNumber"

View File

@ -4,26 +4,18 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import com.knecon.fforesight.keycloakcommons.DefaultKeyCloakCommonsAutoConfiguration;
import com.knecon.fforesight.lifecyclecommons.LifecycleAutoconfiguration;
import com.knecon.fforesight.swaggercommons.SpringDocAutoConfiguration;
import com.knecon.fforesight.tenantcommons.MultiTenancyAutoConfiguration;
import com.knecon.fforesight.tenantusermanagement.client.LicenseClient;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@ImportAutoConfiguration({MultiTenancyAutoConfiguration.class, LiquibaseAutoConfiguration.class, DefaultKeyCloakCommonsAutoConfiguration.class, SpringDocAutoConfiguration.class, LifecycleAutoconfiguration.class})
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class, CassandraAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@EnableAspectJAutoProxy
@EnableFeignClients(basePackageClasses = LicenseClient.class)
@ImportAutoConfiguration({MultiTenancyAutoConfiguration.class, LiquibaseAutoConfiguration.class, DefaultKeyCloakCommonsAutoConfiguration.class, SpringDocAutoConfiguration.class})
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class, CassandraAutoConfiguration.class,})
public class TenantUserManagementServiceApplication {
/**

View File

@ -5,6 +5,7 @@ import org.springframework.http.MediaType;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ -22,15 +23,15 @@ public interface GeneralSettingsResource {
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
@GetMapping(value = API_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Returns the current general configuration")
@Operation(summary = "Returns the current general Configuration.")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK.")})
GeneralConfigurationModel getGeneralConfigurations();
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@PostMapping(value = API_PATH, consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Write general configuration to KeyCloak")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "General configuration updated successful."), @ApiResponse(responseCode = "400", description = "General configuration update failed.")})
@Operation(summary = "Write General Configurations to KeyCloak")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "General Configuration updated successful."), @ApiResponse(responseCode = "400", description = "General Configuration update failed.")})
void updateGeneralConfigurations(@RequestBody GeneralConfigurationModel generalConfigurationModel);
}

View File

@ -1,86 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.api.external;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderList;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderModel;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderRequest;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderWithDescriptorRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.web.bind.annotation.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
@Tag(name = "Identity provider configuration endpoints", description = "Provides operations related to the identity providers")
@ApiResponses(value = {@ApiResponse(responseCode = "429", description = "Too many requests."), @ApiResponse(responseCode = "403", description = "Forbidden")})
public interface IdentityProviderConfigurationResource {
String API_PATH = "/configuration/identity-providers";
String IDENTITY_PROVIDER_ALIAS_PARAM = "providerAlias";
String IDENTITY_PROVIDER_ALIAS_PATH_PARAM = "/{" + IDENTITY_PROVIDER_ALIAS_PARAM + "}";
String IMPORT_SUB_PATH = "/import";
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
@GetMapping(value = API_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Gets all existing identity providers.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
IdentityProviderList getIdentityProviders();
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
@GetMapping(value = API_PATH + IDENTITY_PROVIDER_ALIAS_PATH_PARAM, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Gets an existing identity provider.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "404", description = "Not found")})
IdentityProviderModel getIdentityProvider(@Parameter(name = IDENTITY_PROVIDER_ALIAS_PARAM, description = "The alias of the identity provider to retrieve.", required = true) @PathVariable(IDENTITY_PROVIDER_ALIAS_PARAM) String identityProviderAlias);
@ResponseStatus(value = HttpStatus.CREATED)
@ResponseBody
@PostMapping(value = API_PATH, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Creates a new identity provider", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Successfully created the identity provider"), @ApiResponse(responseCode = "400", description = "Malformed request parameters or body"), @ApiResponse(responseCode = "409", description = "Duplicate")})
ResponseEntity<IdentityProviderModel> createIdentityProvider(@Valid @io.swagger.v3.oas.annotations.parameters.RequestBody @RequestBody IdentityProviderRequest identityProvider);
@ResponseStatus(value = HttpStatus.CREATED)
@ResponseBody
@PostMapping(value = API_PATH + IMPORT_SUB_PATH, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Creates a new identity provider", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Successfully created the identity provider"), @ApiResponse(responseCode = "400", description = "Malformed request parameters or body"), @ApiResponse(responseCode = "409", description = "Duplicate")})
ResponseEntity<IdentityProviderModel> createIdentityProviderFromDescriptor(@Valid @io.swagger.v3.oas.annotations.parameters.RequestBody @RequestBody IdentityProviderWithDescriptorRequest identityProvider);
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
@PutMapping(value = API_PATH + IDENTITY_PROVIDER_ALIAS_PATH_PARAM, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Updates an existing identity provider", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Successfully updated the identity provider"), @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "400", description = "Malformed request parameters or body")})
ResponseEntity<IdentityProviderModel> updateIdentityProvider(@Parameter(name = IDENTITY_PROVIDER_ALIAS_PARAM, description = "The alias of the identity provider to retrieve.", required = true) @PathVariable(IDENTITY_PROVIDER_ALIAS_PARAM) String identityProviderAlias,
@Valid @io.swagger.v3.oas.annotations.parameters.RequestBody @RequestBody IdentityProviderRequest identityProvider);
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@DeleteMapping(value = API_PATH + IDENTITY_PROVIDER_ALIAS_PATH_PARAM)
@Operation(summary = "Deletes an existing identity provider.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "Successfully deleted the identity provider."), @ApiResponse(responseCode = "404", description = "Not found")})
void deleteIdentityProvider(@Parameter(name = IDENTITY_PROVIDER_ALIAS_PARAM, description = "The alias of the identity provider to retrieve.", required = true) @PathVariable(IDENTITY_PROVIDER_ALIAS_PARAM) String identityProviderAlias);
}

View File

@ -6,12 +6,11 @@ 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.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.knecon.fforesight.tenantusermanagement.model.SMTPConfiguration;
import com.knecon.fforesight.tenantusermanagement.model.SMTPResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
@ -23,10 +22,11 @@ public interface SMTPConfigurationResource {
String TEST_PATH = "/test";
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
@GetMapping(value = SMTP_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Returns the current SMTP configuration.")
@Operation(summary = "Returns the current SMTP Configuration.")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK."), @ApiResponse(responseCode = "404", description = "SMTP not configured.")})
SMTPConfiguration getCurrentSMTPConfiguration();
@ -34,22 +34,21 @@ public interface SMTPConfigurationResource {
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@PostMapping(value = SMTP_PATH, consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Write SMTP Settings to KeyCloak")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "SMTP configuration updated successful."), @ApiResponse(responseCode = "400", description = "SMTP update failed.")})
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "SMTP Configuration updated successful."), @ApiResponse(responseCode = "400", description = "SMTP update failed.")})
void updateSMTPConfiguration(@RequestBody SMTPConfiguration smtpConfigurationModel);
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
@PostMapping(value = SMTP_PATH + TEST_PATH, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@PostMapping(value = SMTP_PATH + TEST_PATH, consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Test SMTP Settings to KeyCloak")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "SMTP configuration is valid."), @ApiResponse(responseCode = "400", description = "SMTP test failed.")})
SMTPResponse testSMTPConfiguration(@RequestBody SMTPConfiguration smtpConfigurationModel);
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "SMTP Configuration is valid."), @ApiResponse(responseCode = "400", description = "SMTP test failed.")})
void testSMTPConfiguration(@RequestBody SMTPConfiguration smtpConfigurationModel);
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@DeleteMapping(value = SMTP_PATH)
@Operation(summary = "Deletes SMTP settings on KeyCloak")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "SMTP configuration has been deleted."), @ApiResponse(responseCode = "400", description = "Failed to delete SMTP configuration.")})
@Operation(summary = "Clear SMTP Settings to KeyCloak")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "SMTP Configuration has been cleared."), @ApiResponse(responseCode = "400", description = "Failed to clear SMTP Configuration.")})
void clearSMTPConfiguration();
}

View File

@ -4,21 +4,17 @@ import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.fasterxml.jackson.databind.JsonNode;
import com.knecon.fforesight.tenantcommons.model.TenantResponse;
import com.knecon.fforesight.tenantcommons.model.UpdateDetailsRequest;
import com.knecon.fforesight.tenantusermanagement.model.DeploymentKeyResponse;
import com.knecon.fforesight.tenantusermanagement.model.CreateTenantRequest;
import com.knecon.fforesight.tenantusermanagement.model.UpdateTenantRequest;
import com.knecon.fforesight.tenantusermanagement.model.SimpleTenantResponse;
import com.knecon.fforesight.tenantusermanagement.model.TenantRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
@ -27,48 +23,36 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses;
@ResponseStatus(value = HttpStatus.OK)
public interface TenantsResource {
String TENANTS_PATH = "/tenants";
String TENANT_ID_PARAM = "tenantId";
String TENANT_ID_PATH_PARAM = "/{" + TENANT_ID_PARAM + "}";
String TENANTS_TENANT_ID_PATH = TENANTS_PATH + TENANT_ID_PATH_PARAM;
@PostMapping(value = TENANTS_PATH, consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Create a new tenant", description = "None")
@PostMapping(value = "/tenants", consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Creates a new Tenant", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
void createTenant(@RequestBody CreateTenantRequest tenant);
void createTenant(@RequestBody TenantRequest tenant);
@ResponseBody
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@Operation(summary = "Deletes given tenant", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "OK"), @ApiResponse(responseCode = "403", description = "Forbidden access, you dont have rights to delete tenants"), @ApiResponse(responseCode = "405", description = "Operation is not allowed."), @ApiResponse(responseCode = "409", description = "Conflict while deleting tenant.")})
@DeleteMapping(value = TENANTS_TENANT_ID_PATH)
void deleteTenant(@PathVariable("tenantId") String tenantId);
@GetMapping(value = TENANTS_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Gets all existing tenants", description = "None")
@GetMapping(value = "/tenants", produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Gets all existing tenant", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
List<TenantResponse> getTenants();
@GetMapping(value = TENANTS_TENANT_ID_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Gets an existing tenant", description = "None")
@GetMapping(value = "/tenants/{tenantId}", produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Gets all existing tenant", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
TenantResponse getTenant(@PathVariable("tenantId") String tenantId);
@PutMapping(value = TENANTS_TENANT_ID_PATH, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@PutMapping(value = "/tenants/{tenantId}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Update existing tenant", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
TenantResponse updateTenant(@PathVariable("tenantId") String tenantId, @RequestBody UpdateTenantRequest tenantRequest);
TenantResponse updateTenant(@PathVariable("tenantId") String tenantId, @RequestBody TenantRequest tenantRequest);
@PostMapping(value = TENANTS_TENANT_ID_PATH + "/details", consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Update details", description = "None")
@GetMapping(value = "/tenants/simple", produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Gets all existing tenant in a simplified format", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
void updateDetails(@PathVariable("tenantId") String tenantId, @RequestBody UpdateDetailsRequest request);
List<SimpleTenantResponse> getSimpleTenants();
@GetMapping(value = "/deploymentKey" + TENANT_ID_PATH_PARAM, produces = MediaType.APPLICATION_JSON_VALUE)
@ -76,10 +60,4 @@ public interface TenantsResource {
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
DeploymentKeyResponse getDeploymentKey(@PathVariable(TENANT_ID_PARAM) String tenantId);
@PostMapping(value = TENANTS_TENANT_ID_PATH + "/sync", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Sync existing tenant", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
void syncTenant(@PathVariable("tenantId") String tenantId, @RequestBody JsonNode payload);
}

View File

@ -28,14 +28,14 @@ public interface UserPreferenceResource {
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
@GetMapping(value = PREFERENCES_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Gets user attributes", description = "None")
@Operation(summary = "Get User Attributes.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
Map<String, List<String>> getAllUserAttributes();
@ResponseStatus(HttpStatus.NO_CONTENT)
@PutMapping(value = PREFERENCES_PATH + KEY_PATH_VARIABLE, consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Store user attribute by key", description = "None")
@Operation(summary = "Store User Attribute by key.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "OK")})
void setAttribute(@PathVariable(KEY_PARAMETER_NAME) String key, @RequestBody List<String> values);
@ -43,7 +43,7 @@ public interface UserPreferenceResource {
@ResponseBody
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@DeleteMapping(value = PREFERENCES_PATH + KEY_PATH_VARIABLE)
@Operation(summary = "Delete user preferences by key", description = "None")
@Operation(summary = "Delete User Preferences by key.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "OK")})
void deleteAttribute(@PathVariable(KEY_PARAMETER_NAME) String key);

View File

@ -10,6 +10,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ -44,31 +45,31 @@ public interface UserResource {
@ResponseBody
@Operation(summary = "Gets the users holding application-specific roles", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "400", description = "Invalid offset or limit specified.")})
@Operation(summary = "Gets the users who contain application-specific roles.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "400", description = "Invalid " + "offset or limit specified.")})
@GetMapping(value = RED_USER_REST_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
List<User> getApplicationSpecificUsers(@RequestParam(name = REFRESH_CACHE_PARAM, defaultValue = "false", required = false) boolean bypassCache);
@ResponseBody
@Operation(summary = "Gets all users in realm including role info", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "400", description = "Invalid offset or limit specified.")})
@Operation(summary = "Gets all the users in realm with information of roles.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "400", description = "Invalid " + "offset or limit specified.")})
@GetMapping(value = USER_REST_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
List<User> getAllUsers(@RequestParam(name = REFRESH_CACHE_PARAM, defaultValue = "false", required = false) boolean bypassCache);
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
@Operation(summary = "Update a user profile", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "OK"), @ApiResponse(responseCode = "400", description = "Failed to update profile, e-mail invalid"), @ApiResponse(responseCode = "404", description = "The userId cannot be found.")})
@Operation(summary = "Update your own user-profile.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "OK"), @ApiResponse(responseCode = "400", description = "Failed to update profile, e-mail cannot be empty")})
@PostMapping(value = UPDATE_USER_PROFILE_PATH + USER_ID_PATH_VARIABLE, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
User updateProfile(@PathVariable(USER_ID) String userId, @RequestBody UpdateProfileRequest updateProfileRequest);
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
@Operation(summary = "Update your user profile", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "OK"), @ApiResponse(responseCode = "400", description = "Failed to update profile, e-mail invalid")})
@Operation(summary = "Update your own user-profile.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "OK"), @ApiResponse(responseCode = "400", description = "Failed to update profile, e-mail cannot be empty")})
@PostMapping(value = UPDATE_MY_USER_PROFILE_PATH, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
User updateMyProfile(@RequestBody UpdateMyProfileRequest updateProfileRequest);
@ -90,36 +91,36 @@ public interface UserResource {
@ResponseBody
@Operation(summary = "Create a new user", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "400", description = "Invalid Data.")})
@Operation(summary = "Create a new user.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "400", description = "Invalid Data."), @ApiResponse(responseCode = "409", description = "User already exists.")})
@PostMapping(value = USER_REST_PATH, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
User createUser(@RequestBody CreateUserRequest user);
@ResponseBody
@Operation(summary = "Gets the user in realm including role info", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "404", description = "The userId cannot be found."), @ApiResponse(responseCode = "400", description = "The provided user id is empty or null.")})
@Operation(summary = "Gets the user in realm with information of roles.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "404", description = "The " + "userId can not be found."), @ApiResponse(responseCode = "400", description = "The provided user id is empty or " + "null.")})
@GetMapping(value = USER_REST_PATH + USER_ID_PATH_VARIABLE, produces = MediaType.APPLICATION_JSON_VALUE)
User getUserById(@PathVariable(USER_ID) String userId);
@ResponseStatus(value = HttpStatus.OK)
@Operation(summary = "Add roles to a user", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "No Content"), @ApiResponse(responseCode = "404", description = "The provided userId cannot be found."), @ApiResponse(responseCode = "400", description = "One ore more roles are not valid.")})
@Operation(summary = "Add a role to users", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "No Content"), @ApiResponse(responseCode = "404", description = "The provided userId can not be found."), @ApiResponse(responseCode = "400", description = "One ore more roles are not valid.")})
@PostMapping(value = USER_ROLE_REST_PATH, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
User setRoles(@PathVariable(USER_ID) String userId, @RequestBody Set<String> roles);
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@Operation(summary = "Reset a user's password", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "No Content"), @ApiResponse(responseCode = "404", description = "The provided userId cannot be found.")})
@ApiResponses(value = {@ApiResponse(responseCode = "204", description = "No Content"), @ApiResponse(responseCode = "404", description = "The provided userId can not be found.")})
@PostMapping(value = RESET_PASSWORD_PATH, consumes = MediaType.APPLICATION_JSON_VALUE)
void resetPassword(@PathVariable(USER_ID) String userId, @RequestBody ResetPasswordRequest resetPasswordRequest);
@ResponseBody
@Operation(summary = "Activate/deactivate a user profile", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "400", description = "Failed to activate/deactivate profile"), @ApiResponse(responseCode = "403", description = "Cannot activate/deactivate users with higher rank roles"), @ApiResponse(responseCode = "404", description = "The userId cannot be found.")})
@Operation(summary = "Activate/ deactivate a user-profile.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "400", description = "Failed to activate/deactivate profile")})
@PostMapping(value = ACTIVATE_USER_PROFILE_PATH + USER_ID_PATH_VARIABLE, produces = MediaType.APPLICATION_JSON_VALUE)
User activateProfile(@PathVariable(USER_ID) String userId, @RequestParam(IS_ACTIVE_PARAM) boolean isActive);

View File

@ -1,8 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.api.external.v2;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("${fforesight.tenant-user-management.base-path-v2:/api}")
public interface PublicResourceV2 {
}

View File

@ -1,38 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.api.external.v2;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.knecon.fforesight.tenantusermanagement.api.external.v2.model.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
public interface UserResourceV2 {
String USER_REST_PATH = "/users";
String USER_ID = "userId";
String USER_ID_PATH_VARIABLE = "/{" + USER_ID + "}";
String USERNAME_PARAM = "username";
@ResponseBody
@Operation(summary = "Get a list of users", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "400", description = "Invalid offset or limit specified.")})
@GetMapping(value = USER_REST_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
List<User> getUsers(@RequestParam(name = USERNAME_PARAM, required = false) String username);
@ResponseBody
@Operation(summary = "Retrieve a specific user by its identifier.", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "404", description = "The " + "userId cannot be found."), @ApiResponse(responseCode = "400", description = "The provided user id is empty or " + "null.")})
@GetMapping(value = USER_REST_PATH + USER_ID_PATH_VARIABLE, produces = MediaType.APPLICATION_JSON_VALUE)
User getUserById(@PathVariable(USER_ID) String userId);
}

View File

@ -1,29 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.api.external.v2.model;
import java.util.Set;
import java.util.TreeSet;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = "id")
public class User {
private String id;
private String username;
private String email;
private String firstName;
private String lastName;
private boolean active;
@Builder.Default
private Set<String> roles = new TreeSet<>();
}

View File

@ -1,18 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.api.external.v2.model;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserList {
private List<User> users = new ArrayList<>();
}

View File

@ -11,13 +11,11 @@ import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.fasterxml.jackson.databind.JsonNode;
import com.knecon.fforesight.tenantcommons.TenantApplicationType;
import com.knecon.fforesight.tenantcommons.model.TenantResponse;
import com.knecon.fforesight.tenantcommons.model.UpdateDetailsRequest;
import com.knecon.fforesight.tenantusermanagement.model.DeploymentKeyResponse;
import com.knecon.fforesight.tenantusermanagement.model.CreateTenantRequest;
import com.knecon.fforesight.tenantusermanagement.model.UpdateTenantRequest;
import com.knecon.fforesight.tenantusermanagement.model.SimpleTenantResponse;
import com.knecon.fforesight.tenantusermanagement.model.TenantRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
@ -39,25 +37,30 @@ public interface InternalTenantsResource {
@PostMapping(value = "/tenants", consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Creates a new Tenant", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
TenantResponse createTenant(@RequestBody CreateTenantRequest tenant);
TenantResponse createTenant(@RequestBody TenantRequest tenant);
@GetMapping(value = "/tenants", produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Gets all existing tenants", description = "None")
@Operation(summary = "Gets all existing tenant", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
List<TenantResponse> getTenants();
@GetMapping(value = "/tenants/{tenantId}", produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Get the given tenant", description = "None")
@Operation(summary = "Gets all existing tenant", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
TenantResponse getTenant(@PathVariable("tenantId") String tenantId);
@PutMapping(value = "/tenants/{tenantId}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Update existing tenant", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
TenantResponse updateTenant(@PathVariable("tenantId") String tenantId, @RequestBody UpdateTenantRequest tenantRequest);
TenantResponse updateTenant(@PathVariable("tenantId") String tenantId, @RequestBody TenantRequest tenantRequest);
@GetMapping(value = "/tenants/simple", produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Gets all existing tenant in a simplified format", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
List<SimpleTenantResponse> getSimpleTenants();
@GetMapping(value = "/deploymentKey" + TENANT_ID_PATH_PARAM, produces = MediaType.APPLICATION_JSON_VALUE)
@ -65,16 +68,4 @@ public interface InternalTenantsResource {
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
DeploymentKeyResponse getDeploymentKey(@PathVariable(TENANT_ID_PARAM) String tenantId);
@PostMapping(value = "/tenants/{tenantId}/sync", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Sync existing tenant", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
void syncTenant(@PathVariable("tenantId") String tenantId, @RequestBody JsonNode payload);
@GetMapping(value = {"/tenants/{tenantId}/application-type"}, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Gets the application type of the given tenant", description = "None")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
TenantApplicationType getTenantApplicationType(@PathVariable("tenantId") String tenantId);
}

View File

@ -1,10 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.client;
import org.springframework.cloud.openfeign.FeignClient;
import com.iqser.red.service.persistence.service.v1.api.internal.resources.LicenseResource;
@FeignClient(name = "LicenseResource", url = "${persistence-service.url}")
public interface LicenseClient extends LicenseResource {
}

View File

@ -1,47 +1,25 @@
package com.knecon.fforesight.tenantusermanagement.controller;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.knecon.fforesight.tenantusermanagement.exception.ConflictException;
import com.knecon.fforesight.tenantusermanagement.model.ErrorMessage;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.NotFoundException;
@RestControllerAdvice
public class ControllerAdvice {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorMessage> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
var errorList = e.getFieldErrors();
String errorListAsString = errorList.stream().map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage()).collect(Collectors.joining(", "));
return new ResponseEntity<>(new ErrorMessage(String.format("You have empty/wrong formatted parameters: %s", errorListAsString)), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorMessage> handleNotFound(NotFoundException e) {
return new ResponseEntity<>(new ErrorMessage(e.getMessage()), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(ForbiddenException.class)
public ResponseEntity<ErrorMessage> handleForbiddenAccess(ForbiddenException e) {
return new ResponseEntity<>(new ErrorMessage(e.getMessage()), HttpStatus.FORBIDDEN);
return new ResponseEntity<>(new ErrorMessage(e.getMessage()), HttpStatus.BAD_REQUEST);
}
@ -51,42 +29,4 @@ public class ControllerAdvice {
return new ResponseEntity<>(new ErrorMessage(e.getReason()), e.getStatusCode());
}
@ExceptionHandler(BadRequestException.class)
public ResponseEntity<ErrorMessage> handleBadRequestException(BadRequestException e) {
return new ResponseEntity<>(new ErrorMessage(e.getMessage()), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<ErrorMessage> handleAccessDeniedException(AccessDeniedException e) {
return new ResponseEntity<>(new ErrorMessage(e.getMessage()), HttpStatus.FORBIDDEN);
}
@ExceptionHandler(ConflictException.class)
public ResponseEntity<ErrorMessage> handleConflictException(ConflictException e) {
return new ResponseEntity<>(new ErrorMessage(e.getMessage()), HttpStatus.CONFLICT);
}
@ExceptionHandler({HttpMessageNotReadableException.class})
public ResponseEntity<ErrorMessage> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
String errorMessage = e.getMessage();
var cause = e.getCause();
if (cause instanceof InvalidFormatException invalidFormatException) {
errorMessage = cause.getMessage();
Class<?> targetType = invalidFormatException.getTargetType();
if (targetType != null && targetType.isEnum()) {
errorMessage = String.format("Unsupported value for %s", targetType.getSimpleName());
}
}
return new ResponseEntity<>(new ErrorMessage(errorMessage), HttpStatus.BAD_REQUEST);
}
}

View File

@ -7,12 +7,10 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantusermanagement.api.external.GeneralSettingsResource;
import com.knecon.fforesight.tenantusermanagement.api.external.PublicResource;
import com.knecon.fforesight.tenantusermanagement.model.GeneralConfigurationModel;
import com.knecon.fforesight.tenantusermanagement.service.GeneralConfigurationService;
import com.knecon.fforesight.tenantusermanagement.service.TenantManagementService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -23,14 +21,13 @@ import lombok.extern.slf4j.Slf4j;
public class GeneralSettingsController implements GeneralSettingsResource, PublicResource {
private final GeneralConfigurationService generalConfigurationService;
private final TenantManagementService tenantManagementService;
@Override
@PreAuthorize("hasAuthority('" + READ_GENERAL_CONFIGURATION + "')")
public GeneralConfigurationModel getGeneralConfigurations() {
return generalConfigurationService.getGeneralConfigurations(tenantManagementService.getTenantApplicationType(TenantContext.getTenantId()));
return generalConfigurationService.getGeneralConfigurations();
}
@ -38,7 +35,7 @@ public class GeneralSettingsController implements GeneralSettingsResource, Publi
@PreAuthorize("hasAuthority('" + WRITE_GENERAL_CONFIGURATION + "')")
public void updateGeneralConfigurations(@RequestBody GeneralConfigurationModel generalConfigurationModel) {
generalConfigurationService.updateGeneralConfigurations(generalConfigurationModel, tenantManagementService.getTenantApplicationType(TenantContext.getTenantId()));
generalConfigurationService.updateGeneralConfigurations(generalConfigurationModel);
}
}

View File

@ -1,269 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.controller.external;
import static com.knecon.fforesight.tenantusermanagement.permissions.UserManagementPermissions.READ_IDENTITY_PROVIDER_CONFIGURATION;
import static com.knecon.fforesight.tenantusermanagement.permissions.UserManagementPermissions.WRITE_IDENTITY_PROVIDER_CONFIGURATION;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ResponseStatusException;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantusermanagement.api.external.IdentityProviderConfigurationResource;
import com.knecon.fforesight.tenantusermanagement.api.external.PublicResource;
import com.knecon.fforesight.tenantusermanagement.exception.ConflictException;
import com.knecon.fforesight.tenantusermanagement.exception.IdentityProviderExistsAlreadyException;
import com.knecon.fforesight.tenantusermanagement.exception.IdentityProviderNotFoundException;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderList;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderModel;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderRequest;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderWithDescriptorRequest;
import com.knecon.fforesight.tenantusermanagement.properties.TenantUserManagementProperties;
import com.knecon.fforesight.tenantusermanagement.service.KeyCloakAdminClientService;
import com.knecon.fforesight.tenantusermanagement.service.RealmService;
import com.knecon.fforesight.tenantusermanagement.utils.IdentityProviderMappingService;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.InternalServerErrorException;
import jakarta.ws.rs.core.Response;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequiredArgsConstructor
public class IdentityProviderConfigurationController implements IdentityProviderConfigurationResource, PublicResource {
private final RealmService realmService;
private final TenantUserManagementProperties tenantUserManagementProperties;
private final KeyCloakAdminClientService keyCloakAdminClientService;
@Override
@PreAuthorize("hasAuthority('" + READ_IDENTITY_PROVIDER_CONFIGURATION + "')")
public IdentityProviderList getIdentityProviders() {
return new IdentityProviderList(getRealmRepresentation().getIdentityProviders()
.stream()
.map(IdentityProviderMappingService::toModelFromRepresentation)
.toList());
}
@Override
@PreAuthorize("hasAuthority('" + READ_IDENTITY_PROVIDER_CONFIGURATION + "')")
public IdentityProviderModel getIdentityProvider(String identityProviderAlias) {
return IdentityProviderMappingService.toModelFromRepresentation(getIdentityProviderRepresentation(identityProviderAlias));
}
private IdentityProviderRepresentation getIdentityProviderRepresentation(String identityProviderAlias) {
return getRealmRepresentation().getIdentityProviders()
.stream()
.filter(identityProviderRepresentation -> identityProviderRepresentation.getAlias().equals(identityProviderAlias))
.findFirst()
.orElseThrow(() -> new IdentityProviderNotFoundException(identityProviderAlias));
}
@Override
@PreAuthorize("hasAuthority('" + WRITE_IDENTITY_PROVIDER_CONFIGURATION + "')")
public ResponseEntity<IdentityProviderModel> createIdentityProvider(IdentityProviderRequest identityProviderRequest) {
if (identityProviderRequest.getAlias() == null) {
throw new BadRequestException("Alias must not be null.");
}
if (identityProviderRequest.getDisplayName() == null || identityProviderRequest.getDisplayName().isEmpty()) {
identityProviderRequest.setDisplayName(identityProviderRequest.getAlias());
}
checkIfOtherIdpHasSameDisplayNameOnCreate(identityProviderRequest.getDisplayName());
IdentityProviderModel identityProviderModel = IdentityProviderMappingService.toModelFromRequest(identityProviderRequest);
return callKeyCloakIdentityProvidersCreateForModel(identityProviderModel);
}
@Override
@PreAuthorize("hasAuthority('" + WRITE_IDENTITY_PROVIDER_CONFIGURATION + "')")
public ResponseEntity<IdentityProviderModel> createIdentityProviderFromDescriptor(IdentityProviderWithDescriptorRequest identityProviderWithDescriptorRequest) {
if (identityProviderWithDescriptorRequest.getDisplayName() == null || identityProviderWithDescriptorRequest.getDisplayName().isEmpty()) {
identityProviderWithDescriptorRequest.setDisplayName(identityProviderWithDescriptorRequest.getAlias());
}
checkIfOtherIdpHasSameDisplayNameOnCreate(identityProviderWithDescriptorRequest.getDisplayName());
Map<String, Object> requestMap = new HashMap<>();
requestMap.put("providerId", identityProviderWithDescriptorRequest.getProviderId());
requestMap.put("fromUrl", identityProviderWithDescriptorRequest.getSamlEntityDescriptorURL());
try {
Map<String, String> configurationsMap = realmService.realm(getTenantId()).identityProviders().importFrom(requestMap);
if (configurationsMap == null || configurationsMap.isEmpty()) {
throw new BadRequestException("Could not set config from provided descriptor.");
}
configurationsMap.put("entityId", identityProviderWithDescriptorRequest.getEntityId());
IdentityProviderModel identityProviderModel = IdentityProviderMappingService.toModelFromDescriptorRequestAndConfig(identityProviderWithDescriptorRequest,
configurationsMap);
return callKeyCloakIdentityProvidersCreateForModel(identityProviderModel);
} catch (InternalServerErrorException internalServerErrorException) {
throw new BadRequestException("Provided descriptor is malformed.");
}
}
private ResponseEntity<IdentityProviderModel> callKeyCloakIdentityProvidersCreateForModel(IdentityProviderModel identityProviderModel) {
identityProviderModel.setSpecificDefaults();
try (Response response = realmService.realm(getTenantId()).identityProviders().create(IdentityProviderMappingService.toRepresentationFromModel(identityProviderModel))) {
var httpStatus = HttpStatus.valueOf(response.getStatus());
switch (httpStatus) {
case CREATED -> {
IdentityProviderModel createdIdentityProvider = getIdentityProvider(identityProviderModel.getAlias());
return new ResponseEntity<>(createdIdentityProvider, HttpStatus.valueOf(response.getStatus()));
}
case CONFLICT -> throw new IdentityProviderExistsAlreadyException(identityProviderModel.getAlias());
default -> throw new ResponseStatusException(httpStatus, extractKeycloakErrorMessageInfos(response.readEntity(String.class)));
}
}
}
@Override
@PreAuthorize("hasAuthority('" + WRITE_IDENTITY_PROVIDER_CONFIGURATION + "')")
public ResponseEntity<IdentityProviderModel> updateIdentityProvider(String identityProviderAlias, IdentityProviderRequest identityProviderRequest) {
identityProviderRequest.setAlias(identityProviderAlias);
getIdentityProviderRepresentation(identityProviderAlias);
checkIfOtherIdpHasSameDisplayNameOnUpdate(identityProviderAlias, identityProviderRequest.getDisplayName());
IdentityProviderModel identityProviderModel = IdentityProviderMappingService.toModelFromRequest(identityProviderRequest);
identityProviderModel.setSpecificDefaults();
var restTemplate = new RestTemplate();
var url = getKeycloakIdentityProviderInstancesUrl() + identityProviderRequest.getAlias();
var headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Bearer " + getToken());
HttpEntity<IdentityProviderModel> httpEntity = new HttpEntity<>(identityProviderModel, headers);
try {
ResponseEntity<?> response = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class);
var httpStatus = HttpStatus.valueOf(response.getStatusCode().value());
if (httpStatus == HttpStatus.NO_CONTENT) {
IdentityProviderModel createdIdentityProvider = getIdentityProvider(identityProviderRequest.getAlias());
return new ResponseEntity<>(createdIdentityProvider, HttpStatus.OK);
} else if (httpStatus.is4xxClientError()) {
throw new ResponseStatusException(httpStatus, "Bad request to keycloak API");
} else {
throw new ResponseStatusException(httpStatus, httpStatus.getReasonPhrase());
}
} catch (HttpClientErrorException e) {
throw new ResponseStatusException(e.getStatusCode(), extractKeycloakErrorMessageInfos(e.getMessage()));
}
}
@Override
@PreAuthorize("hasAuthority('" + WRITE_IDENTITY_PROVIDER_CONFIGURATION + "')")
public void deleteIdentityProvider(String identityProviderAlias) {
getIdentityProviderRepresentation(identityProviderAlias);
var restTemplate = new RestTemplate();
var url = getKeycloakIdentityProviderInstancesUrl() + identityProviderAlias;
var headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Bearer " + getToken());
HttpEntity<?> httpEntity = new HttpEntity<>(headers);
try {
restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);
} catch (HttpClientErrorException e) {
throw new ResponseStatusException(e.getStatusCode(), extractKeycloakErrorMessageInfos(e.getMessage()));
}
}
private void checkIfOtherIdpHasSameDisplayNameOnUpdate(String alias, String displayName) {
checkIfOtherIdpHasSameDisplayName(getIdentityProviders().getIdentityProviders()
.stream()
.filter(identityProviderModel -> !identityProviderModel.getAlias().equals(alias))
.toList(), displayName);
}
private void checkIfOtherIdpHasSameDisplayNameOnCreate(String displayName) {
checkIfOtherIdpHasSameDisplayName(getIdentityProviders().getIdentityProviders(), displayName);
}
private void checkIfOtherIdpHasSameDisplayName(List<IdentityProviderModel> identityProviderModelList, String displayName) {
if (identityProviderModelList.stream()
.anyMatch(idp -> idp.getDisplayName().isEmpty() ? idp.getAlias().equals(displayName) : idp.getDisplayName().equals(displayName))) {
throw new ConflictException("Identity provider with this display name already exists.");
}
}
private static String extractKeycloakErrorMessageInfos(String keyCloakErrorMessage) {
String errorMessageRegex = "\\{\"errorMessage\":\"(.*?)\"}";
Pattern pattern = Pattern.compile(errorMessageRegex);
Matcher matcher = pattern.matcher(keyCloakErrorMessage);
if (matcher.find()) {
return matcher.group(1);
}
return keyCloakErrorMessage;
}
private String getTenantId() {
return TenantContext.getTenantId();
}
private RealmRepresentation getRealmRepresentation() {
return realmService.realm(getTenantId()).toRepresentation();
}
private String getKeycloakIdentityProviderInstancesUrl() {
return tenantUserManagementProperties.getServerUrl() + "/admin/realms/" + getTenantId() + "/identity-provider/instances/";
}
private String getToken() {
return keyCloakAdminClientService.getAdminClient().tokenManager().getAccessToken().getToken();
}
}

View File

@ -6,25 +6,20 @@ import static com.knecon.fforesight.tenantusermanagement.permissions.UserManagem
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.knecon.fforesight.tenantcommons.EncryptionDecryptionService;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantusermanagement.api.external.PublicResource;
import com.knecon.fforesight.tenantusermanagement.api.external.SMTPConfigurationResource;
import com.knecon.fforesight.tenantusermanagement.model.SMTPConfiguration;
import com.knecon.fforesight.tenantusermanagement.model.SMTPResponse;
import com.knecon.fforesight.tenantusermanagement.service.EmailService;
import com.knecon.fforesight.tenantusermanagement.service.RealmService;
import com.knecon.fforesight.tenantusermanagement.service.SMTPService;
import jakarta.ws.rs.BadRequestException;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@ -32,16 +27,19 @@ import lombok.extern.slf4j.Slf4j;
@RequiredArgsConstructor
public class SMTPConfigurationController implements SMTPConfigurationResource, PublicResource {
private final static String SMTP_PASSWORD_KEY = "FFORESIGHT_SMTP_PASSWORD";
private final RealmService realmService;
private final EmailService emailService;
private final SMTPService smtpService;
private final ObjectMapper objectMapper;
private final EncryptionDecryptionService encryptionDecryptionService;
@Override
@PreAuthorize("hasAuthority('" + READ_SMTP_CONFIGURATION + "')")
public SMTPConfiguration getCurrentSMTPConfiguration() {
return smtpService.getSMTPConfiguration();
var realm = realmService.realm(TenantContext.getTenantId()).toRepresentation();
return objectMapper.convertValue(realm.getSmtpServer(), SMTPConfiguration.class);
}
@ -49,42 +47,52 @@ public class SMTPConfigurationController implements SMTPConfigurationResource, P
@PreAuthorize("hasAuthority('" + WRITE_SMTP_CONFIGURATION + "')")
public void updateSMTPConfiguration(@RequestBody SMTPConfiguration smtpConfigurationModel) {
if (!smtpService.canUpdateSMTPConfig()) {
throw new BadRequestException("Current license does not allow updating the SMTP configuration!");
var realmRepresentation = realmService.realm(TenantContext.getTenantId()).toRepresentation();
var propertiesMap = convertSMTPConfigurationModelToMap(smtpConfigurationModel);
realmRepresentation.setSmtpServer(propertiesMap);
if (!smtpConfigurationModel.getPassword().matches("\\**")) {
realmRepresentation.getAttributesOrEmpty().put(SMTP_PASSWORD_KEY, encryptionDecryptionService.encrypt(smtpConfigurationModel.getPassword()));
}
smtpService.updateSMTPConfiguration(smtpConfigurationModel);
realmService.realm(TenantContext.getTenantId()).update(realmRepresentation);
}
private Map<String, String> convertSMTPConfigurationModelToMap(SMTPConfiguration smtpConfigurationModel) {
Map<String, Object> propertiesMap = objectMapper.convertValue(smtpConfigurationModel, Map.class);
Map<String, String> stringPropertiesMap = new HashMap<>();
propertiesMap.forEach((key, value) -> {
if (value != null) {
stringPropertiesMap.put(key, value.toString());
} else {
stringPropertiesMap.put(key, "");
}
});
return stringPropertiesMap;
}
@SneakyThrows
@Override
@PreAuthorize("hasAuthority('" + WRITE_SMTP_CONFIGURATION + "')")
public SMTPResponse testSMTPConfiguration(@RequestBody SMTPConfiguration smtpConfiguration) {
public void testSMTPConfiguration(@RequestBody SMTPConfiguration smtpConfigurationModel) {
String targetEmail = realmService.getEmail(realmService.realm(TenantContext.getTenantId()));
boolean adminEmail = true;
if (StringUtils.isEmpty(targetEmail)) {
// will send e-mail to self in case targetEmail is not set
targetEmail = smtpConfiguration.getFrom();
adminEmail = false;
}
SMTPResponse.SMTPResponseBuilder smtpResponseBuilder = emailService.send(smtpService.convertSMTPConfigToMap(smtpConfiguration),
targetEmail,
"Redaction Test message",
"This is a test message");
SMTPResponse smtpResponse = smtpResponseBuilder.adminEmail(adminEmail).recipientEmail(targetEmail).build();
log.info("Test SMTP Configuration status: {}, reason: {}, recipient: {}", smtpResponse.getStatusCode(), smtpResponse.getReasonPhrase(), smtpResponse.getRecipientEmail());
return smtpResponse;
var propertiesMap = convertSMTPConfigurationModelToMap(smtpConfigurationModel);
var response = realmService.realm(TenantContext.getTenantId()).testSMTPConnection(propertiesMap);
log.info("Test SMTP email status {}", response.getStatus());
}
@Override
@PreAuthorize("hasAuthority('" + WRITE_SMTP_CONFIGURATION + "')")
public void clearSMTPConfiguration() {
smtpService.createDefaultSMTPConfiguration();
// also update in KC
var realmRepresentation = realmService.realm(TenantContext.getTenantId()).toRepresentation();
realmRepresentation.setSmtpServer(new HashMap<>());
realmRepresentation.getAttributesOrEmpty().remove(SMTP_PASSWORD_KEY);
realmService.realm(TenantContext.getTenantId()).update(realmRepresentation);
}

View File

@ -1,7 +1,6 @@
package com.knecon.fforesight.tenantusermanagement.controller.external;
import static com.knecon.fforesight.tenantusermanagement.permissions.UserManagementPermissions.CREATE_TENANT;
import static com.knecon.fforesight.tenantusermanagement.permissions.UserManagementPermissions.DELETE_TENANT;
import static com.knecon.fforesight.tenantusermanagement.permissions.UserManagementPermissions.DEPLOYMENT_INFO;
import static com.knecon.fforesight.tenantusermanagement.permissions.UserManagementPermissions.GET_TENANTS;
import static com.knecon.fforesight.tenantusermanagement.permissions.UserManagementPermissions.UPDATE_TENANT;
@ -16,14 +15,12 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import com.fasterxml.jackson.databind.JsonNode;
import com.knecon.fforesight.tenantcommons.model.TenantResponse;
import com.knecon.fforesight.tenantcommons.model.UpdateDetailsRequest;
import com.knecon.fforesight.tenantusermanagement.api.external.PublicResource;
import com.knecon.fforesight.tenantusermanagement.api.external.TenantsResource;
import com.knecon.fforesight.tenantusermanagement.model.DeploymentKeyResponse;
import com.knecon.fforesight.tenantusermanagement.model.CreateTenantRequest;
import com.knecon.fforesight.tenantusermanagement.model.UpdateTenantRequest;
import com.knecon.fforesight.tenantusermanagement.model.SimpleTenantResponse;
import com.knecon.fforesight.tenantusermanagement.model.TenantRequest;
import com.knecon.fforesight.tenantusermanagement.service.DeploymentKeyService;
import com.knecon.fforesight.tenantusermanagement.service.TenantManagementService;
@ -39,7 +36,7 @@ public class TenantsController implements TenantsResource, PublicResource {
@PreAuthorize("hasAuthority('" + CREATE_TENANT + "')")
public void createTenant(@Valid @RequestBody CreateTenantRequest tenantRequest) {
public void createTenant(@Valid @RequestBody TenantRequest tenantRequest) {
try {
tenantManagementService.createTenant(tenantRequest);
@ -48,21 +45,9 @@ public class TenantsController implements TenantsResource, PublicResource {
}
}
@PreAuthorize("hasAuthority('" + DELETE_TENANT + "')")
public void deleteTenant(String tenantId) {
try {
tenantManagementService.deleteTenant(tenantId);
} catch (IllegalArgumentException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage(), e);
}
}
@PreAuthorize("hasAuthority('" + GET_TENANTS + "')")
public List<TenantResponse> getTenants() {
List<TenantResponse> tenants = tenantManagementService.getTenants();
return tenants.stream().map(tenantManagementService::removePasswords).collect(Collectors.toList());
}
@ -76,33 +61,24 @@ public class TenantsController implements TenantsResource, PublicResource {
}
public List<SimpleTenantResponse> getSimpleTenants() {
return tenantManagementService.getTenants().stream().map(t -> new SimpleTenantResponse(t.getTenantId(), t.getDisplayName(), t.getGuid())).toList();
}
@PreAuthorize("hasAuthority('" + UPDATE_TENANT + "')")
public TenantResponse updateTenant(String tenantId, @RequestBody UpdateTenantRequest tenantRequest) {
public TenantResponse updateTenant(String tenantId,
@RequestBody TenantRequest tenantRequest) {
TenantResponse tenantResponse = tenantManagementService.updateTenant(tenantId, tenantRequest);
return tenantManagementService.removePasswords(tenantResponse);
}
@PreAuthorize("hasAuthority('" + UPDATE_TENANT + "')")
public void updateDetails(@PathVariable("tenantId") String tenantId, @RequestBody UpdateDetailsRequest request) {
tenantManagementService.updateDetails(tenantId, request);
}
@PreAuthorize("hasAuthority('" + DEPLOYMENT_INFO + "')")
public DeploymentKeyResponse getDeploymentKey(@PathVariable(TENANT_ID_PARAM) String tenantId) {
return new DeploymentKeyResponse(deploymentKeyService.getDeploymentKey(tenantId));
}
@Override
public void syncTenant(@PathVariable(TENANT_ID_PARAM) String tenantId, @RequestBody JsonNode payload) {
tenantManagementService.syncTenant(tenantId, payload);
}
}

View File

@ -1,6 +1,5 @@
package com.knecon.fforesight.tenantusermanagement.controller.external;
import static com.knecon.fforesight.tenantusermanagement.permissions.ApplicationRoles.KNECON_ROLE_FILTER;
import static com.knecon.fforesight.tenantusermanagement.permissions.UserManagementPermissions.READ_ALL_USERS;
import static com.knecon.fforesight.tenantusermanagement.permissions.UserManagementPermissions.READ_USERS;
import static com.knecon.fforesight.tenantusermanagement.permissions.UserManagementPermissions.UPDATE_MY_PROFILE;
@ -26,8 +25,7 @@ import com.knecon.fforesight.tenantusermanagement.model.ResetPasswordRequest;
import com.knecon.fforesight.tenantusermanagement.model.UpdateMyProfileRequest;
import com.knecon.fforesight.tenantusermanagement.model.UpdateProfileRequest;
import com.knecon.fforesight.tenantusermanagement.model.User;
import com.knecon.fforesight.tenantusermanagement.permissions.ApplicationRoles;
import com.knecon.fforesight.tenantusermanagement.service.TenantApplicationTypeService;
import com.knecon.fforesight.tenantusermanagement.properties.TenantUserManagementProperties;
import com.knecon.fforesight.tenantusermanagement.service.UserService;
import jakarta.validation.Valid;
@ -39,9 +37,8 @@ import lombok.extern.slf4j.Slf4j;
@RequiredArgsConstructor
public class UserController implements UserResource, PublicResource {
private final UserService userService;
private final TenantApplicationTypeService tenantApplicationTypeService;
private final TenantUserManagementProperties tenantUserManagementProperties;
@Override
@ -51,15 +48,9 @@ public class UserController implements UserResource, PublicResource {
if (bypassCache) {
userService.evictUserCache();
}
var mappedRoles = tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping().getAllRoles();
return userService.getAllUsers()
.stream()
.filter(user -> user.getRoles()
.stream()
.anyMatch(mappedRoles::contains))
.filter(KNECON_ROLE_FILTER)
.toList();
var allRoles = tenantUserManagementProperties.getKcRoleMapping().getAllRoles();
return userService.getAllUsers().stream().filter(user -> user.getRoles().stream().anyMatch(allRoles::contains)).collect(Collectors.toList());
}
@ -71,10 +62,7 @@ public class UserController implements UserResource, PublicResource {
userService.evictUserCache();
}
return userService.getAllUsers()
.stream()
.filter(KNECON_ROLE_FILTER)
.toList();
return userService.getAllUsers();
}
@ -125,20 +113,7 @@ public class UserController implements UserResource, PublicResource {
if (StringUtils.isEmpty(userId)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "The userId should not be empty.");
}
var user = userService.getUserById(userId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
Set<String> filteredRoles = user.getRoles()
.stream()
.filter(ApplicationRoles::isNoKneconRole)
.collect(Collectors.toSet());
if (!user.getRoles().isEmpty() && filteredRoles.isEmpty()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found");
}
user.setRoles(filteredRoles);
return user;
return userService.getUserById(userId).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
}

View File

@ -4,7 +4,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@ -15,8 +14,6 @@ import com.knecon.fforesight.tenantusermanagement.api.external.UserPreferenceRes
import com.knecon.fforesight.tenantusermanagement.permissions.UserManagementPermissions;
import com.knecon.fforesight.tenantusermanagement.service.UserService;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.NotFoundException;
import lombok.RequiredArgsConstructor;
@RestController

View File

@ -1,57 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.controller.external.v2;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.knecon.fforesight.tenantusermanagement.api.external.v2.PublicResourceV2;
import com.knecon.fforesight.tenantusermanagement.api.external.v2.UserResourceV2;
import com.knecon.fforesight.tenantusermanagement.api.external.v2.model.User;
import com.knecon.fforesight.tenantusermanagement.controller.external.UserController;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequiredArgsConstructor
@Tag(name = "6. Users endpoints", description = "Operations related to users.")
public class UserControllerV2 implements UserResourceV2, PublicResourceV2 {
private final UserController userController;
public List<User> getUsers(@RequestParam(name = USERNAME_PARAM, required = false) String username) {
var users = userController.getApplicationSpecificUsers(false)
.stream()
.map(this::convertUser);
if (username == null) {
return users.toList();
}
return users.filter(user -> user.getUsername().equals(username)).toList();
}
public User getUserById(@PathVariable(USER_ID) String userId) {
return convertUser(userController.getUserById(userId));
}
private User convertUser(com.knecon.fforesight.tenantusermanagement.model.User user){
return User.builder()
.id(user.getUserId())
.username(user.getUsername())
.email(user.getEmail())
.firstName(user.getFirstName())
.lastName(user.getLastName())
.active(user.isActive())
.roles(user.getRoles())
.build();
}
}

View File

@ -8,15 +8,13 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import com.fasterxml.jackson.databind.JsonNode;
import com.knecon.fforesight.tenantcommons.TenantApplicationType;
import com.knecon.fforesight.tenantcommons.model.TenantResponse;
import com.knecon.fforesight.tenantcommons.model.UpdateDetailsRequest;
import com.knecon.fforesight.tenantusermanagement.api.internal.InternalResource;
import com.knecon.fforesight.tenantusermanagement.api.internal.InternalTenantsResource;
import com.knecon.fforesight.tenantusermanagement.model.CreateTenantRequest;
import com.knecon.fforesight.tenantusermanagement.model.DeploymentKeyResponse;
import com.knecon.fforesight.tenantusermanagement.model.UpdateTenantRequest;
import com.knecon.fforesight.tenantusermanagement.model.SimpleTenantResponse;
import com.knecon.fforesight.tenantusermanagement.model.TenantRequest;
import com.knecon.fforesight.tenantusermanagement.service.DeploymentKeyService;
import com.knecon.fforesight.tenantusermanagement.service.TenantManagementService;
@ -38,7 +36,7 @@ public class InternalTenantsController implements InternalTenantsResource, Inter
}
public TenantResponse createTenant(@Valid @RequestBody CreateTenantRequest tenantRequest) {
public TenantResponse createTenant(@Valid @RequestBody TenantRequest tenantRequest) {
try {
return tenantManagementService.createTenant(tenantRequest);
@ -61,29 +59,21 @@ public class InternalTenantsController implements InternalTenantsResource, Inter
@Override
public TenantResponse updateTenant(String tenantId, UpdateTenantRequest tenantRequest) {
public TenantResponse updateTenant(String tenantId, TenantRequest tenantRequest) {
return tenantManagementService.updateTenant(tenantId, tenantRequest);
}
public List<SimpleTenantResponse> getSimpleTenants() {
return tenantManagementService.getTenants().stream().map(t -> new SimpleTenantResponse(t.getTenantId(), t.getDisplayName(), t.getGuid())).toList();
}
public DeploymentKeyResponse getDeploymentKey(@PathVariable(TENANT_ID_PARAM) String tenantId) {
return new DeploymentKeyResponse(deploymentKeyService.getDeploymentKey(tenantId));
}
@Override
public void syncTenant(@PathVariable(TENANT_ID_PARAM) String tenantId, @RequestBody JsonNode payload) {
tenantManagementService.syncTenant(tenantId, payload);
}
public TenantApplicationType getTenantApplicationType(@PathVariable(TENANT_ID_PARAM) String tenantId) {
return tenantManagementService.getTenantApplicationType(tenantId);
}
}

View File

@ -10,7 +10,6 @@ import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantusermanagement.model.TenantUser;
import com.knecon.fforesight.tenantusermanagement.service.TenantManagementService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
@ -21,15 +20,17 @@ import lombok.SneakyThrows;
public class DevApplicationRunner implements ApplicationRunner {
private final DevTestTenantService devTestTenantService;
private final TenantManagementService tenantManagementService;
@Override
@SneakyThrows
public void run(ApplicationArguments args) {
devTestTenantService.createTestTenantIfNotExists("redaction", new ArrayList<>());
tenantManagementService.syncTenant("redaction", null);
// devTestTenantService.deleteAll();
List<TenantUser> users = new ArrayList<>();
users.add(TenantUser.builder().email("test@taas.com").username("test@taas.com").password("test").roles(Set.of("SUPER_USER")).build());
devTestTenantService.createTestTenantIfNotExists("taas", users);
}
}

View File

@ -1,12 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.dev;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("dev")
@EnableConfigurationProperties(DevTenantProperties.class)
public class DevConfiguration {
}

View File

@ -1,60 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.dev;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
@Data
@ConfigurationProperties("dev.tenant")
public class DevTenantProperties {
private boolean recreateTenant;
private DevDatabaseProperties db = new DevDatabaseProperties();
private DevStorageProperties storage = new DevStorageProperties();
@Data
public static class DevStorageProperties {
private DevStorageMode mode = DevStorageMode.S3;
private DevS3StorageProperties s3 = new DevS3StorageProperties();
private DevAzureStorageProperties azure = new DevAzureStorageProperties();
}
public enum DevStorageMode {
S3,
AZURE
}
@Data
public static class DevS3StorageProperties {
private String key;
private String secret;
private String bucket;
private String endpoint;
}
@Data
public static class DevAzureStorageProperties {
private String containerName;
private String connectionString;
}
@Data
public static class DevDatabaseProperties {
private int port;
private String host;
private String database;
private String schema;
private String username;
private String password;
}
}

View File

@ -7,6 +7,7 @@ import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
@ -15,12 +16,12 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.StatementCallback;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.knecon.fforesight.tenantcommons.model.AzureStorageConnection;
import com.knecon.fforesight.tenantcommons.model.DatabaseConnection;
import com.knecon.fforesight.tenantcommons.model.S3StorageConnection;
import com.knecon.fforesight.tenantusermanagement.model.SearchConnectionRequest;
import com.knecon.fforesight.tenantusermanagement.model.CreateTenantRequest;
import com.knecon.fforesight.tenantcommons.model.SearchConnection;
import com.knecon.fforesight.tenantusermanagement.model.TenantRequest;
import com.knecon.fforesight.tenantusermanagement.model.TenantUser;
import com.knecon.fforesight.tenantusermanagement.repository.TenantRepository;
import com.knecon.fforesight.tenantusermanagement.service.TenantManagementService;
@ -41,19 +42,13 @@ public class DevTestTenantService {
@Value("${spring.datasource.url:}")
private String masterJDBCURL;
private final DevTenantProperties devTenantProperties;
@SneakyThrows
public void createTestTenantIfNotExists(String tenantId, List<TenantUser> users) {
if (devTenantProperties.isRecreateTenant()) {
tenantRepository.deleteByQuery(tenantId);
}
try {
tenantManagementService.getTenant(tenantId);
} catch (Exception e) {
tenantRepository.deleteByQuery(tenantId);
createTestTenant(tenantId, users);
}
@ -72,39 +67,25 @@ public class DevTestTenantService {
createDatabase(tenantsDBName, tenantsDBPassword);
createSchema(jdbcUrl, tenantId, tenantsDBName, tenantsDBPassword);
var tenantRequest = CreateTenantRequest.builder()
var tenantRequest = TenantRequest.builder()
.tenantId(tenantId)
.displayName(tenantId)
.guid(UUID.randomUUID().toString())
.defaultUsers(users != null ? users : new ArrayList<>())
.databaseConnection(DatabaseConnection.builder()
.driver("postgresql")
.host(devTenantProperties.getDb().getHost())
.port(devTenantProperties.getDb().getPort() + "")
.database(devTenantProperties.getDb().getDatabase())
.schema(devTenantProperties.getDb().getSchema())
.username(devTenantProperties.getDb().getUsername())
.password(devTenantProperties.getDb().getPassword())
.host("localhost")
.port("5432")
.database(tenantsDBName)
.schema(tenantId)
.username(tenantsDBName)
.password(tenantsDBPassword)
.build())
.searchConnection(SearchConnectionRequest.builder()
.hosts(Set.of("localhost"))
.port(9200)
.scheme("http")
.numberOfShards("1")
.numberOfReplicas("5")
.build());
.searchConnection(SearchConnection.builder().hosts(Set.of("localhost")).port(9200).scheme("http").numberOfShards("1").numberOfReplicas("5").build())
.s3StorageConnection(S3StorageConnection.builder().key("minioadmin").secret("minioadmin").bucketName("redaction").endpoint("http://localhost:9000").build())
.build();
if (devTenantProperties.getStorage().getMode() == DevTenantProperties.DevStorageMode.S3) {
tenantRequest.s3StorageConnection(S3StorageConnection.builder().key(devTenantProperties.getStorage().getS3().getKey())
.secret(devTenantProperties.getStorage().getS3().getSecret())
.region("eu-central-1")
.bucketName(devTenantProperties.getStorage().getS3().getBucket()).endpoint(devTenantProperties.getStorage().getS3().getEndpoint()).build());
} else {
tenantRequest.azureStorageConnection(AzureStorageConnection.builder().connectionString(devTenantProperties.getStorage().getAzure().getConnectionString())
.containerName(devTenantProperties.getStorage().getAzure().getContainerName()).build());
}
tenantManagementService.createTenant(tenantRequest.build());
tenantManagementService.createTenant(tenantRequest);
}
@ -149,4 +130,11 @@ public class DevTestTenantService {
}
}
@Transactional
public void deleteAll() {
tenantRepository.deleteAll();
}
}

View File

@ -1,60 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "global_smtp_configuration")
public class GlobalSMTPConfigurationEntity {
@Id
@Column(nullable = false, updatable = false)
private String id = "singleton";
@Column
private Boolean auth;
@Column
private String envelopeFrom;
@Column
private String fromEmail;
@Column
private String fromDisplayName;
@Column
private String host;
@Column
private String password;
@Column
private Integer port;
@Column
private String replyTo;
@Column
private String replyToDisplayName;
@Column
private Boolean ssl;
@Column
private Boolean starttls;
@Column
private String userName;
}

View File

@ -1,30 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Embeddable
public class MongoDBConnectionEntity {
@Column(name = "mongodb_prefix")
private String prefix;
@Column(name = "mongodb_username")
private String username;
@Column(name = "mongodb_password")
private String password;
@Column(name = "mongodb_address")
private String address;
@Column(name = "mongodb_database")
private String database;
@Column(name = "mongodb_options")
private String options;
}

View File

@ -23,7 +23,6 @@ public class SearchConnectionEntity {
@Convert(converter = JSONStringSetConverter.class)
private Set<String> hosts;
@Column(name = "search_port")
@Builder.Default
private int port = 9300;
@Column(name = "search_scheme")
private String scheme;
@ -35,7 +34,5 @@ public class SearchConnectionEntity {
private String numberOfShards;
@Column(name = "search_number_of_replicas")
private String numberOfReplicas;
@Column(name = "search_index_prefix")
private String indexPrefix;
}

View File

@ -3,7 +3,6 @@ package com.knecon.fforesight.tenantusermanagement.entity;
import java.util.HashMap;
import java.util.Map;
import com.knecon.fforesight.tenantcommons.TenantApplicationType;
import com.knecon.fforesight.tenantusermanagement.utils.JSONMapConverter;
import jakarta.persistence.Basic;
@ -11,8 +10,6 @@ import jakarta.persistence.Column;
import jakarta.persistence.Convert;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@ -48,17 +45,8 @@ public class TenantEntity {
@Embedded
private S3StorageConnectionEntity s3StorageConnection;
@Embedded
private MongoDBConnectionEntity mongoDBConnection;
@Basic(fetch = FetchType.EAGER)
@Column(columnDefinition = "text")
@Convert(converter = JSONMapConverter.class)
@Builder.Default
private Map<String, Object> details = new HashMap<>();
@Column
@Enumerated(EnumType.STRING)
private TenantApplicationType applicationType;
}

View File

@ -1,17 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.events;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TenantSyncEvent {
private String tenantId;
private JsonNode payload;
}

View File

@ -1,23 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.exception;
public class ConflictException extends RuntimeException {
public ConflictException(String message) {
super(message);
}
public ConflictException(String message, Throwable t) {
super(message, t);
}
public static ConflictException withObjectName(String objectName) {
return new ConflictException(String.format("An object of type %s already exists.", objectName));
}
}

View File

@ -1,14 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.CONFLICT)
public class IdentityProviderExistsAlreadyException extends ConflictException {
private static final String IDENTITY_PROVIDER_ALREADY_EXISTS_MESSAGE = "Identity provider with alias %s already exists in keycloak.";
public IdentityProviderExistsAlreadyException(String identityProviderAlias) {
super(String.format(IDENTITY_PROVIDER_ALREADY_EXISTS_MESSAGE, identityProviderAlias));
}
}

View File

@ -1,16 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import jakarta.ws.rs.NotFoundException;
@ResponseStatus(code = HttpStatus.NOT_FOUND)
public class IdentityProviderNotFoundException extends NotFoundException {
private static final String IDENTITY_PROVIDER_NOT_FOUND_MESSAGE = "Identity provider with alias %s not found in keycloak.";
public IdentityProviderNotFoundException(String identityProviderAlias) {
super(String.format(IDENTITY_PROVIDER_NOT_FOUND_MESSAGE, identityProviderAlias));
}
}

View File

@ -1,17 +1,12 @@
package com.knecon.fforesight.tenantusermanagement.initializer;
import com.knecon.fforesight.tenantusermanagement.service.TenantManagementService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantcommons.TenantProvider;
import com.knecon.fforesight.tenantusermanagement.service.KeyCloakRoleManagerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -25,17 +20,9 @@ public class MigrateOnlyHook {
private final ApplicationContext ctx;
private final TenantManagementService tenantManagementService;
private final KeyCloakRoleManagerService keyCloakRoleManagerService;
@SuppressWarnings("PMD.DoNotTerminateVM")
@SuppressWarnings("PMD")
@EventListener(ApplicationReadyEvent.class)
public void migrate() {
tenantManagementService.getTenants().forEach(tenant -> keyCloakRoleManagerService.updateRoles(tenant.getTenantId(), tenant.getApplicationType()));
// This should only run in post upgrade hook
if (isMigrateOnly) {
System.exit(SpringApplication.exit(ctx, () -> 0));

View File

@ -0,0 +1,5 @@
package com.knecon.fforesight.tenantusermanagement.initializer;
public class TenantInitializer {
}

View File

@ -0,0 +1,5 @@
package com.knecon.fforesight.tenantusermanagement.initializer;
public class TenantInitializerService {
}

View File

@ -20,10 +20,29 @@ public class MessagingConfiguration {
return new TopicExchange(tenantExchangeName);
}
@Bean
TopicExchange userExchange(@Value("${fforesight.user-exchange.name}") String userExchangeName) {
return new TopicExchange(userExchangeName);
}
@Bean
public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
final var rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(producerJackson2MessageConverter());
return rabbitTemplate;
}
@Bean
public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
return new Jackson2JsonMessageConverter(mapper);
}
}

View File

@ -1,55 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
import java.util.ArrayList;
import java.util.List;
import com.knecon.fforesight.tenantcommons.TenantApplicationType;
import com.knecon.fforesight.tenantcommons.model.AzureStorageConnection;
import com.knecon.fforesight.tenantcommons.model.DatabaseConnection;
import com.knecon.fforesight.tenantcommons.model.S3StorageConnection;
import com.knecon.fforesight.tenantcommons.model.MongoDBConnection;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Object containing the request to create a tenant.")
public class CreateTenantRequest {
@NotBlank
@Pattern(regexp = "[A-Za-z0-9_-]*", message = "Tenant Id must match [A-Za-z0-9_-]")
@Schema(description = "Parameter containing the ID of the tenant.")
private String tenantId;
@NotBlank
@Schema(description = "Parameter containing the display name of the tenant.")
private String displayName;
@Schema(description = "Parameter containing the global unique ID of the tenant.")
private String guid;
@Schema(description = "Parameter containing data of the database connection.")
private DatabaseConnection databaseConnection;
@Schema(description = "Parameter containing data of the search connection.")
private SearchConnectionRequest searchConnection;
@Schema(description = "Parameter containing data of the Azure storage connection.")
private AzureStorageConnection azureStorageConnection;
@Schema(description = "Parameter containing data of the S3 storage connection.")
private S3StorageConnection s3StorageConnection;
@Schema(description = "Parameter containing data of the MongoDB connection.")
private MongoDBConnection mongoDBConnection;
@Builder.Default
@Schema(description = "Parameter containing a list of users of the tenant.")
private List<TenantUser> defaultUsers = new ArrayList<>();
@Schema(description = "Parameter containing the application type of the tenant.")
private TenantApplicationType applicationType;
}

View File

@ -7,7 +7,6 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "Object containing the request to create a profile.")
public class CreateUserRequest {
@Schema(description = "Email of user.")
@ -22,10 +21,7 @@ public class CreateUserRequest {
@Schema(description = "Last name of user.")
private String lastName;
@Schema(description = "Roles to assign to user.")
@Schema(description = "The list of RED_* roles.")
private Set<String> roles = new HashSet<>();
@Schema(description = "Whether a set password mail should be sent")
private boolean sendSetPasswordMail;
}

View File

@ -1,6 +1,5 @@
package com.knecon.fforesight.tenantusermanagement.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@ -8,10 +7,8 @@ import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "Object containing data about the deployment key.")
public class DeploymentKeyResponse {
@Schema(description = "Parameter containing the deployment key.")
private String value;
}

View File

@ -1,10 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
import java.util.Map;
public interface ExtensibleModel {
void setNotMappedFields(Map<String, String> notMappedFields);
Map<String, String> getNotMappedFields();
}

View File

@ -1,6 +1,5 @@
package com.knecon.fforesight.tenantusermanagement.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@ -12,14 +11,10 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor
@Builder
@EqualsAndHashCode
@Schema(description = "Object containing data about general configurations.")
public class GeneralConfigurationModel {
@Schema(description = "Parameter indicating if the 'ForgotPassword' function is enabled.")
private boolean forgotPasswordFunctionEnabled;
@Schema(description = "Parameter containing the auxiliary name.")
private String auxiliaryName;
@Schema(description = "Parameter containing the display name of the application.")
private String displayName;
}

View File

@ -1,128 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Object containing information about an identity provider configuration.")
public class IdentityProviderConfigModel implements ExtensibleModel {
@Builder.Default
@Schema(description = "Whether the external identity provider is allowed to create a new identifier to represent the principal")
private Boolean allowCreate = true;
@Builder.Default
@Schema(description = "Display order : It defines the order of the providers in GUI (for example, on the Login page). The lowest number will be applied first.")
private Integer guiOrder = 0;
@Schema(description = "Service provider entity ID : It is used to uniquely identify this SAML Service Provider.")
private String entityId;
@Schema(description = "Identity provider entity ID : It is used to validate the Issuer for received SAML assertions. If empty, no Issuer validation is performed.")
private String idpEntityId;
@Schema(description = "The Url that must be used to send authentication requests (SAML AuthnRequest).")
private String singleSignOnServiceUrl;
@Builder.Default
@Schema(description = "The Url that must be used to send logout requests.")
private String singleLogoutServiceUrl = "";
@Builder.Default
@Schema(description = "Name of the Attribute Consuming Service profile to advertise in the SP metadata.")
private String attributeConsumingServiceName = "";
@Builder.Default
@Schema(description = "Backchannel logout : Does the external IDP support backchannel logout?")
private Boolean backchannelSupported = false;
@Builder.Default
@Schema(description = "Specifies the URI reference corresponding to a name identifier format.")
private IdentityProviderNameIDPolicyFormat nameIDPolicyFormat = IdentityProviderNameIDPolicyFormat.PERSISTENT;
@Builder.Default
@Schema(description = "Used to identify and track external users from the assertion. Default is using Subject NameID, alternatively can be set up as identifying attribute.")
private IdentityProviderPrincipalType principalType = IdentityProviderPrincipalType.SUBJECT;
@Builder.Default
@Schema(description = "HTTP-POST binding response : Indicates whether to respond to requests using HTTP-POST binding. If false, HTTP-REDIRECT binding will be used.")
private Boolean postBindingResponse = false;
@Builder.Default
@Schema(description = "HTTP-POST binding for AuthnRequest : Indicates whether the AuthnRequest must be sent using HTTP-POST binding. If false, HTTP-REDIRECT binding will be used.")
private Boolean postBindingAuthnRequest = false;
@Builder.Default
@Schema(description = "HTTP-POST binding logout : Indicates whether to respond to requests using HTTP-POST binding. If false, HTTP-REDIRECT binding will be used.")
private Boolean postBindingLogout = false;
@Builder.Default
@Schema(description = "Indicates whether the identity provider expects a signed AuthnRequest.")
private Boolean wantAuthnRequestsSigned = false;
@Builder.Default
@Schema(description = "Indicates whether this service provider expects a signed Assertion.")
private Boolean wantAssertionsSigned = false;
@Builder.Default
@Schema(description = "Indicates whether this service provider expects an encrypted Assertion.")
private Boolean wantAssertionsEncrypted = false;
@Builder.Default
@Schema(description = "Force authentication : Indicates whether the identity provider must authenticate the presenter directly rather than rely on a previous security context.")
private Boolean forceAuthn = false;
@Builder.Default
@Schema(description = "Enable/disable signature validation of external IDP signatures.")
private Boolean validateSignature = false;
@Builder.Default
@Schema(description = "Sign service provider metadata : Enable/disable signature of the provider SAML metadata.")
private Boolean signSpMetadata = false;
@Builder.Default
@Schema(description = "Pass subject : During login phase, forward an optional login_hint query parameter to SAML AuthnRequest's Subject.")
private Boolean loginHint = false;
@Builder.Default
@Schema(description = "Clock skew in seconds that is tolerated when validating identity provider tokens. Default value is zero.")
private Integer allowedClockSkew = 0;
@Builder.Default
@Schema(description = "Index of the Attribute Consuming Service profile to request during authentication.")
private Integer attributeConsumingServiceIndex = 0;
@Builder.Default
@Schema(description = "If hidden, login with this provider is possible only if requested explicitly, for example using the 'kc_idp_hint' parameter.")
private Boolean hideOnLoginPage = false;
@Builder.Default
@Schema(description = "Default sync mode for all mappers. The sync mode determines when user data will be synced using the mappers. Possible values are: 'legacy' to keep the behaviour before this option was introduced, 'import' to only import the user once during first login of the user with this identity provider, 'force' to always update the user during every login with this identity provider.")
@JsonInclude(JsonInclude.Include.NON_NULL)
private IdentityProviderSyncMode syncMode = IdentityProviderSyncMode.IMPORT;
@Schema(description = "The signature algorithm to use to sign documents. Note that 'SHA1' based algorithms are deprecated and can be removed in the future. It is recommended to stick to some more secure algorithm instead of '*_SHA1'.")
@JsonInclude(JsonInclude.Include.NON_NULL)
private IdentityProviderSignatureAlgorithm signatureAlgorithm;
@Schema(description = "SAML signature key name : Signed SAML documents contain identification of signing key in KeyName element. For Keycloak / RH-SSO counter-party, use KEY_ID, for MS AD FS use CERT_SUBJECT, for others check and use NONE if no other option works.")
@JsonInclude(JsonInclude.Include.NON_NULL)
private IdentityProviderSAMLSignatureKeyName xmlSigKeyInfoKeyNameTransformer;
@Builder.Default
@Schema(description = "All not mapped configurations")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Map<String, String> notMappedFields = new HashMap<>();
}

View File

@ -1,65 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Create request for the identity provider configuration.")
public class IdentityProviderConfigRequest {
@Builder.Default
@Schema(description = "Whether the external identity provider is allowed to create a new identifier to represent the principal (default: true)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private Boolean allowCreate = true;
@Builder.Default
@Schema(description = "Display order : It defines the order of the providers in GUI (for example, on the Login page). The lowest number will be applied first. (default: 0)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private Integer guiOrder = 0;
@Schema(description = "Service provider entity ID : It is used to uniquely identify this SAML Service Provider.", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull
private String entityId;
@Schema(description = "Identity provider entity ID : It is used to validate the Issuer for received SAML assertions. If empty, no Issuer validation is performed.", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull
private String idpEntityId;
@Schema(description = "The Url that must be used to send authentication requests (SAML AuthnRequest).", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull
private String singleSignOnServiceUrl;
@Builder.Default
@Schema(description = "Specifies the URI reference corresponding to a name identifier format. (default: PERSISTENT)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private IdentityProviderNameIDPolicyFormat nameIDPolicyFormat = IdentityProviderNameIDPolicyFormat.PERSISTENT;
@Builder.Default
@Schema(description = "Used to identify and track external users from the assertion. Default is using Subject NameID, alternatively can be set up as identifying attribute. (default: SUBJECT)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private IdentityProviderPrincipalType principalType = IdentityProviderPrincipalType.SUBJECT;
@Builder.Default
@Schema(description = "HTTP-POST binding response : Indicates whether to respond to requests using HTTP-POST binding. If false, HTTP-REDIRECT binding will be used. (default: false)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private Boolean postBindingResponse = false;
@Builder.Default
@Schema(description = "HTTP-POST binding for AuthnRequest : Indicates whether the AuthnRequest must be sent using HTTP-POST binding. If false, HTTP-REDIRECT binding will be used. (default: false)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private Boolean postBindingAuthnRequest = false;
@Builder.Default
@Schema(description = "Indicates whether the identity provider expects a signed AuthnRequest. (default: false)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private Boolean wantAuthnRequestsSigned = false;
@Builder.Default
@Schema(description = "The signature algorithm to use to sign documents. Note that 'SHA1' based algorithms are deprecated and can be removed in the future. It is recommended to stick to some more secure algorithm instead of '*_SHA1'. (only used when wantAuthnRequestsSigned is true, default: RSA_SHA256)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private IdentityProviderSignatureAlgorithm signatureAlgorithm = IdentityProviderSignatureAlgorithm.RSA_SHA256;
@Builder.Default
@Schema(description = "SAML signature key name : Signed SAML documents contain identification of signing key in KeyName element. For Keycloak / RH-SSO counter-party, use KEY_ID, for MS AD FS use CERT_SUBJECT, for others check and use NONE if no other option works. (only used when wantAuthnRequestsSigned is true, default: KEY_ID)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private IdentityProviderSAMLSignatureKeyName xmlSigKeyInfoKeyNameTransformer = IdentityProviderSAMLSignatureKeyName.KEY_ID;
}

View File

@ -1,69 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.Builder;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Object containing information about an identity provider.")
public class IdentityProviderModel implements ExtensibleModel {
@Schema(description = "Alias of the identity provider used for identification")
private String alias;
@Builder.Default
@Schema(description = "Configuration of the identity provider")
private IdentityProviderConfigModel config = new IdentityProviderConfigModel();
@Builder.Default
@Schema(description = "Display name of the identity provider in keycloak")
private String displayName = "";
@Builder.Default
@Schema(description = "The ID of the SSO technology provider")
private String providerId = "saml";
@Builder.Default
@Schema(description = "Enable/disable if tokens must be stored after authenticating users.")
private Boolean storeToken = false;
@Builder.Default
@Schema(description = "Stored tokens readable : Enable/disable if new users can read any stored tokens. This assigns the broker.read-token role.")
private Boolean addReadTokenRoleOnCreate = false;
@Builder.Default
@Schema(description = "If enabled, email provided by this provider is not verified even if verification is enabled for the realm.")
private Boolean trustEmail = false;
@Builder.Default
@Schema(description = "Account linking only : If true, users cannot log in through this provider. They can only link to this provider. This is useful if you don't want to allow login from the provider, but want to integrate with a provider")
private Boolean linkOnly = false;
@Builder.Default
@Schema(description = "First login flow : Alias of authentication flow, which is triggered after first login with this identity provider. Term 'First Login' means that no Keycloak account is currently linked to the authenticated identity provider account.")
private String firstBrokerLoginFlowAlias = "first broker login";
@Builder.Default
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Map<String, String> notMappedFields = new HashMap<>();
public void setSpecificDefaults() {
this.setStoreToken(true);
this.setTrustEmail(true);
this.getConfig().setSyncMode(IdentityProviderSyncMode.FORCE);
}
}

View File

@ -1,43 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
import com.fasterxml.jackson.annotation.JsonValue;
import jakarta.ws.rs.BadRequestException;
import lombok.Getter;
@Getter
public enum IdentityProviderNameIDPolicyFormat {
PERSISTENT("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"),
TRANSIENT("urn:oasis:names:tc:SAML:2.0:nameid-format:transient"),
EMAIL("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"),
KERBEROS("urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos"),
X_509_SUBJECT_NAME("urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName"),
WINDOWS_DOMAIN_QUALIFIED_NAME("urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName"),
UNSPECIFIED("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
private final String representation;
IdentityProviderNameIDPolicyFormat(String representation) {
this.representation = representation;
}
@Override
@JsonValue
public String toString() {
return representation;
}
public static IdentityProviderNameIDPolicyFormat fromRepresentation(String value) {
for (IdentityProviderNameIDPolicyFormat v : values()) {
if (v.getRepresentation().equalsIgnoreCase(value)) {
return v;
}
}
throw new BadRequestException("Unsupported identity provider name ID policy format");
}
}

View File

@ -1,24 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
import jakarta.ws.rs.BadRequestException;
public enum IdentityProviderPrincipalType {
SUBJECT,
ATTRIBUTE,
FRIENDLY_ATTRIBUTE;
public static IdentityProviderPrincipalType fromStringValue(String value) {
for (IdentityProviderPrincipalType v : values()) {
if (v.toString().equalsIgnoreCase(value)) {
return v;
}
if (value.equalsIgnoreCase("Subject NameID")) {
return SUBJECT;
}
}
throw new BadRequestException("Unsupported identity provider principal type");
}
}

View File

@ -1,34 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Create or update request for an identity provider.")
public class IdentityProviderRequest {
@Schema(description = "Alias of the identity provider used for identification", requiredMode = Schema.RequiredMode.REQUIRED)
private String alias;
@Builder.Default
@Schema(description = "Configuration of the identity provider", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull
private @Valid IdentityProviderConfigRequest config = new IdentityProviderConfigRequest();
@Builder.Default
@Schema(description = "Display name of the identity provider in keycloak (optional, fallbacks to alias if empty)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String displayName = "";
@Builder.Default
@Schema(description = "The ID of the SSO technology provider (default: saml)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String providerId = "saml";
}

View File

@ -1,7 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
public enum IdentityProviderSAMLSignatureKeyName {
NONE,
KEY_ID,
CERT_SUBJECT
}

View File

@ -1,10 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
public enum IdentityProviderSignatureAlgorithm {
RSA_SHA1,
RSA_SHA256,
RSA_SHA256_MGF1,
RSA_SHA512,
RSA_SHA512_MGF1,
DSA_SHA1
}

View File

@ -1,8 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
public enum IdentityProviderSyncMode {
INHERIT,
IMPORT,
LEGACY,
FORCE
}

View File

@ -1,36 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Create request for an identity provider using a SAML entity descriptor for a faster creation process.")
public class IdentityProviderWithDescriptorRequest {
@Schema(description = "Alias of the identity provider used for identification", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull
private String alias;
@Builder.Default
@Schema(description = "Display name of the identity provider in keycloak (optional, fallbacks to alias if empty)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String displayName = "";
@Builder.Default
@Schema(description = "The ID of the SSO technology provider (default: saml)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String providerId = "saml";
@Schema(description = "The SAML entity descriptor as a URL to external IDP metadata, used to fill other fields for a faster identity provider creation process", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull
private String samlEntityDescriptorURL;
@Schema(description = "Service provider entity ID that will be used to uniquely identify this SAML Service Provider", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull
private String entityId;
}

View File

@ -1,21 +1,11 @@
package com.knecon.fforesight.tenantusermanagement.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Schema(description = "Object containing the request to reset a password.")
public class ResetPasswordRequest {
@Schema(description = "Parameter containing the new password.")
private String password;
@Schema(description = "Parameter indicating if the password is temporary.")
private boolean temporary;
}

View File

@ -1,6 +1,5 @@
package com.knecon.fforesight.tenantusermanagement.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@ -10,34 +9,19 @@ import lombok.NoArgsConstructor;
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Object containing the SMTP configuration.")
public class SMTPConfiguration {
@Schema(description = "Parameter containing the ID of the SMTP configuration.")
private String id;
@Schema(description = "Parameter containing the email of the sender.")
private String from;
@Schema(description = "Parameter containing the display name of the sender.")
private String fromDisplayName;
@Schema(description = "Parameter containing the email of the sender on the envelope.")
private String envelopeFrom;
@Schema(description = "Parameter containing the host.")
private String host;
@Schema(description = "Parameter containing the port.")
private Integer port;
@Schema(description = "Parameter containing the email to reply.")
private String replyTo;
@Schema(description = "Parameter containing the display name of the email to reply.")
private String replyToDisplayName;
@Schema(description = "Parameter indicating the usage of the SSL protocol.")
private boolean ssl;
@Schema(description = "Parameter indicating the usage of the STARTTLS protocol.")
private boolean starttls;
@Schema(description = "Parameter indicating the authentication of the client.")
private boolean auth;
@Schema(description = "Parameter containing the user.")
private String user;
@Schema(description = "Parameter containing the password.")
private String password;
}

View File

@ -1,26 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Object containing a simplified version of the SMTP test connection response.")
public class SMTPResponse {
@Schema(description = "Parameter containing status code of the response.")
private int statusCode;
@Schema(description = "Parameter containing the reason phrase of the response.")
private String reasonPhrase;
@Schema(description = "Parameter containing the email of the recipient.")
private String recipientEmail;
@Schema(description = "Parameter flag that specifies if the admin email was found.")
private boolean adminEmail;
}

View File

@ -1,24 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
import java.util.Set;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SearchConnectionRequest {
private Set<String> hosts;
private int port;
private String scheme;
private String username;
private String password;
private String numberOfShards;
private String numberOfReplicas;
}

View File

@ -1,8 +1,5 @@
package com.knecon.fforesight.tenantusermanagement.model;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@ -10,10 +7,12 @@ import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class IdentityProviderList {
@NoArgsConstructor
public class SimpleTenantResponse {
private String tenantId;
private String displayName;
private String guid;
@Builder.Default
private List<IdentityProviderModel> identityProviders = new ArrayList<>();
}

View File

@ -0,0 +1,40 @@
package com.knecon.fforesight.tenantusermanagement.model;
import java.util.ArrayList;
import java.util.List;
import com.knecon.fforesight.tenantcommons.model.AzureStorageConnection;
import com.knecon.fforesight.tenantcommons.model.DatabaseConnection;
import com.knecon.fforesight.tenantcommons.model.S3StorageConnection;
import com.knecon.fforesight.tenantcommons.model.SearchConnection;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TenantRequest {
@NotBlank
@Pattern(regexp = "[A-Za-z0-9_-]*", message = "Tenant Id must match [A-Za-z0-9_-]")
private String tenantId;
@NotBlank
private String displayName;
private String guid;
private DatabaseConnection databaseConnection;
private SearchConnection searchConnection;
private AzureStorageConnection azureStorageConnection;
private S3StorageConnection s3StorageConnection;
@Builder.Default
private List<TenantUser> defaultUsers = new ArrayList<>();
}

View File

@ -3,7 +3,6 @@ package com.knecon.fforesight.tenantusermanagement.model;
import java.util.HashSet;
import java.util.Set;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@ -13,22 +12,15 @@ import lombok.NoArgsConstructor;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "Object containing the tenant user data.")
public class TenantUser {
@Schema(description = "Parameter containing the username of the tenant user.")
private String username;
@Schema(description = "Parameter containing the password of the tenant user.")
private String password;
@Schema(description = "Parameter containing the email of the tenant user.")
private String email;
@Schema(description = "Parameter containing the first name of the tenant user.")
private String firstName;
@Schema(description = "Parameter containing the last name of the tenant user.")
private String lastName;
@Builder.Default
@Schema(description = "Parameter containing the roles assigned to the tenant user.")
private Set<String> roles = new HashSet<>();
}

View File

@ -12,7 +12,6 @@ import lombok.NoArgsConstructor;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "Object containing the request to update a profile.")
public class UpdateMyProfileRequest {
@Schema(description = "Email of user.")

View File

@ -13,7 +13,6 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Schema(description = "Object containing the request to update a profile.")
public class UpdateProfileRequest {
@Schema(description = "Email of user.")
@ -26,7 +25,7 @@ public class UpdateProfileRequest {
private String lastName;
@Builder.Default
@Schema(description = "Roles to assign to the user.")
@Schema(description = "Roles.")
private Set<String> roles = new HashSet<>();
}

View File

@ -1,43 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.model;
import java.util.ArrayList;
import java.util.List;
import com.knecon.fforesight.tenantcommons.model.AzureStorageConnection;
import com.knecon.fforesight.tenantcommons.model.DatabaseConnection;
import com.knecon.fforesight.tenantcommons.model.MongoDBConnection;
import com.knecon.fforesight.tenantcommons.model.S3StorageConnection;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "Object containing the request to update a tenant.")
public class UpdateTenantRequest {
@NotBlank
@Schema(description = "Parameter containing the display name of the tenant.")
private String displayName;
@Schema(description = "Parameter containing the global unique ID of the tenant.")
private String guid;
@Schema(description = "Parameter containing data of the database connection.")
private DatabaseConnection databaseConnection;
@Schema(description = "Parameter containing data of the search connection.")
private SearchConnectionRequest searchConnection;
@Schema(description = "Parameter containing data of the Azure storage connection.")
private AzureStorageConnection azureStorageConnection;
@Schema(description = "Parameter containing data of the S3 storage connection.")
private S3StorageConnection s3StorageConnection;
@Schema(description = "Parameter containing data of the MongoDB connection.")
private MongoDBConnection mongoDBConnection;
}

View File

@ -4,7 +4,6 @@ import java.io.Serializable;
import java.util.Set;
import java.util.TreeSet;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@ -16,29 +15,21 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = "userId")
@Schema(description = "Object containing the user data.")
public class User implements Serializable {
@Schema(description = "Parameter containing the ID of the user.")
private String userId;
@Schema(description = "Parameter containing the username of the user.")
private String username;
@Schema(description = "Parameter containing the email of the user.")
private String email;
@Schema(description = "Parameter containing the first name of the user.")
private String firstName;
@Schema(description = "Parameter containing the last name of the user.")
private String lastName;
@Schema(description = "Parameter indicating if the user is activated.")
private boolean isActive;
@Builder.Default
@Schema(description = "Parameter containing the roles of the user.")
private Set<String> roles = new TreeSet<>();
}

View File

@ -1,60 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.permissions;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.knecon.fforesight.tenantusermanagement.model.User;
public final class ApplicationRoles {
public static final String KNECON_ADMIN_ROLE = "KNECON_ADMIN";
public static final String KNECON_SUPPORT_ROLE = "KNECON_SUPPORT";
public static final String RED_USER_ROLE = "RED_USER";
public static final String RED_MANAGER_ROLE = "RED_MANAGER";
public static final String RED_ADMIN_ROLE = "RED_ADMIN";
public static final String RED_USER_ADMIN_ROLE = "RED_USER_ADMIN";
public static final Set<String> KNECON_ROLES = Set.of(KNECON_ADMIN_ROLE, KNECON_SUPPORT_ROLE);
public static final Set<String> RED_ROLES = Set.of(RED_USER_ROLE, RED_MANAGER_ROLE, RED_ADMIN_ROLE, RED_USER_ADMIN_ROLE);
public static final Predicate<User> KNECON_ROLE_FILTER = user -> {
Set<String> filteredRoles = user.getRoles()
.stream()
.filter(ApplicationRoles::isNoKneconRole)
.collect(Collectors.toSet());
if (!user.getRoles().isEmpty() && filteredRoles.isEmpty()) {
return false;
}
user.setRoles(filteredRoles);
return true;
};
public static boolean isNoKneconRole(String role) {
return !KNECON_ROLES.contains(role);
}
public static boolean isKneconRole(String role) {
return KNECON_ROLES.contains(role);
}
public static boolean isNoREDRole(String role) {
return !RED_ROLES.contains(role);
}
public static boolean isREDRole(String role) {
return RED_ROLES.contains(role);
}
}

View File

@ -19,16 +19,10 @@ public class UserManagementPermissions {
public static final String CREATE_TENANT = "fforesight-create-tenant";
public static final String GET_TENANTS = "fforesight-get-tenants";
public static final String UPDATE_TENANT = "fforesight-update-tenant";
public static final String DELETE_TENANT = "fforesight-delete-tenant";
public static final String DEPLOYMENT_INFO = "fforesight-deployment-info";
// SMTP
public static final String READ_SMTP_CONFIGURATION = "fforesight-read-smtp-configuration";
public static final String WRITE_SMTP_CONFIGURATION = "fforesight-write-smtp-configuration";
// Identity provider
public static final String READ_IDENTITY_PROVIDER_CONFIGURATION = "fforesight-read-identity-provider-config";
public static final String WRITE_IDENTITY_PROVIDER_CONFIGURATION = "fforesight-write-identity-provider-config";
}

View File

@ -1,25 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.properties;
import java.util.ArrayList;
import java.util.List;
import com.knecon.fforesight.tenantusermanagement.model.KCRoleMapping;
import lombok.Data;
@Data
public class ApplicationTypeProperties {
private String applicationClientId;
private String applicationName;
private Integer tenantAccessTokenLifeSpan = 300;
private Integer accessTokenLifeSpan = 1800;
private Integer ssoSessionIdleTimeout = 86400;
private Integer refreshTokenMaxReuse;
private String defaultTheme = "redaction";
private List<String> validRedirectUris = new ArrayList<>();
private KCRoleMapping kcRoleMapping = new KCRoleMapping();
private String loginTheme;
private String appPrefix;
}

View File

@ -1,13 +1,11 @@
package com.knecon.fforesight.tenantusermanagement.properties;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import com.knecon.fforesight.tenantcommons.TenantApplicationType;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantusermanagement.model.KCRoleMapping;
import lombok.Data;
@ -16,17 +14,20 @@ import lombok.Data;
public class TenantUserManagementProperties {
private String serverUrl;
private String realm = "master";
private String swaggerClientId = "swagger-ui-client";
private String publicServerUrl;
private String realm;
private String applicationClientId;
private String swaggerClientId ="swagger-ui-client";
private String swaggerClientSecret;
private String clientId;
private String clientSecret;
private String publicServerUrl;
private String basePath = "/";
private String basePathV2 = "/api";
private int connectionPoolSize = 10;
private Map<String, ApplicationTypeProperties> applicationTypes = new HashMap<>();
private String applicationName;
private Integer accessTokenLifeSpan = 1800;
private Integer ssoSessionIdleTimeout = 86400;
private String defaultTheme = "redaction";
private List<String> validRedirectUris = new ArrayList<>();
private KCRoleMapping kcRoleMapping = new KCRoleMapping();
}

View File

@ -1,15 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.knecon.fforesight.tenantusermanagement.entity.GlobalSMTPConfigurationEntity;
public interface GlobalSMTPConfigurationRepository extends JpaRepository<GlobalSMTPConfigurationEntity, String> {
default Optional<GlobalSMTPConfigurationEntity> findSingleton() {
return findById("singleton");
}
}

View File

@ -2,33 +2,15 @@ package com.knecon.fforesight.tenantusermanagement.repository;
import java.util.Optional;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.knecon.fforesight.tenantcommons.TenantApplicationType;
import com.knecon.fforesight.tenantusermanagement.entity.TenantEntity;
import jakarta.transaction.Transactional;
public interface TenantRepository extends JpaRepository<TenantEntity, String> {
@Query("select t from TenantEntity t where t.tenantId = :tenantId")
Optional<TenantEntity> findByTenantId(@Param("tenantId") String tenantId);
@CacheEvict(value = "tenantApplicationType", key = "#tenantId")
@Transactional
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete from TenantEntity t where t.id = :tenantId ")
void deleteByQuery(String tenantId);
@Cacheable(value = "tenantApplicationType", key = "#tenantId")
@Query("select t.applicationType from TenantEntity t where t.tenantId = :tenantId")
Optional<TenantApplicationType> findApplicationTypeByTenantId(@Param("tenantId") String tenantId);
}

View File

@ -1,173 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.service;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import javax.net.ssl.SSLContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ResponseStatusException;
import com.knecon.fforesight.tenantusermanagement.model.SMTPResponse;
import jakarta.mail.Address;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Multipart;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.AddressException;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import jakarta.mail.internet.MimeUtility;
import jakarta.ws.rs.BadRequestException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
@Slf4j
@Service
@RequiredArgsConstructor
public class EmailService {
private final String AUTHENTICATION_UNSUCCESSFUL = "Authentication unsuccessful";
private final String WRONG_USERNAME_PASSWORD = "Username and Password not accepted";
public SMTPResponse.SMTPResponseBuilder send(Map<String, String> config, String address, String subject, String textBody) {
Transport transport = null;
try {
Properties props = new Properties();
if (config.containsKey("host")) {
props.setProperty("mail.smtp.host", config.get("host"));
}
boolean auth = "true".equals(config.get("auth"));
boolean ssl = "true".equals(config.get("ssl"));
boolean starttls = "true".equals(config.get("starttls"));
if (config.containsKey("port") && config.get("port") != null) {
props.setProperty("mail.smtp.port", config.get("port"));
}
if (auth) {
props.setProperty("mail.smtp.auth", "true");
}
if (ssl) {
props.setProperty("mail.smtp.ssl.enable", "true");
}
if (starttls) {
props.setProperty("mail.smtp.starttls.enable", "true");
}
if (ssl || starttls) {
props.put("mail.smtp.ssl.protocols", getSupportedSslProtocols());
}
props.setProperty("mail.smtp.timeout", "10000");
props.setProperty("mail.smtp.connectiontimeout", "10000");
String from = config.get("from");
String fromDisplayName = config.get("fromDisplayName");
String replyTo = config.get("replyTo");
String replyToDisplayName = config.get("replyToDisplayName");
String envelopeFrom = config.get("envelopeFrom");
Session session = Session.getInstance(props);
Multipart multipart = new MimeMultipart("alternative");
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(textBody, "UTF-8");
multipart.addBodyPart(textPart);
Message msg = new MimeMessage(session);
msg.setFrom(toInternetAddress(from, fromDisplayName));
msg.setReplyTo(new Address[]{toInternetAddress(from, fromDisplayName)});
if (StringUtils.isNotBlank(replyTo)) {
msg.setReplyTo(new Address[]{toInternetAddress(replyTo, replyToDisplayName)});
}
if (StringUtils.isNotBlank(envelopeFrom)) {
props.setProperty("mail.smtp.from", envelopeFrom);
}
msg.setHeader("To", address);
msg.setSubject(MimeUtility.encodeText(subject, StandardCharsets.UTF_8.name(), null));
msg.setContent(multipart);
msg.saveChanges();
msg.setSentDate(new Date());
transport = session.getTransport("smtp");
if (auth) {
transport.connect(config.get("user"), config.get("password"));
} else {
transport.connect();
}
transport.sendMessage(msg, new InternetAddress[]{new InternetAddress(address)});
return SMTPResponse.builder()
.statusCode(200);
} catch (Exception e) {
if (e.getMessage().contains(AUTHENTICATION_UNSUCCESSFUL) || e.getMessage().contains(WRONG_USERNAME_PASSWORD)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, AUTHENTICATION_UNSUCCESSFUL);
} else {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage(), e);
}
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
log.warn("Failed to close transport", e);
}
}
}
}
protected InternetAddress toInternetAddress(String email, String displayName) throws UnsupportedEncodingException, AddressException, BadRequestException {
if (StringUtils.isBlank(email)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Please provide a valid address");
}
if (StringUtils.isBlank(displayName)) {
return new InternetAddress(email);
}
return new InternetAddress(email, displayName, "utf-8");
}
private String getSupportedSslProtocols() {
try {
String[] protocols = SSLContext.getDefault().getSupportedSSLParameters().getProtocols();
if (protocols != null) {
return String.join(" ", protocols);
}
} catch (Exception e) {
log.warn("Failed to get list of supported SSL protocols", e);
}
return null;
}
}

View File

@ -1,52 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantusermanagement.model.SMTPConfiguration;
import lombok.RequiredArgsConstructor;
@Service
@RequiredArgsConstructor
public class EnvironmentSMTPConfigurationProvider {
private final Environment environment;
public static final Integer KEYCLOAK_DEFAULT_PORT = 25;
public static final String SMTP_DEFAULT_HOST = "SMTP_DEFAULT_HOST";
public static final String SMTP_DEFAULT_PORT = "SMTP_DEFAULT_PORT";
public static final String SMTP_DEFAULT_SENDER_EMAIL = "SMTP_DEFAULT_SENDER_EMAIL";
public static final String SMTP_DEFAULT_SENDER_NAME = "SMTP_DEFAULT_SENDER_NAME";
public static final String SMTP_DEFAULT_REPLY_EMAIL = "SMTP_DEFAULT_REPLY_EMAIL";
public static final String SMTP_DEFAULT_REPLY_NAME = "SMTP_DEFAULT_REPLY_NAME";
public static final String SMTP_DEFAULT_SENDER_ENVELOPE = "SMTP_DEFAULT_SENDER_ENVELOPE";
public static final String SMTP_DEFAULT_SSL = "SMTP_DEFAULT_SSL";
public static final String SMTP_DEFAULT_STARTTLS = "SMTP_DEFAULT_STARTTLS";
public static final String SMTP_DEFAULT_AUTH = "SMTP_DEFAULT_AUTH";
public static final String SMTP_DEFAULT_AUTH_USER = "SMTP_DEFAULT_AUTH_USER";
public static final String SMTP_DEFAULT_AUTH_PASSWORD = "SMTP_DEFAULT_AUTH_PASSWORD";
public SMTPConfiguration get() {
String port = environment.getProperty(SMTP_DEFAULT_PORT, "");
return SMTPConfiguration.builder()
.id("singleton")
.host(environment.getProperty(SMTP_DEFAULT_HOST, ""))
.port(StringUtils.isEmpty(port) || !StringUtils.isNumeric(port) ? KEYCLOAK_DEFAULT_PORT : Integer.parseInt(port))
.from(environment.getProperty(SMTP_DEFAULT_SENDER_EMAIL, ""))
.fromDisplayName(environment.getProperty(SMTP_DEFAULT_SENDER_NAME, ""))
.replyTo(environment.getProperty(SMTP_DEFAULT_REPLY_EMAIL, ""))
.replyToDisplayName(environment.getProperty(SMTP_DEFAULT_REPLY_NAME, ""))
.envelopeFrom(environment.getProperty(SMTP_DEFAULT_SENDER_ENVELOPE, ""))
.ssl(Boolean.parseBoolean(environment.getProperty(SMTP_DEFAULT_SSL, "false")))
.starttls(Boolean.parseBoolean(environment.getProperty(SMTP_DEFAULT_STARTTLS, "false")))
.auth(Boolean.parseBoolean(environment.getProperty(SMTP_DEFAULT_AUTH, "false")))
.user(environment.getProperty(SMTP_DEFAULT_AUTH_USER, ""))
.password(environment.getProperty(SMTP_DEFAULT_AUTH_PASSWORD, ""))
.build();
}
}

View File

@ -4,10 +4,8 @@ import org.apache.commons.lang3.StringUtils;
import org.keycloak.representations.idm.RealmRepresentation;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantcommons.TenantApplicationType;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantusermanagement.model.GeneralConfigurationModel;
import com.knecon.fforesight.tenantusermanagement.properties.ApplicationTypeProperties;
import com.knecon.fforesight.tenantusermanagement.properties.TenantUserManagementProperties;
import lombok.RequiredArgsConstructor;
@ -20,30 +18,28 @@ public class GeneralConfigurationService {
private final RealmService realmService;
private final TenantUserManagementProperties tenantUserManagementProperties;
private final TenantApplicationTypeService tenantApplicationTypeService;
public void initGeneralConfiguration(String tenantId, TenantApplicationType tenantApplicationType) {
public void initGeneralConfiguration(String tenantId) {
TenantContext.setTenantId(tenantId);
var generalConfiguration = getGeneralConfigurations(tenantApplicationType);
log.info("Currently Configured Application Name: {}, default name: {}", generalConfiguration.getDisplayName(), tenantApplicationTypeService.getProperties(tenantApplicationType).getApplicationName());
updateGeneralConfigurations(getGeneralConfigurations(tenantApplicationType), tenantApplicationType);
var generalConfiguration = getGeneralConfigurations();
log.info("Currently Configured Application Name: {}, default name: {}", generalConfiguration.getDisplayName(), tenantUserManagementProperties.getApplicationName());
updateGeneralConfigurations(getGeneralConfigurations());
TenantContext.clear();
}
public GeneralConfigurationModel getGeneralConfigurations(TenantApplicationType tenantApplicationType) {
public GeneralConfigurationModel getGeneralConfigurations() {
var realm = realmService.realm(TenantContext.getTenantId()).toRepresentation();
var auxiliaryName = realm.getDisplayNameHtml();
String computedAuxiliaryName = null;
ApplicationTypeProperties currentAppTypeProperties = tenantApplicationTypeService.getProperties(tenantApplicationType);
if (!currentAppTypeProperties.getApplicationName().equals(auxiliaryName)) {
if (!tenantUserManagementProperties.getApplicationName().equals(auxiliaryName)) {
auxiliaryName = StringUtils.replaceOnce(auxiliaryName, currentAppTypeProperties.getApplicationName(), "");
auxiliaryName = StringUtils.replaceOnce(auxiliaryName, tenantUserManagementProperties.getApplicationName(), "");
auxiliaryName = StringUtils.replaceOnce(auxiliaryName, " (", "");
auxiliaryName = StringUtils.reverse(StringUtils.replaceOnce(StringUtils.reverse(auxiliaryName), ")", ""));
@ -58,7 +54,7 @@ public class GeneralConfigurationService {
}
public void updateGeneralConfigurations(GeneralConfigurationModel generalConfigurationModel, TenantApplicationType tenantApplicationType) {
public void updateGeneralConfigurations(GeneralConfigurationModel generalConfigurationModel) {
var realm = realmService.realm(TenantContext.getTenantId());
@ -71,16 +67,10 @@ public class GeneralConfigurationService {
var realmRepresentation = realm.toRepresentation();
realmRepresentation.setResetPasswordAllowed(generalConfigurationModel.isForgotPasswordFunctionEnabled());
realmRepresentation.setRevokeRefreshToken(true);
ApplicationTypeProperties applicationTypeProperties = tenantApplicationTypeService.getProperties(tenantApplicationType);
realmRepresentation.setRefreshTokenMaxReuse(applicationTypeProperties.getRefreshTokenMaxReuse());
realmRepresentation.getAttributes().put("actionTokenGeneratedByUserLifespan.idp-verify-account-via-email", Integer.toString(86400));
if (!StringUtils.isEmpty(generalConfigurationModel.getAuxiliaryName())) {
setDisplayName(realmRepresentation, applicationTypeProperties.getApplicationName() + " (" + generalConfigurationModel.getAuxiliaryName() + ")");
setDisplayName(realmRepresentation, tenantUserManagementProperties.getApplicationName() + " (" + generalConfigurationModel.getAuxiliaryName() + ")");
} else {
setDisplayName(realmRepresentation, applicationTypeProperties.getApplicationName());
setDisplayName(realmRepresentation, tenantUserManagementProperties.getApplicationName());
}
try {

View File

@ -1,37 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.service;
import java.util.Optional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.knecon.fforesight.tenantusermanagement.entity.GlobalSMTPConfigurationEntity;
import com.knecon.fforesight.tenantusermanagement.repository.GlobalSMTPConfigurationRepository;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
@Service
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
public class GlobalSMTPConfigurationPersistenceService {
GlobalSMTPConfigurationRepository smtpConfigurationRepository;
@Transactional(readOnly = true)
public Optional<GlobalSMTPConfigurationEntity> get() {
return smtpConfigurationRepository.findSingleton();
}
@Transactional
public GlobalSMTPConfigurationEntity createUpdate(GlobalSMTPConfigurationEntity smtpConfiguration) {
smtpConfiguration.setId("singleton");
return smtpConfigurationRepository.save(smtpConfiguration);
}
}

View File

@ -9,8 +9,6 @@ import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.springframework.stereotype.Component;
import com.knecon.fforesight.tenantcommons.TenantApplicationType;
import com.knecon.fforesight.tenantusermanagement.properties.ApplicationTypeProperties;
import com.knecon.fforesight.tenantusermanagement.properties.TenantUserManagementProperties;
import lombok.RequiredArgsConstructor;
@ -23,26 +21,24 @@ public class KeyCloakRoleManagerService {
private final RealmService realmService;
private final TenantUserManagementProperties tenantUserManagementProperties;
private final TenantApplicationTypeService tenantApplicationTypeService;
public void updateRoles(String tenantId, TenantApplicationType applicationType) {
public void updateRoles(String tenantId) {
var realm = realmService.realm(tenantId);
ApplicationTypeProperties applicationTypeProperties = tenantApplicationTypeService.getProperties(applicationType);
log.info("Running KeyCloak Role Manager, managing client: {} with system client {}",
applicationTypeProperties.getApplicationClientId(),
tenantUserManagementProperties.getClientId());
tenantUserManagementProperties.getApplicationClientId(),
tenantUserManagementProperties.getClientId());
var existingRoles = realm.roles().list().stream().map(RoleRepresentation::getName).collect(Collectors.toList());
log.info("Existing KC roles: {}", existingRoles);
var redactionClientRepresentation = getRedactionClientRepresentation(tenantId, applicationTypeProperties.getApplicationClientId());
var redactionClientRepresentation = getRedactionClientRepresentation(tenantId);
var redactionClient = realm.clients().get(redactionClientRepresentation.getId());
var clientRoles = redactionClient.roles().list().stream().map(RoleRepresentation::getName).collect(Collectors.toList());
var allPermissions = applicationTypeProperties.getKcRoleMapping().getPermissions();
var allPermissions = tenantUserManagementProperties.getKcRoleMapping().getPermissions();
log.info("Existing KC client roles: {}", clientRoles);
log.info("Current Application KC client roles: {}", allPermissions);
@ -69,8 +65,8 @@ public class KeyCloakRoleManagerService {
var allClientRoles = redactionClient.roles().list();
var allRoles = applicationTypeProperties.getKcRoleMapping().getAllRoles();
var rolePermissionMappings = applicationTypeProperties.getKcRoleMapping().getRolePermissionMapping();
var allRoles = tenantUserManagementProperties.getKcRoleMapping().getAllRoles();
var rolePermissionMappings = tenantUserManagementProperties.getKcRoleMapping().getRolePermissionMapping();
// if an application-role doesn't exist, create it
for (String applicationRole : allRoles) {
@ -97,7 +93,7 @@ public class KeyCloakRoleManagerService {
log.info("Finished application role {}", applicationRole);
}
var composites = applicationTypeProperties.getKcRoleMapping().getRoleComposites();
var composites = tenantUserManagementProperties.getKcRoleMapping().getRoleComposites();
for (var key : composites.keySet()) {
var realmRole = realm.roles().get(key).toRepresentation();
@ -115,8 +111,9 @@ public class KeyCloakRoleManagerService {
}
private ClientRepresentation getRedactionClientRepresentation(String tenantId, String applicationClientId) {
private ClientRepresentation getRedactionClientRepresentation(String tenantId) {
String applicationClientId = tenantUserManagementProperties.getApplicationClientId();
var clientRepresentationIterator = realmService.realm(tenantId).clients().findByClientId(applicationClientId).iterator();
if (clientRepresentationIterator.hasNext()) {

View File

@ -1,14 +1,12 @@
package com.knecon.fforesight.tenantusermanagement.service;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.representations.idm.RealmRepresentation;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.knecon.fforesight.tenantcommons.model.AuthDetails;
import com.knecon.fforesight.tenantusermanagement.properties.TenantUserManagementProperties;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -21,15 +19,12 @@ public class RealmService {
private final TenantUserManagementProperties tenantUserManagementProperties;
public RealmResource realm(String tenantId) {
return keycloak.getAdminClient().realm(tenantId);
}
public String getEmail(RealmResource resource) {
var user = resource.users().list().stream().filter(userRepresentation -> userRepresentation.getUsername().equals("admin")).findFirst();
return user.isPresent() ? user.get().getEmail() : "";
}
public AuthDetails getOpenIdConnectDetails(String tenantId) {

View File

@ -1,258 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.iqser.red.service.persistence.service.v1.api.shared.model.license.Feature;
import com.iqser.red.service.persistence.service.v1.api.shared.model.license.RedactionLicenseModel;
import com.knecon.fforesight.tenantcommons.EncryptionDecryptionService;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantusermanagement.client.LicenseClient;
import com.knecon.fforesight.tenantusermanagement.entity.GlobalSMTPConfigurationEntity;
import com.knecon.fforesight.tenantusermanagement.entity.TenantEntity;
import com.knecon.fforesight.tenantusermanagement.model.SMTPConfiguration;
import com.knecon.fforesight.tenantusermanagement.repository.TenantRepository;
import com.knecon.fforesight.tenantusermanagement.utils.SMTPConfigurationMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
@RequiredArgsConstructor
public class SMTPService {
private final GlobalSMTPConfigurationPersistenceService smtpConfigurationPersistenceService;
private final EnvironmentSMTPConfigurationProvider environmentSMTPConfigurationProvider;
private final LicenseClient licenseClient;
private final RealmService realmService;
private final TenantRepository tenantRepository;
private final EncryptionDecryptionService encryptionDecryptionService;
private final ObjectMapper objectMapper;
private final static String SMTP_PASSWORD_KEY = "FFORESIGHT_SMTP_PASSWORD";
private final static String DEFAULT_PASSWORD = "**********";
public static final String CONFIGURABLE_SMTP_SERVER_FEATURE = "configurableSMTPServer";
@EventListener(ApplicationReadyEvent.class)
public void synchronizeSMTPConfigurations() {
log.info("Starting SMTP configuration synchronization...");
try {
List<TenantEntity> tenants = tenantRepository.findAll();
log.info("Retrieved {} tenants for SMTP synchronization.", tenants.size());
Optional<GlobalSMTPConfigurationEntity> optionalLatestGlobalConfigEntity = smtpConfigurationPersistenceService.get();
if (optionalLatestGlobalConfigEntity.isEmpty()) {
log.info("Global SMTP configuration was newly added. Initializing all tenant SMTP configurations.");
initializeGlobalSmtpConfig(tenants);
} else {
updateGlobalSmtpConfig(optionalLatestGlobalConfigEntity.get(), tenants);
}
log.info("SMTP configuration synchronization completed successfully.");
} catch (Exception e) {
log.error("Failed to synchronize SMTP configurations: {}", e.getMessage(), e);
}
}
private void initializeGlobalSmtpConfig(List<TenantEntity> tenants) {
SMTPConfiguration currentGlobalConfig = environmentSMTPConfigurationProvider.get();
initializeTenantsSmtpConfig(tenants, currentGlobalConfig);
currentGlobalConfig.setPassword(encryptionDecryptionService.encrypt(currentGlobalConfig.getPassword()));
GlobalSMTPConfigurationEntity updatedGlobalConfig = SMTPConfigurationMapper.toEntity(currentGlobalConfig);
smtpConfigurationPersistenceService.createUpdate(updatedGlobalConfig);
}
private void updateGlobalSmtpConfig(GlobalSMTPConfigurationEntity latestGlobalConfigEntity, List<TenantEntity> tenants) {
SMTPConfiguration latestGlobalConfig = SMTPConfigurationMapper.toModel(latestGlobalConfigEntity);
latestGlobalConfig.setPassword(encryptionDecryptionService.decrypt(latestGlobalConfig.getPassword()));
log.info("Existing global SMTP configuration was loaded.");
// Generate the latest SMTP config from environment variables and compare it to the last/saved global config
SMTPConfiguration currentGlobalConfig = environmentSMTPConfigurationProvider.get();
if (!currentGlobalConfig.equals(latestGlobalConfig)) {
log.info("Environment SMTP configuration has changed. Updating global SMTP configuration.");
updateTenantsSmtpConfig(tenants, latestGlobalConfig, currentGlobalConfig);
currentGlobalConfig.setPassword(encryptionDecryptionService.encrypt(currentGlobalConfig.getPassword()));
GlobalSMTPConfigurationEntity updatedGlobalConfig = SMTPConfigurationMapper.toEntity(currentGlobalConfig);
smtpConfigurationPersistenceService.createUpdate(updatedGlobalConfig);
} else {
log.info("No changes detected in environment SMTP configuration.");
}
}
private void initializeTenantsSmtpConfig(List<TenantEntity> tenants, SMTPConfiguration currentGlobalConfig) {
tenants.forEach(tenant -> processTenantSmtpConfig(tenant, currentGlobalConfig, null, true));
}
private void updateTenantsSmtpConfig(List<TenantEntity> tenants, SMTPConfiguration latestGlobalConfig, SMTPConfiguration currentGlobalConfig) {
tenants.forEach(tenant -> processTenantSmtpConfig(tenant, currentGlobalConfig, latestGlobalConfig, false));
}
private void processTenantSmtpConfig(TenantEntity tenant, SMTPConfiguration currentGlobalConfig, SMTPConfiguration latestGlobalConfig, boolean isInitialization) {
String tenantId = tenant.getTenantId();
log.info("Processing SMTP configuration for tenant: {}", tenantId);
try {
TenantContext.setTenantId(tenantId);
SMTPConfiguration tenantSMTPConfig = getSMTPConfiguration();
tenantSMTPConfig.setId("singleton");
updatePassword(tenantSMTPConfig);
if (!StringUtils.isBlank(tenantSMTPConfig.getPassword())) {
tenantSMTPConfig.setPassword(encryptionDecryptionService.decrypt(tenantSMTPConfig.getPassword()));
}
if (isInitialization) {
if (StringUtils.isBlank(tenantSMTPConfig.getHost())) {
log.info("Tenant '{}' SMTP configuration has not been yet set.", tenantId);
updateSMTPConfiguration(currentGlobalConfig);
log.info("Tenant '{}' SMTP configuration set successfully.", tenantId);
} else {
log.info("Tenant '{}' SMTP configuration was already set. No action taken.", tenantId);
}
} else {
if (tenantSMTPConfig.equals(latestGlobalConfig)) {
log.info("Tenant '{}' SMTP configuration matches global. Updating to latest environment configuration.", tenantId);
updateSMTPConfiguration(currentGlobalConfig);
log.info("Tenant '{}' SMTP configuration updated successfully.", tenantId);
} else {
log.info("Tenant '{}' SMTP configuration differs from global. No action taken.", tenantId);
}
}
} catch (Exception e) {
log.error("Error processing SMTP configuration for tenant '{}': {}", tenantId, e.getMessage());
} finally {
TenantContext.clear();
}
}
public SMTPConfiguration getSMTPConfiguration() {
var realm = realmService.realm(TenantContext.getTenantId()).toRepresentation();
return objectMapper.convertValue(realm.getSmtpServer(), SMTPConfiguration.class);
}
public Map<String, String> convertSMTPConfigToMap(SMTPConfiguration smtpConfiguration) {
updatePassword(smtpConfiguration);
smtpConfiguration.setPassword(encryptionDecryptionService.decrypt(smtpConfiguration.getPassword()));
return convertSMTPConfigurationModelToMap(smtpConfiguration);
}
public boolean canUpdateSMTPConfig() {
RedactionLicenseModel licenseModel = licenseClient.getLicense();
String activeLicenseId = licenseModel.getActiveLicense();
return licenseModel.getLicenses()
.stream()
.filter(license -> license.getId().equals(activeLicenseId))
.flatMap(license -> license.getFeatures()
.stream())
.filter(feature -> CONFIGURABLE_SMTP_SERVER_FEATURE.equals(feature.getName()))
.map(Feature::getValue)
.filter(Boolean.class::isInstance)
.map(Boolean.class::cast)
.findFirst()
.orElse(false);
}
public void createDefaultSMTPConfiguration() {
SMTPConfiguration defaultConfig = environmentSMTPConfigurationProvider.get();
updateSMTPConfiguration(defaultConfig);
}
public void updateSMTPConfiguration(SMTPConfiguration smtpConfigurationModel) {
String tenantId = TenantContext.getTenantId();
var realmRepresentation = realmService.realm(tenantId).toRepresentation();
var propertiesMap = convertSMTPConfigurationModelToMap(smtpConfigurationModel);
realmRepresentation.setSmtpServer(propertiesMap);
if (smtpConfigurationModel.getPassword() != null && !smtpConfigurationModel.getPassword().matches("\\**")) {
realmRepresentation.getAttributesOrEmpty().put(SMTP_PASSWORD_KEY, encryptionDecryptionService.encrypt(smtpConfigurationModel.getPassword()));
}
realmService.realm(tenantId).update(realmRepresentation);
}
public void clearSMTPConfiguration() {
var realmRepresentation = realmService.realm(TenantContext.getTenantId()).toRepresentation();
realmRepresentation.setSmtpServer(new HashMap<>());
realmRepresentation.getAttributesOrEmpty().remove(SMTP_PASSWORD_KEY);
realmService.realm(TenantContext.getTenantId()).update(realmRepresentation);
}
private Map<String, String> convertSMTPConfigurationModelToMap(SMTPConfiguration smtpConfigurationModel) {
Map<String, Object> propertiesMap = objectMapper.convertValue(smtpConfigurationModel, new TypeReference<>() {
});
Map<String, String> stringPropertiesMap = new HashMap<>();
propertiesMap.forEach((key, value) -> {
if (value != null) {
stringPropertiesMap.put(key, value.toString());
} else {
stringPropertiesMap.put(key, "");
}
});
return stringPropertiesMap;
}
private void updatePassword(SMTPConfiguration smtpConfiguration) {
if (DEFAULT_PASSWORD.equals(smtpConfiguration.getPassword())) {
try {
var password = realmService.realm(TenantContext.getTenantId()).toRepresentation().getAttributesOrEmpty().getOrDefault(SMTP_PASSWORD_KEY, "");
smtpConfiguration.setPassword(password);
} catch (Exception e) {
log.info("No current SMTP Config exists", e);
}
} else {
smtpConfiguration.setPassword(encryptionDecryptionService.encrypt(smtpConfiguration.getPassword()));
}
}
}

View File

@ -1,54 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.service;
import java.util.Locale;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import com.knecon.fforesight.tenantcommons.TenantApplicationType;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantusermanagement.properties.ApplicationTypeProperties;
import com.knecon.fforesight.tenantusermanagement.properties.TenantUserManagementProperties;
import com.knecon.fforesight.tenantusermanagement.repository.TenantRepository;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
@Service
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
public class TenantApplicationTypeService {
TenantUserManagementProperties tenantUserManagementProperties;
TenantRepository tenantRepository;
public TenantApplicationType getCurrent() {
return get(TenantContext.getTenantId());
}
public TenantApplicationType get(String tenantId) {
return tenantRepository.findApplicationTypeByTenantId(tenantId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Tenant does not exist"));
}
public ApplicationTypeProperties getProperties(TenantApplicationType applicationType) {
return tenantUserManagementProperties.getApplicationTypes()
.get(applicationType.name().toLowerCase(Locale.ROOT));
}
public ApplicationTypeProperties getCurrentProperties() {
TenantApplicationType applicationType = get(TenantContext.getTenantId());
return getProperties(applicationType);
}
}

View File

@ -1,10 +1,11 @@
package com.knecon.fforesight.tenantusermanagement.service;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantcommons.TenantProvider;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -22,7 +23,7 @@ public class UserCacheBuilder {
try {
tenantManagementService.getTenants().forEach(tenant -> userService.getAllUsers(tenant.getTenantId()));
} catch (Exception e) {
}catch (Exception e){
log.debug("Cold start");
}
}

View File

@ -14,6 +14,7 @@ import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Service;
import com.knecon.fforesight.tenantusermanagement.model.User;
import com.knecon.fforesight.tenantusermanagement.properties.TenantUserManagementProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -25,7 +26,7 @@ public class UserListingService {
private final RealmService realmService;
private final TenantApplicationTypeService tenantApplicationTypeService;
private final TenantUserManagementProperties tenantUserManagementProperties;
private final RetryTemplate retryTemplate = RetryTemplate.builder().maxAttempts(3).exponentialBackoff(1000, 2, 5000).build();
@ -40,10 +41,10 @@ public class UserListingService {
Map<String, Set<String>> usersByRole = new HashMap<>();
if (!allUsers.isEmpty()) {
var realmRoles = realm.roles().list().stream().map(r -> r.getName().toUpperCase(Locale.ROOT)).collect(Collectors.toSet());
var allRoles = tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping().getAllRoles();
var allRoles = tenantUserManagementProperties.getKcRoleMapping().getAllRoles();
for (var role : allRoles) {
if (realmRoles.contains(role)) {
List<UserRepresentation> users = realm.roles().get(role).getUserMembers(0, 500);
Set<UserRepresentation> users = realm.roles().get(role).getRoleUserMembers(0, 500);
usersByRole.put(role, users.stream().map(UserRepresentation::getId).collect(Collectors.toSet()));
}
}
@ -70,7 +71,7 @@ public class UserListingService {
users.add(user);
}
var roleComposites = tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping().getRoleComposites();
var roleComposites = tenantUserManagementProperties.getKcRoleMapping().getRoleComposites();
users.forEach(user -> {
for (var parentRole : roleComposites.keySet()) {
if (user.getRoles().contains(parentRole)) {

View File

@ -1,5 +1,6 @@
package com.knecon.fforesight.tenantusermanagement.service;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@ -8,6 +9,11 @@ import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import org.apache.commons.validator.routines.EmailValidator;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.internal.ResteasyClientBuilderImpl;
@ -39,14 +45,9 @@ import com.knecon.fforesight.tenantusermanagement.model.ResetPasswordRequest;
import com.knecon.fforesight.tenantusermanagement.model.UpdateMyProfileRequest;
import com.knecon.fforesight.tenantusermanagement.model.UpdateProfileRequest;
import com.knecon.fforesight.tenantusermanagement.model.User;
import com.knecon.fforesight.tenantusermanagement.permissions.ApplicationRoles;
import com.knecon.fforesight.tenantusermanagement.properties.TenantUserManagementProperties;
import io.micrometer.common.util.StringUtils;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.core.Response;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -59,7 +60,6 @@ public class UserService {
private final TenantUserManagementProperties tenantUserManagementProperties;
private final UserListingService userListingService;
private final RabbitTemplate rabbitTemplate;
private final TenantApplicationTypeService tenantApplicationTypeService;
@Value("${fforesight.user-exchange.name}")
private String userExchangeName;
@ -74,20 +74,20 @@ public class UserService {
@CacheEvict(value = "${commons.keycloak.userCache}", allEntries = true, beforeInvocation = true)
public User createUser(CreateUserRequest user) {
if (StringUtils.isEmpty(user.getEmail())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Email address must be set");
}
String username = StringUtils.isEmpty(user.getUsername()) ? user.getEmail() : user.getUsername();
if (!this.getTenantUsersResource().search(username, true).isEmpty() || !this.getTenantUsersResource().searchByEmail(user.getEmail(), true).isEmpty()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Requested username or email address not available");
if (!this.getTenantUsersResource().search(username).isEmpty()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "User with this username already exists");
}
if (!EmailValidator.getInstance().isValid(user.getEmail())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Email address format is not valid");
throw new ResponseStatusException(HttpStatus.CONFLICT, "Email address format is not valid");
}
// also search by email in case the username was provided at creation
if (!StringUtils.isEmpty(user.getUsername()) && !this.getTenantUsersResource().searchByEmail(user.getEmail(), true).isEmpty()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "User with this email already exists");
}
tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping().validateRoles(user.getRoles());
tenantUserManagementProperties.getKcRoleMapping().validateRoles(user.getRoles());
UserRepresentation userRepresentation = new UserRepresentation();
userRepresentation.setUsername(username);
@ -96,13 +96,11 @@ public class UserService {
userRepresentation.setFirstName(user.getFirstName());
userRepresentation.setLastName(user.getLastName());
checkRankOrderForAssigningRole(user.getRoles(), this.getUserRoles(KeycloakSecurity.getUserId()));
try (var response = this.getTenantUsersResource().create(userRepresentation)) {
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
if (response.getStatusInfo().getStatusCode() == 409) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, response.getStatusInfo().getReasonPhrase());
throw new ResponseStatusException(HttpStatus.CONFLICT, response.getStatusInfo().getReasonPhrase());
}
if (response.getStatusInfo().getStatusCode() == 400) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, response.getStatusInfo().getReasonPhrase());
@ -112,12 +110,10 @@ public class UserService {
var createdUser = getUserByUsername(username);
if (user.isSendSetPasswordMail()) {
try {
sendResetPasswordEmail(createdUser.getUserId());
} catch (Exception e) {
log.debug("Set Password E-mail could not be sent!", e);
}
try {
sendResetPasswordEmail(createdUser.getUserId());
} catch (Exception e) {
log.debug("Activation E-mail could not be sent!", e);
}
this.rabbitTemplate.convertAndSend(userExchangeName, "user.created", new UserCreatedEvent(createdUser, KeycloakSecurity.getUserId()));
@ -131,186 +127,101 @@ public class UserService {
}
private void sendResetPasswordEmail(String userId) {
public void checkRankOrderForAssigningRole(Set<String> newRoles, Set<String> currentUserRoles) {
var roleMapping = tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping();
var maxRank = currentUserRoles.stream()
.map(r -> roleMapping.getRole(r).getRank())
.max(Integer::compare)
.orElse(-1);
var newRolesRank = newRoles.stream()
.map(r -> roleMapping.getRole(r).getRank())
.toList();
var maxNewRolesRank = newRolesRank.stream()
.max(Integer::compare)
.orElse(-1);
if (maxNewRolesRank > maxRank) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cannot assign this role to that user. Insufficient rights");
try {
this.getTenantUsersResource().get(userId).executeActionsEmail(Collections.singletonList("UPDATE_PASSWORD"), 86400);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed to send email", e);
}
}
public Set<String> getUserRoles(String userId) {
var userResource = getUserResource(userId);
return userResource.roles().realmLevel().listEffective()
.stream()
.map(RoleRepresentation::getName)
.filter(r -> tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping().isValidRole(r))
.collect(Collectors.toSet());
}
@CacheEvict(value = "${commons.keycloak.userCache}", allEntries = true, beforeInvocation = true)
public User setRoles(String userId, Set<String> roles) {
var currentUserRoles = this.getUserRoles(KeycloakSecurity.getUserId());
Set<String> oldRoles = getRoles(userId);
if (!userId.equalsIgnoreCase(KeycloakSecurity.getUserId()) && !oldRoles.isEmpty() && oldRoles.stream()
.allMatch(ApplicationRoles::isKneconRole)) {
throw new NotFoundException("User with id: " + userId + " does not exist");
}
return setRoles(userId, roles, currentUserRoles);
}
@CacheEvict(value = "${commons.keycloak.userCache}", allEntries = true, beforeInvocation = true)
public User setRoles(String userId, Set<String> newRoles, Set<String> currentUserRoles) {
var allRoles = tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping().getAllRoles();
var allRoles = tenantUserManagementProperties.getKcRoleMapping().getAllRoles();
newRoles.forEach(role -> {
if (!allRoles.contains(role) || ApplicationRoles.isKneconRole(role)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid role: " + role);
}
});
var userResource = getUserResource(userId);
var oldRoles = userResource.roles().realmLevel().listEffective()
.stream()
.map(RoleRepresentation::getName)
.collect(Collectors.toSet());
validateSufficientRoles(userId, oldRoles, newRoles, currentUserRoles);
var currentRolesAsRoleRepresentation = allRoles.stream()
.map(this::getRoleRepresentation)
.collect(Collectors.toList());
var newMappedRoles = newRoles.stream()
.map(this::getRoleRepresentation)
.collect(Collectors.toList());
userResource.roles().realmLevel().remove(currentRolesAsRoleRepresentation);
userResource.roles().realmLevel().add(newMappedRoles);
var userWithNewRoles = getUserByUsername(userResource.toRepresentation().getUsername());
this.rabbitTemplate.convertAndSend(userExchangeName, "user.rolesUpdated", (new UserRolesUpdatedEvent(userWithNewRoles, oldRoles, newRoles, KeycloakSecurity.getUserId())));
return userWithNewRoles;
}
@CacheEvict(value = "${commons.keycloak.userCache}", allEntries = true, beforeInvocation = true)
public void removeRolesForDeletion(String userId, Set<String> roles) {
var allRoles = tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping().getAllRoles();
roles.forEach(role -> {
if (!allRoles.contains(role)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid role: " + role);
}
});
var userResource = getUserResource(userId);
var userRoles = userResource.roles().realmLevel().listEffective().stream().map(RoleRepresentation::getName).collect(Collectors.toSet());
var currentRolesAsRoleRepresentation = roles.stream()
.map(this::getRoleRepresentation)
.collect(Collectors.toList());
var roleMapping = tenantUserManagementProperties.getKcRoleMapping();
var maxRank = currentUserRoles.stream().map(r -> roleMapping.getRole(r).getRank()).max(Integer::compare).orElse(-1);
var newRolesRank = newRoles.stream().map(r -> roleMapping.getRole(r).getRank()).toList();
var maxNewRolesRank = newRolesRank.stream().max(Integer::compare).orElse(-1);
userResource.roles().realmLevel().remove(currentRolesAsRoleRepresentation);
}
@CacheEvict(value = "${commons.keycloak.userCache}", allEntries = true, beforeInvocation = true)
public void validateSufficientRoles(String userId, Set<String> userRoles, Set<String> newRoles, Set<String> currentUserRoles) {
var roleMapping = tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping();
int maxCurrentUserRank = currentUserRoles.stream()
.map(r -> roleMapping.getRole(r).getRank())
.max(Integer::compare)
.orElse(-1);
Set<String> untouchableRoles = userRoles.stream()
var untouchableRoles = userRoles.stream()
.filter(roleMapping::isValidRole)
.map(roleMapping::getRole)
.filter(r -> r.getRank() > maxCurrentUserRank && !ApplicationRoles.isKneconRole(r.getName()))
.filter(r -> r.getRank() > maxRank)
.map(KCRole::getName)
.collect(Collectors.toSet());
Set<String> kneconRoles = userRoles.stream()
.filter(roleMapping::isValidRole)
.map(roleMapping::getRole)
.map(KCRole::getName)
.filter(ApplicationRoles::isKneconRole)
.collect(Collectors.toSet());
int maxNewRolesRank = newRoles.stream()
.map(r -> roleMapping.getRole(r).getRank())
.max(Integer::compare)
.orElse(-1);
newRoles.addAll(kneconRoles);
int maxNewRolesRankIncludingKnecon = newRoles.stream()
.map(r -> roleMapping.getRole(r).getRank())
.max(Integer::compare)
.orElse(-1);
ensureNoHigherRankAssigned(maxCurrentUserRank, maxNewRolesRank);
ensureUntouchableRolesPreserved(untouchableRoles, newRoles);
ensureHighestRankNotRemovedFromSelf(userId, maxCurrentUserRank, maxNewRolesRankIncludingKnecon, roleMapping.getMaxRank());
}
private void ensureNoHigherRankAssigned(int maxCurrentUserRank, int maxNewRolesRank) {
if (maxNewRolesRank > maxCurrentUserRank) {
if (maxNewRolesRank > maxRank) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cannot assign this role to that user. Insufficient rights");
}
}
private void ensureUntouchableRolesPreserved(Set<String> untouchableRoles, Set<String> newRoles) {
if (!newRoles.containsAll(untouchableRoles)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cannot modify some roles for this user. Insufficient rights");
}
if (userId.equals(KeycloakSecurity.getUserId()) && maxRank.equals(roleMapping.getMaxRank()) && !maxNewRolesRank.equals(maxRank)) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Cannot remove highest ranking role from self.");
}
var currentRolesAsRoleRepresentation = allRoles.stream().map(this::getRoleRepresentation).collect(Collectors.toList());
var newMappedRoles = newRoles.stream().map(this::getRoleRepresentation).collect(Collectors.toList());
userResource.roles().realmLevel().remove(currentRolesAsRoleRepresentation);
userResource.roles().realmLevel().add(newMappedRoles);
var userWithNewRoles = getUserByUsername(userResource.toRepresentation().getUsername());
this.rabbitTemplate.convertAndSend(userExchangeName, "user.rolesUpdated", (new UserRolesUpdatedEvent(userWithNewRoles, userRoles, newRoles, KeycloakSecurity.getUserId())));
return userWithNewRoles;
}
private void ensureHighestRankNotRemovedFromSelf(String userId, int maxCurrentUserRank, int maxNewRolesRankIncludingKnecon, int overallMaxRank) {
@CacheEvict(value = "${commons.keycloak.userCache}", allEntries = true, beforeInvocation = true)
public User setRoles(String userId, Set<String> roles) {
boolean isSelf = userId.equalsIgnoreCase(KeycloakSecurity.getUserId());
boolean isUserHighestRank = maxCurrentUserRank == overallMaxRank;
boolean highestRankRemoved = !Integer.valueOf(maxNewRolesRankIncludingKnecon).equals(maxCurrentUserRank);
var currentUserResource = getUserResource(KeycloakSecurity.getUserId());
var currentUserRoles = currentUserResource.roles().realmLevel().listEffective().stream().map(RoleRepresentation::getName).collect(Collectors.toSet());
currentUserRoles = currentUserRoles.stream().filter(r -> tenantUserManagementProperties.getKcRoleMapping().isValidRole(r)).collect(Collectors.toSet());
if (isSelf && isUserHighestRank && highestRankRemoved) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Cannot remove highest ranking role from self.");
var userWithNewRoles = setRoles(userId, roles, currentUserRoles);
return userWithNewRoles;
}
private RoleRepresentation getRoleRepresentation(String role) {
RoleRepresentation realmRole;
try {
realmRole = realmService.realm(TenantContext.getTenantId()).roles().get(role).toRepresentation();
} catch (NotFoundException e) {
log.warn("The realm role {} is not found.", role);
throw new NotFoundException("The realm role " + role + " is not found.", e);
}
return realmRole;
}
public Optional<User> getUserById(String userId) {
return userListingService.getAllUsers(TenantContext.getTenantId())
.stream()
.filter(u -> u.getUserId().equalsIgnoreCase(userId))
.findAny();
return userListingService.getAllUsers(TenantContext.getTenantId()).stream().filter(u -> u.getUserId().equalsIgnoreCase(userId)).findAny();
}
public List<User> getUsersByIds(Collection<String> userIds) {
return userListingService.getAllUsers(TenantContext.getTenantId()).stream().filter(u -> userIds.contains(u.getUserId())).collect(Collectors.toList());
}
@ -338,16 +249,12 @@ public class UserService {
user.update(userRepresentation);
} catch (ClientErrorException e) {
if (e.getResponse().getStatus() == 409) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "E-mail is not available");
throw new ResponseStatusException(HttpStatus.CONFLICT, "E-mail already in use");
}
throw e;
}
var updatedProfile = getUserByUsername(userRepresentation.getUsername());
updatedProfile.setRoles(updatedProfile.getRoles()
.stream()
.filter(ApplicationRoles::isNoKneconRole)
.collect(Collectors.toSet()));
this.rabbitTemplate.convertAndSend(userExchangeName, "user.ownProfileUpdated", (new UserUpdatedOwnProfileEvent(updatedProfile)));
@ -361,8 +268,7 @@ public class UserService {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No id provided.");
}
try {
return this.getTenantUsersResource()
.get(userId);
return this.getTenantUsersResource().get(userId);
} catch (NotFoundException e) {
throw new NotFoundException("User with id: " + userId + " does not exist", e);
}
@ -381,19 +287,19 @@ public class UserService {
.realm(TenantContext.getTenantId())
.username(username)
.password(password)
.clientId(tenantApplicationTypeService.getCurrentProperties().getApplicationClientId())
.clientId(tenantUserManagementProperties.getApplicationClientId())
.grantType(OAuth2Constants.PASSWORD)
.resteasyClient(new ResteasyClientBuilderImpl().connectionTTL(2, TimeUnit.SECONDS)
.hostnameVerification(ResteasyClientBuilder.HostnameVerificationPolicy.ANY)
.connectionPoolSize(tenantUserManagementProperties.getConnectionPoolSize())
.disableTrustManager()
.build())
.hostnameVerification(ResteasyClientBuilder.HostnameVerificationPolicy.ANY)
.connectionPoolSize(tenantUserManagementProperties.getConnectionPoolSize())
.disableTrustManager()
.build())
.build();
try {
changeEmailClient.tokenManager().getAccessTokenString();
} catch (NotAuthorizedException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Could not confirm credentials");
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
}
changeEmailClient.close();
@ -411,26 +317,15 @@ public class UserService {
private User getUserByUsername(String username) {
var userList = this.getTenantUsersResource().search(username, true);
var userList = this.getTenantUsersResource().search(username);
if (userList.isEmpty()) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "User with this username already exists");
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User with this username already exists");
}
return convert(userList.iterator().next());
}
private boolean userExists(String userId) {
try {
getTenantUsersResource().get(userId).toRepresentation();
return true;
} catch (NotFoundException e) {
return false;
}
}
private UsersResource getTenantUsersResource() {
return realmService.realm(TenantContext.getTenantId()).users();
@ -442,7 +337,7 @@ public class UserService {
var user = userListingService.convertBasicUser(userRepresentation);
user.setRoles(getRoles(user.getUserId()));
var roleComposites = tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping().getRoleComposites();
var roleComposites = tenantUserManagementProperties.getKcRoleMapping().getRoleComposites();
for (var parentRole : roleComposites.keySet()) {
if (user.getRoles().contains(parentRole)) {
user.getRoles().addAll(roleComposites.get(parentRole));
@ -454,17 +349,13 @@ public class UserService {
private Set<String> getRoles(String id) {
List<RoleRepresentation> realmMappings = this.getTenantUsersResource()
.get(id).roles().getAll().getRealmMappings();
List<RoleRepresentation> realmMappings = this.getTenantUsersResource().get(id).roles().getAll().getRealmMappings();
if (realmMappings == null) {
log.warn("User with id=" + id + " contains null role mappings.");
return new TreeSet<>();
}
var allRoles = tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping().getAllRoles();
return realmMappings.stream()
.map(RoleRepresentation::getName)
.filter(allRoles::contains)
.collect(Collectors.toSet());
var allRoles = tenantUserManagementProperties.getKcRoleMapping().getAllRoles();
return realmMappings.stream().map(RoleRepresentation::getName).filter(allRoles::contains).collect(Collectors.toSet());
}
@ -475,30 +366,23 @@ public class UserService {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Cannot delete self");
}
if (!userExists(userId)) {
return;
}
var status = validateExecutionForDeletion(KeycloakSecurity.getUserId(), userId);
if (status.equals(ValidationResult.FORBIDDEN)) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "It is not allowed to delete a user with higher ranking roles");
} else if (status.equals(ValidationResult.INVALID)) {
return;
}
var currentUserResource = getUserResource(KeycloakSecurity.getUserId());
var currentRoles = getRoles(currentUserResource.toRepresentation().getId());
var userResource = getUserResource(userId);
var userToBeRemoved = getUserByUsername(userResource.toRepresentation().getUsername());
var userRoles = getRoles(userId);
if (status.equals(ValidationResult.ROLE_REMOVAL)) {
removeRolesForDeletion(userId,
getRoles(userId).stream()
.filter(ApplicationRoles::isNoKneconRole)
.collect(Collectors.toSet()));
} else {
userResource.remove();
var roleMapping = tenantUserManagementProperties.getKcRoleMapping();
var maxRank = currentRoles.stream().map(r -> roleMapping.getRole(r).getRank()).max(Integer::compare).orElse(-1);
var toDeleteUserMaxRank = userRoles.stream().map(r -> roleMapping.getRole(r).getRank()).max(Integer::compare).orElse(-1);
if (toDeleteUserMaxRank > maxRank) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "It is not allowed to delete a user with higher ranking roles");
}
var userToBeRemoved = getUserByUsername(userResource.toRepresentation().getUsername());
userResource.remove();
this.rabbitTemplate.convertAndSend(userExchangeName, "user.deleted", (new UserRemovedEvent(userToBeRemoved, KeycloakSecurity.getUserId())));
}
@ -510,12 +394,6 @@ public class UserService {
var user = this.getUserResource(userId);
var userRepresentation = user.toRepresentation();
Set<String> currentRoles = getRoles(userId);
if (!userExists(userId) || !currentRoles.isEmpty() && currentRoles.stream()
.allMatch(ApplicationRoles::isKneconRole)) {
throw new NotFoundException("User with id: " + userId + " does not exist");
}
if (userRepresentation.getFederatedIdentities() != null && !userRepresentation.getFederatedIdentities().isEmpty() && !updateProfileRequest.getEmail()
.equals(userRepresentation.getEmail())) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "It is not allowed to change the email from a federated identity");
@ -535,10 +413,6 @@ public class UserService {
setRoles(userId, updateProfileRequest.getRoles());
var updatedUser = getUserByUsername(userRepresentation.getUsername());
updatedUser.setRoles(updatedUser.getRoles()
.stream()
.filter(ApplicationRoles::isNoKneconRole)
.collect(Collectors.toSet()));
this.rabbitTemplate.convertAndSend(userExchangeName, "user.updated", (new UserUpdatedEvent(updatedUser, KeycloakSecurity.getUserId())));
@ -548,16 +422,6 @@ public class UserService {
public User activateProfile(String userId, boolean isActive) {
if (!userId.equalsIgnoreCase(KeycloakSecurity.getUserId())) {
var status = validateExecution(KeycloakSecurity.getUserId(), userId);
if (status.equals(ValidationResult.FORBIDDEN)) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "It is not allowed to activate/deactivate a user with higher ranking roles");
} else if (status.equals(ValidationResult.INVALID)) {
throw new NotFoundException("User with id: " + userId + " does not exist");
}
}
var user = this.getUserResource(userId);
var userRepresentation = user.toRepresentation();
@ -565,45 +429,28 @@ public class UserService {
user.update(userRepresentation);
var currentRoles = getRoles(userId);
if (isActive && currentRoles.isEmpty()) { // add RED_USER role
setRoles(userId, tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping().getDefaultRoles());
setRoles(userId, tenantUserManagementProperties.getKcRoleMapping().getDefaultRoles());
}
var toggledUser = getUserByUsername(userRepresentation.getUsername());
toggledUser.setRoles(toggledUser.getRoles()
.stream()
.filter(ApplicationRoles::isNoKneconRole)
.collect(Collectors.toSet()));
this.rabbitTemplate.convertAndSend(userExchangeName, "user.statusChanged", (new UserStatusToggleEvent(toggledUser, KeycloakSecurity.getUserId())));
return toggledUser;
return convert(this.getTenantUsersResource().get(userId).toRepresentation());
}
public void resetPassword(String userId, ResetPasswordRequest resetPasswordRequest) {
if (!userId.equalsIgnoreCase(KeycloakSecurity.getUserId())) {
var status = validateExecution(KeycloakSecurity.getUserId(), userId);
if (status.equals(ValidationResult.FORBIDDEN)) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "It is not allowed to reset the password of a user with higher ranking roles");
} else if (status.equals(ValidationResult.INVALID)) {
throw new NotFoundException("User with id: " + userId + " does not exist");
}
}
try {
CredentialRepresentation request = new CredentialRepresentation();
request.setType(CredentialRepresentation.PASSWORD);
request.setType("password");
request.setTemporary(resetPasswordRequest.isTemporary());
request.setValue(resetPasswordRequest.getPassword());
realmService.realm(TenantContext.getTenantId()).users()
.get(userId).resetPassword(request);
log.info("User {} resetted password for user {}", KeycloakSecurity.getUserId(), userId);
realmService.realm(TenantContext.getTenantId()).users().get(userId).resetPassword(request);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Could not reset password. It does not match the password policy.", e);
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed to send email", e);
}
}
@ -613,92 +460,4 @@ public class UserService {
return userListingService.getAllUsers(TenantContext.getTenantId());
}
private RoleRepresentation getRoleRepresentation(String role) {
RoleRepresentation realmRole;
try {
realmRole = realmService.realm(TenantContext.getTenantId()).roles()
.get(role).toRepresentation();
} catch (NotFoundException e) {
log.warn("The realm role {} is not found.", role);
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "The realm role " + role + " is not found.", e);
}
return realmRole;
}
private void sendResetPasswordEmail(String userId) {
try {
this.getTenantUsersResource()
.get(userId).executeActionsEmail(Collections.singletonList("UPDATE_PASSWORD"), 86400);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed to send email.", e);
}
}
private enum ValidationResult {
ALLOWED,
FORBIDDEN,
INVALID,
ROLE_REMOVAL
}
private ValidationResult validateExecution(String executingUserId, String targetUserId) {
var currentUserResource = getUserResource(executingUserId);
var currentRoles = getRoles(currentUserResource.toRepresentation().getId());
var userRoles = getRoles(targetUserId);
return validateRoleRanks(currentRoles, userRoles);
}
private ValidationResult validateExecutionForDeletion(String executingUserId, String targetUserId) {
var currentUserResource = getUserResource(executingUserId);
var currentRoles = getRoles(currentUserResource.toRepresentation().getId());
var userRoles = getRoles(targetUserId);
ValidationResult validationResult = validateRoleRanks(currentRoles, userRoles);
if (validationResult == ValidationResult.ALLOWED) {
if (userRoles.stream()
.anyMatch(ApplicationRoles::isKneconRole) && userRoles.stream()
.anyMatch(ApplicationRoles::isNoKneconRole)) {
return ValidationResult.ROLE_REMOVAL;
}
}
return validationResult;
}
private ValidationResult validateRoleRanks(Set<String> currentRoles, Set<String> userRoles) {
if (!userRoles.isEmpty() && userRoles.stream()
.allMatch(ApplicationRoles::isKneconRole)) {
return ValidationResult.INVALID;
}
var roleMapping = tenantApplicationTypeService.getCurrentProperties().getKcRoleMapping();
var maxRank = currentRoles.stream()
.map(r -> roleMapping.getRole(r).getRank())
.max(Integer::compare)
.orElse(-1);
var targetRank = userRoles.stream()
.filter(ApplicationRoles::isNoKneconRole)
.map(r -> roleMapping.getRole(r).getRank())
.max(Integer::compare)
.orElse(-1);
if (targetRank <= maxRank) {
return ValidationResult.ALLOWED;
} else {
return ValidationResult.FORBIDDEN;
}
}
}

View File

@ -1,179 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.utils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import com.knecon.fforesight.databasetenantcommons.providers.utils.MagicConverter;
import com.knecon.fforesight.tenantusermanagement.model.ExtensibleModel;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderConfigModel;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderModel;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderNameIDPolicyFormat;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderPrincipalType;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderRequest;
import com.knecon.fforesight.tenantusermanagement.model.IdentityProviderWithDescriptorRequest;
import lombok.SneakyThrows;
public class IdentityProviderMappingService {
public static IdentityProviderRepresentation toRepresentationFromRequest(IdentityProviderRequest identityProviderRequest) {
return toRepresentationFromModel(toModelFromRequest(identityProviderRequest));
}
public static IdentityProviderModel toModelFromRequest(IdentityProviderRequest identityProviderRequest) {
if (!identityProviderRequest.getConfig().getWantAuthnRequestsSigned()) {
identityProviderRequest.getConfig().setXmlSigKeyInfoKeyNameTransformer(null);
identityProviderRequest.getConfig().setSignatureAlgorithm(null);
}
return MagicConverter.convert(identityProviderRequest, IdentityProviderModel.class, getModelFromRequestDeltaMapper());
}
private static BiConsumer<IdentityProviderRequest, IdentityProviderModel> getModelFromRequestDeltaMapper() {
return ((identityProviderRequest, identityProviderModel) -> {
var identityProviderConfigModel = MagicConverter.convert(identityProviderRequest.getConfig(), IdentityProviderConfigModel.class);
identityProviderModel.setConfig(identityProviderConfigModel);
});
}
public static IdentityProviderRepresentation toRepresentationFromModel(IdentityProviderModel identityProviderModel) {
return MagicConverter.convert(identityProviderModel, IdentityProviderRepresentation.class, getModelToRepresentationDeltaMapper());
}
private static BiConsumer<IdentityProviderModel, IdentityProviderRepresentation> getModelToRepresentationDeltaMapper() {
return ((identityProviderModel, identityProviderRepresentation) -> identityProviderRepresentation.setConfig(convertObjectToMap(identityProviderModel.getConfig())));
}
public static IdentityProviderModel toModelFromDescriptorRequestAndConfig(IdentityProviderWithDescriptorRequest identityProvider, Map<String, String> configurationsMap) {
IdentityProviderModel identityProviderModel = MagicConverter.convert(identityProvider, IdentityProviderModel.class);
identityProviderModel.setConfig(convertMapToObject(configurationsMap, IdentityProviderConfigModel.class));
return identityProviderModel;
}
@SneakyThrows
public static Map<String, String> convertObjectToMap(Object obj) {
Map<String, String> resultMap = new HashMap<>();
Class<?> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getter = pd.getReadMethod();
Object fieldValue = getter.invoke(obj);
if (fieldValue != null) {
resultMap.put(field.getName(), fieldValue.toString());
}
}
return resultMap;
}
public static IdentityProviderModel toModelFromRepresentation(IdentityProviderRepresentation identityProviderRepresentation) {
return MagicConverter.convert(identityProviderRepresentation, IdentityProviderModel.class, getRepresentationToModelDeltaMapper());
}
private static BiConsumer<IdentityProviderRepresentation, IdentityProviderModel> getRepresentationToModelDeltaMapper() {
return ((identityProviderRepresentation, identityProviderModel) -> identityProviderModel.setConfig(convertMapToObject(identityProviderRepresentation.getConfig(),
IdentityProviderConfigModel.class)));
}
@SneakyThrows
public static <T extends ExtensibleModel> T convertMapToObject(Map<String, String> map, Class<T> clazz) {
T obj = clazz.getDeclaredConstructor().newInstance();
Field[] fields = clazz.getDeclaredFields();
sanitizeMapKeys(map);
for (Field field : fields) {
String fieldName = field.getName();
if (map.containsKey(fieldName)) {
String fieldValue = map.get(fieldName);
setFieldValue(obj, field, fieldValue);
map.remove(fieldName);
}
}
obj.setNotMappedFields(map);
return obj;
}
private static void sanitizeMapKeys(Map<String, String> inputMap) {
var keys = new ArrayList<>(inputMap.keySet());
for (String key : keys) {
String sanitizedKey = sanitize(key);
if (!sanitizedKey.equals(key)) {
String value = inputMap.remove(key);
inputMap.put(sanitizedKey, value);
}
}
}
private static String sanitize(String input) {
StringBuilder result = new StringBuilder();
String[] segments = input.split("\\.");
for (String segment : segments) {
if (!result.isEmpty()) {
result.append(Character.toUpperCase(segment.charAt(0)));
result.append(segment.substring(1));
} else {
result.append(segment);
}
}
return result.toString();
}
@SneakyThrows
private static <T> void setFieldValue(T obj, Field field, String value) {
Class<?> fieldType = field.getType();
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), obj.getClass());
Method setter = pd.getWriteMethod();
if (fieldType == String.class) {
setter.invoke(obj, value);
} else if (fieldType == int.class || fieldType == Integer.class) {
setter.invoke(obj, Integer.parseInt(value));
} else if (fieldType == boolean.class || fieldType == Boolean.class) {
setter.invoke(obj, Boolean.parseBoolean(value));
} else if (fieldType == IdentityProviderNameIDPolicyFormat.class) {
setter.invoke(obj, IdentityProviderNameIDPolicyFormat.fromRepresentation(value));
} else if (fieldType == IdentityProviderPrincipalType.class) {
setter.invoke(obj, IdentityProviderPrincipalType.fromStringValue(value));
} else if (fieldType.isEnum()) {
Enum<?> enumValue = Enum.valueOf(fieldType.asSubclass(Enum.class), value);
setter.invoke(obj, enumValue);
}
}
}

View File

@ -13,7 +13,7 @@ import lombok.SneakyThrows;
@Converter
public class JSONMapConverter implements AttributeConverter<Map<String, Object>, String> {
private static final ObjectMapper objectMapper = new ObjectMapper();
private final ObjectMapper objectMapper = new ObjectMapper();
@SneakyThrows

View File

@ -13,7 +13,7 @@ import lombok.SneakyThrows;
@Converter
public class JSONStringSetConverter implements AttributeConverter<Set<String>, String> {
private final static ObjectMapper objectMapper = new ObjectMapper();
private final ObjectMapper objectMapper = new ObjectMapper();
@SneakyThrows

View File

@ -1,60 +0,0 @@
package com.knecon.fforesight.tenantusermanagement.utils;
import com.knecon.fforesight.tenantusermanagement.entity.GlobalSMTPConfigurationEntity;
import com.knecon.fforesight.tenantusermanagement.model.SMTPConfiguration;
import lombok.experimental.UtilityClass;
@UtilityClass
public final class SMTPConfigurationMapper {
public static GlobalSMTPConfigurationEntity toEntity(SMTPConfiguration smtpConfig) {
if (smtpConfig == null) {
return null;
}
return GlobalSMTPConfigurationEntity.builder()
.id("singleton")
.auth(smtpConfig.isAuth())
.envelopeFrom(smtpConfig.getEnvelopeFrom())
.fromEmail(smtpConfig.getFrom())
.fromDisplayName(smtpConfig.getFromDisplayName())
.host(smtpConfig.getHost())
.password(smtpConfig.getPassword())
.port(smtpConfig.getPort())
.replyTo(smtpConfig.getReplyTo())
.replyToDisplayName(smtpConfig.getReplyToDisplayName())
.ssl(smtpConfig.isSsl())
.starttls(smtpConfig.isStarttls())
.userName(smtpConfig.getUser())
.build();
}
public static SMTPConfiguration toModel(GlobalSMTPConfigurationEntity entity) {
if (entity == null) {
return null;
}
SMTPConfiguration smtpConfig = new SMTPConfiguration();
smtpConfig.setId(entity.getId());
smtpConfig.setAuth(entity.getAuth() != null && entity.getAuth());
smtpConfig.setEnvelopeFrom(entity.getEnvelopeFrom());
smtpConfig.setFrom(entity.getFromEmail());
smtpConfig.setFromDisplayName(entity.getFromDisplayName());
smtpConfig.setHost(entity.getHost());
smtpConfig.setPassword(entity.getPassword());
smtpConfig.setPort(entity.getPort());
smtpConfig.setReplyTo(entity.getReplyTo());
smtpConfig.setReplyToDisplayName(entity.getReplyToDisplayName());
smtpConfig.setSsl(entity.getSsl() != null && entity.getSsl());
smtpConfig.setStarttls(entity.getStarttls() != null && entity.getStarttls());
smtpConfig.setUser(entity.getUserName());
return smtpConfig;
}
}

View File

@ -0,0 +1,35 @@
server:
port: 8091
fforesight:
tenant-user-management:
server-url: http://localhost:8080
client-secret: oE2DVrV45w0Tr5jBBcoufVxIkFWU69lP
client-id: manager
realm: master
kc-role-mapping:
roles:
- name: SUPER_USER
set-by-default: true
rank: 100
permissions:
- 'fforesight-read-general-configuration'
- 'fforesight-write-general-configuration'
- 'fforesight-manage-user-preferences'
- 'fforesight-read-users'
- 'fforesight-read-all-users'
- 'fforesight-write-users'
- 'fforesight-update-my-profile'
- 'fforesight-create-tenant'
- 'fforesight-get-tenants'
- 'fforesight-update-tenant'
- 'fforesight-deployment-info'
- 'fforesight-read-smtp-configuration'
- 'fforesight-write-smtp-configuration'
springdoc:
auth-server-url: http://localhost:8080
cors.enabled: true

View File

@ -1,93 +0,0 @@
server:
port: 8091
fforesight:
tenant-user-management:
server-url: http://localhost:8080
client-secret: p2InUtjQUDSlwsXyEUFuYrSWi1BeZD1P
client-id: manager
realm: master
application-types:
redactmanager:
kc-role-mapping:
roles:
- name: SUPER_USER
set-by-default: true
rank: 100
permissions:
- 'fforesight-read-general-configuration'
- 'fforesight-write-general-configuration'
- 'fforesight-manage-user-preferences'
- 'fforesight-read-users'
- 'fforesight-read-all-users'
- 'fforesight-write-users'
- 'fforesight-update-my-profile'
- 'fforesight-create-tenant'
- 'fforesight-get-tenants'
- 'fforesight-delete-tenant'
- 'fforesight-update-tenant'
- 'fforesight-deployment-info'
- 'fforesight-read-smtp-configuration'
- 'fforesight-write-smtp-configuration'
- 'fforesight-read-identity-provider-config'
- 'fforesight-write-identity-provider-config'
- name: KNECON_ADMIN
set-by-default: true
rank: 1000
permissions:
- 'fforesight-read-general-configuration'
- 'fforesight-write-general-configuration'
- 'fforesight-manage-user-preferences'
- 'fforesight-read-users'
- 'fforesight-read-all-users'
- 'fforesight-write-users'
- 'fforesight-update-my-profile'
- 'fforesight-create-tenant'
- 'fforesight-get-tenants'
- 'fforesight-update-tenant'
- 'fforesight-deployment-info'
- 'fforesight-read-smtp-configuration'
- 'fforesight-write-smtp-configuration'
- 'fforesight-read-identity-provider-config'
- 'fforesight-write-identity-provider-config'
- name: KNECON_SUPPORT
set-by-default: true
rank: 1000
permissions:
- 'fforesight-read-general-configuration'
- 'fforesight-write-general-configuration'
- 'fforesight-manage-user-preferences'
- 'fforesight-read-users'
- 'fforesight-read-all-users'
- 'fforesight-write-users'
- 'fforesight-update-my-profile'
- 'fforesight-create-tenant'
- 'fforesight-get-tenants'
- 'fforesight-update-tenant'
- 'fforesight-deployment-info'
- 'fforesight-read-smtp-configuration'
- 'fforesight-write-smtp-configuration'
- 'fforesight-read-identity-provider-config'
- 'fforesight-write-identity-provider-config'
application-name: "redaction"
springdoc:
auth-server-url: http://localhost:8080
dev.tenant.storage:
mode: 'S3'
s3:
key: minioadmin
secret: minioadmin
bucket: redaction
endpoint: http://localhost:9000
dev.tenant.db:
port: 5432
host: localhost
database: master
schema: public
username: fforesight
password: fforesight
cors.enabled: true

View File

@ -0,0 +1,53 @@
fforesight:
tenant-user-management:
application-client-id: 'redaction'
application-name: 'RedactManager'
client-id: 'manager'
tenant-access-token-life-span: 300
realm: master
default-theme: 'scm'
valid-redirect-uris: [ '/redaction-gateway-v1/*','/tenant-user-management/*','http://localhost:4200/*','/ui/*' ,'/auth/*' ]
kc-role-mapping:
unmappedPermissions: [ "red-unarchive-dossier", "red-update-license", "fforesight-create-tenant", "fforesight-update-tenant" ]
compositeRoles:
- name: RED_MANAGER
composites:
- name: RED_USER
- name: RED_ADMIN
composites:
- name: RED_USER_ADMIN
roles:
- name: RED_USER
set-by-default: true
rank: 100
permissions: [ "red-get-tables", "red-get-rss", "red-add-comment", "red-read-license", "red-read-app-configuration", "red-read-dossier-status", "red-add-dossier-dictionary-entry", "red-add-redaction", "red-add-update-dossier-dictionary-type",
"red-delete-comment", "red-delete-dossier-dictionary-entry", "red-delete-dossier-dictionary-type", "red-delete-file", "red-delete-manual-redaction", "red-download-annotated-file",
"red-download-original-file", "red-download-redacted-file", "red-download-redaction-preview-file", "red-download-report-template", "red-exclude-include-file",
"red-exclude-include-pages", "red-get-report-templates", "fforesight-manage-user-preferences", "red-manage-viewed-pages", "red-process-download", "red-process-manual-redaction-request",
"red-read-colors", "red-read-dictionary-types", "red-read-digital-signature", "red-read-dossier", "red-read-dossier-attributes", "red-read-dossier-attributes-config",
"red-read-dossier-templates", "red-read-download-status", "red-read-file-attributes-config", "red-read-file-status", "fforesight-read-general-configuration", "red-read-legal-basis",
"red-read-manual-redactions", "red-read-notification", "red-read-redaction-log", "red-read-rules", "fforesight-read-users", "red-read-versions", "red-reanalyze-dossier",
"red-reanalyze-file", "red-request-redaction", "red-rotate-page", "red-search", "red-search-audit-log", "red-set-reviewer", "red-set-status-approved", "red-set-status-under-approval",
"fforesight-update-my-profile", "red-update-notification", "red-upload-file", "red-write-file-attributes", "red-process-texthighlights", "red-get-highlights", "red-convert-highlights", "red-delete-highlights", "red-delete-imported-redactions" ]
- name: RED_ADMIN
set-by-default: false
rank: 800
permissions: [ "red-add-dictionary-entry", "red-add-update-dictionary-type", "red-write-dossier-status", "red-read-dossier-status", "red-delete-dictionary-entry", "red-delete-dictionary-type",
"red-delete-report-template", "red-download-report-template", "red-get-report-templates", "fforesight-manage-user-preferences", "red-read-colors", "red-read-dictionary-types",
"red-read-digital-signature", "red-read-dossier-attributes", "red-read-dossier-attributes-config", "red-read-dossier-templates", "red-read-file-attributes-config",
"red-read-legal-basis", "red-read-license-report", "red-read-notification", "red-read-rules", "fforesight-read-smtp-configuration", "red-read-versions", "red-reindex", "red-search-audit-log", "red-update-notification", "red-upload-report-template", "red-write-colors", "red-write-digital-signature", "red-write-dossier-attributes-config",
"red-write-dossier-templates", "red-write-file-attributes-config", "fforesight-write-general-configuration", "red-write-legal-basis", "red-write-rules", "fforesight-write-smtp-configuration", "red-write-app-configuration", "red-manage-acl-permissions", "fforesight-create-tenant", "fforesight-get-tenants", "fforesight-update-tenant", "fforesight-deployment-info" ]
- name: RED_MANAGER
set-by-default: false
rank: 200
permissions: [ "red-add-update-dossier", "red-archived-dossier", "red-delete-dossier", "red-write-dossier-attributes" ]
- name: RED_USER_ADMIN
set-by-default: false
rank: 400
permissions: [ "fforesight-manage-user-preferences", "fforesight-read-all-users", "red-read-dossier", "red-read-app-configuration", "fforesight-read-general-configuration",
"red-read-notification", "fforesight-read-users", "fforesight-update-my-profile", "red-update-notification", "fforesight-write-users", "red-read-license" ]
springdoc:
default-tenant: 'redaction'

Some files were not shown because too many files have changed in this diff Show More