Merge branch 'dmp-refactoring' of https://code-repo.d4science.org/MaDgiK-CITE/argos into dmp-refactoring

This commit is contained in:
Sofia Papacharalampous 2024-06-10 17:28:11 +03:00
commit 6d5b6f4859
30 changed files with 1701 additions and 773 deletions

View File

@ -20,7 +20,7 @@ public enum ActionConfirmationType implements DatabaseEnum<Short> {
@Override
@JsonValue
public Short getValue() {
return value;
return this.value;
}
private static final Map<Short, ActionConfirmationType> map = EnumUtils.getEnumValueMap(ActionConfirmationType.class);

View File

@ -536,9 +536,6 @@ public class UserServiceImpl implements UserService {
fieldInfoList.add(new FieldInfo("{userName}", DataType.String, currentUser.getName()));
fieldInfoList.add(new FieldInfo("{confirmationToken}", DataType.String, token));
fieldInfoList.add(new FieldInfo("{expiration_time}", DataType.String, this.secondsToTime(this.notificationProperties.getEmailExpirationTimeSeconds())));
if(this.tenantScope.getTenantCode() != null && !this.tenantScope.getTenantCode().equals(this.tenantScope.getDefaultTenantCode())){
fieldInfoList.add(new FieldInfo("{tenant-url-path}", DataType.String, String.format("/t/%s", this.tenantScope.getTenantCode())));
}
data.setFields(fieldInfoList);
event.setData(this.jsonHandlingService.toJsonSafe(data));
this.eventHandler.handle(event);
@ -563,9 +560,6 @@ public class UserServiceImpl implements UserService {
List<FieldInfo> fieldInfoList = new ArrayList<>();
fieldInfoList.add(new FieldInfo("{confirmationToken}", DataType.String, token));
fieldInfoList.add(new FieldInfo("{expiration_time}", DataType.String, this.secondsToTime(this.notificationProperties.getEmailExpirationTimeSeconds())));
if(this.tenantScope.getTenantCode() != null && !this.tenantScope.getTenantCode().equals(this.tenantScope.getDefaultTenantCode())){
fieldInfoList.add(new FieldInfo("{tenant-url-path}", DataType.String, String.format("/t/%s", this.tenantScope.getTenantCode())));
}
data.setFields(fieldInfoList);
event.setData(this.jsonHandlingService.toJsonSafe(data));
this.eventHandler.handle(event);
@ -579,9 +573,14 @@ public class UserServiceImpl implements UserService {
persist.setMergeAccountConfirmation(new MergeAccountConfirmationPersist());
persist.getMergeAccountConfirmation().setEmail(email);
persist.setExpiresAt(Instant.now().plusSeconds(this.notificationProperties.getEmailExpirationTimeSeconds()));
this.validatorFactory.validator(ActionConfirmationPersist.ActionConfirmationPersistValidator.class).validateForce(persist);
this.validatorFactory.validator(ActionConfirmationPersist.ActionConfirmationPersistValidator.class).validateForce(persist);
this.actionConfirmationService.persist(persist, null);
try {
this.entityManager.disableTenantFilters();
} finally {
this.entityManager.reloadTenantFilters();
}
return persist.getToken();
}
@ -593,9 +592,13 @@ public class UserServiceImpl implements UserService {
persist.setRemoveCredentialRequest(new RemoveCredentialRequestPersist());
persist.getRemoveCredentialRequest().setCredentialId(credentialId);
persist.setExpiresAt(Instant.now().plusSeconds(this.notificationProperties.getEmailExpirationTimeSeconds()));
this.validatorFactory.validator(ActionConfirmationPersist.ActionConfirmationPersistValidator.class).validateForce(persist);
this.actionConfirmationService.persist(persist, null);
this.validatorFactory.validator(ActionConfirmationPersist.ActionConfirmationPersistValidator.class).validateForce(persist);
try {
this.entityManager.disableTenantFilters();
this.actionConfirmationService.persist(persist, null);
} finally {
this.entityManager.reloadTenantFilters();
}
return persist.getToken();
}
@ -614,9 +617,14 @@ public class UserServiceImpl implements UserService {
}
public void confirmMergeAccount(String token) throws IOException, InvalidApplicationException {
ActionConfirmationEntity action = this.queryFactory.query(ActionConfirmationQuery.class).tokens(token).types(ActionConfirmationType.MergeAccount).isActive(IsActive.Active).first();
ActionConfirmationEntity action;
try {
this.entityManager.disableTenantFilters();
action = this.queryFactory.query(ActionConfirmationQuery.class).tokens(token).types(ActionConfirmationType.MergeAccount).isActive(IsActive.Active).first();
} finally {
this.entityManager.reloadTenantFilters();
}
if (action == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{token, ActionConfirmationEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
this.checkActionState(action);
MergeAccountConfirmationEntity mergeAccountConfirmationEntity = this.xmlHandlingService.fromXmlSafe(MergeAccountConfirmationEntity.class, action.getData());
@ -637,11 +645,17 @@ public class UserServiceImpl implements UserService {
this.mergeNewUserToOld(newUser, userToBeMerge);
}
action.setUpdatedAt(Instant.now());
action.setStatus(ActionConfirmationStatus.Accepted);
this.entityManager.merge(action);
this.entityManager.flush();
try {
this.entityManager.disableTenantFilters();
action.setUpdatedAt(Instant.now());
action.setStatus(ActionConfirmationStatus.Accepted);
this.entityManager.merge(action);
this.entityManager.flush();
} finally {
this.entityManager.reloadTenantFilters();
}
this.userTouchedIntegrationEventHandler.handle(newUser.getId());
this.userRemovalIntegrationEventHandler.handle(userToBeMerge.getId());
@ -805,9 +819,15 @@ public class UserServiceImpl implements UserService {
}
public void confirmRemoveCredential(String token) throws InvalidApplicationException {
ActionConfirmationEntity action = this.queryFactory.query(ActionConfirmationQuery.class).tokens(token).types(ActionConfirmationType.RemoveCredential).isActive(IsActive.Active).first();
ActionConfirmationEntity action;
try {
this.entityManager.disableTenantFilters();
action = this.queryFactory.query(ActionConfirmationQuery.class).tokens(token).types(ActionConfirmationType.RemoveCredential).isActive(IsActive.Active).first();
} finally {
this.entityManager.reloadTenantFilters();
}
if (action == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{token, ActionConfirmationEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
this.checkActionState(action);
RemoveCredentialRequestEntity removeCredentialRequestEntity = this.xmlHandlingService.fromXmlSafe(RemoveCredentialRequestEntity.class, action.getData());
@ -828,11 +848,17 @@ public class UserServiceImpl implements UserService {
}
this.deleterFactory.deleter(UserCredentialDeleter.class).delete(List.of(userCredentialEntity));
action.setUpdatedAt(Instant.now());
action.setStatus(ActionConfirmationStatus.Accepted);
this.entityManager.merge(action);
this.entityManager.flush();
try {
this.entityManager.disableTenantFilters();
action.setUpdatedAt(Instant.now());
action.setStatus(ActionConfirmationStatus.Accepted);
this.entityManager.merge(action);
this.entityManager.flush();
} finally {
this.entityManager.reloadTenantFilters();
}
this.userTouchedIntegrationEventHandler.handle(userCredentialEntity.getUserId());
@ -854,10 +880,16 @@ public class UserServiceImpl implements UserService {
}
}
private UserEntity getUserEntityFromToken(String token) throws MyForbiddenException, MyNotFoundException {
ActionConfirmationEntity action = this.queryFactory.query(ActionConfirmationQuery.class).tokens(token).types(ActionConfirmationType.MergeAccount).isActive(IsActive.Active).first();
private UserEntity getUserEntityFromToken(String token) throws MyForbiddenException, MyNotFoundException, InvalidApplicationException {
ActionConfirmationEntity action;
try {
this.entityManager.disableTenantFilters();
action = this.queryFactory.query(ActionConfirmationQuery.class).tokens(token).types(ActionConfirmationType.MergeAccount).isActive(IsActive.Active).first();
} finally {
this.entityManager.reloadTenantFilters();
}
if (action == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{token, ActionConfirmationEntity.class.getSimpleName()}, LocaleContextHolder.getLocale()));
this.checkActionState(action);
MergeAccountConfirmationEntity mergeAccountConfirmationEntity = this.xmlHandlingService.fromXmlSafe(MergeAccountConfirmationEntity.class, action.getData());

View File

@ -16,6 +16,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.xml.bind.JAXBException;
import org.opencdmp.audit.AuditableAction;
@ -24,6 +25,8 @@ import org.opencdmp.commons.enums.DmpAccessType;
import org.opencdmp.commons.enums.DmpStatus;
import org.opencdmp.commons.enums.IsActive;
import org.opencdmp.controllers.swagger.SwaggerHelpers;
import org.opencdmp.controllers.swagger.annotation.Swagger404;
import org.opencdmp.controllers.swagger.annotation.SwaggerErrorResponses;
import org.opencdmp.convention.ConventionService;
import org.opencdmp.data.StorageFileEntity;
import org.opencdmp.model.DescriptionValidationResult;
@ -72,6 +75,7 @@ import static org.opencdmp.authorization.AuthorizationFlags.Public;
@RestController
@RequestMapping(path = "api/description")
@Tag(name = "Descriptions", description = "Manage descriptions")
@SwaggerErrorResponses
public class DescriptionController {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionController.class));
@ -166,7 +170,24 @@ public class DescriptionController {
}
)
}
)
),
responses = {
@ApiResponse(
description = "OK",
responseCode = "200",
content = {
@Content(
examples = {
@ExampleObject(
name = "First page",
description = "Example with the first page of paginated results",
value = SwaggerHelpers.Description.endpoint_query_response_example
)
}
)
}
)
}
)
public QueryResult<Description> query(@RequestBody DescriptionLookup lookup) throws MyApplicationException, MyForbiddenException {
logger.debug("querying {}", Description.class.getSimpleName());
@ -183,6 +204,7 @@ public class DescriptionController {
@GetMapping("{id}")
@Operation(summary = "Fetch a specific description by id")
@Swagger404
public Description get(
@Parameter(name = "id", description = "The id of a description to fetch", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id,
@Parameter(name = "fieldSet", description = SwaggerHelpers.Commons.fieldset_description, required = true) FieldSet fieldSet
@ -207,6 +229,7 @@ public class DescriptionController {
@PostMapping("persist")
@Operation(summary = "Create a new or update an existing description")
@Swagger404
@Transactional
@ValidationFilterAnnotation(validator = DescriptionPersist.DescriptionPersistValidator.ValidatorName, argumentName = "model")
public Description persist(
@ -228,6 +251,7 @@ public class DescriptionController {
@PostMapping("persist-status")
@Operation(summary = "Update the status of an existing description")
@Swagger404
@Transactional
@ValidationFilterAnnotation(validator = DescriptionStatusPersist.DescriptionStatusPersistValidator.ValidatorName, argumentName = "model")
public Description persistStatus(
@ -281,6 +305,7 @@ public class DescriptionController {
@DeleteMapping("{id}")
@Operation(summary = "Delete a description by id")
@Swagger404
@Transactional
public void delete(
@Parameter(name = "id", description = "The id of a description to delete", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id
@ -294,6 +319,7 @@ public class DescriptionController {
@GetMapping("{id}/export/{type}")
@Operation(summary = "Export a description in various formats by id")
@Swagger404
public ResponseEntity<byte[]> export(
@Parameter(name = "id", description = "The id of a description to export", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id,
@Parameter(name = "type", description = "The type of the export", example = "rda", required = true) @PathVariable("type") String exportType
@ -305,6 +331,7 @@ public class DescriptionController {
@PostMapping("field-file/upload")
@Operation(summary = "Upload a file attachment on a field that supports it")
@Swagger404
@Transactional
@ValidationFilterAnnotation(validator = DescriptionFieldFilePersist.PersistValidator.ValidatorName, argumentName = "model")
public StorageFile uploadFieldFiles(
@ -327,6 +354,7 @@ public class DescriptionController {
@GetMapping("{id}/field-file/{fileId}")
@Operation(summary = "Fetch a field file attachment as byte array")
@Swagger404
public ResponseEntity<ByteArrayResource> getFieldFile(
@Parameter(name = "id", description = "The id of a description", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id,
@Parameter(name = "fileIid", description = "The id of the file we want to fetch", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("fileId") UUID fileId
@ -353,6 +381,7 @@ public class DescriptionController {
@PostMapping("update-description-template")
@Operation(summary = "Change the template of a description")
@Swagger404
@Transactional
@ValidationFilterAnnotation(validator = UpdateDescriptionTemplatePersist.UpdateDescriptionTemplatePersistValidator.ValidatorName, argumentName = "model")
public Boolean updateDescriptionTemplate(@RequestBody UpdateDescriptionTemplatePersist model) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, IOException, JAXBException {
@ -368,6 +397,7 @@ public class DescriptionController {
@RequestMapping(method = RequestMethod.GET, value = "/xml/export/{id}", produces = "application/xml")
@Operation(summary = "Export a description in xml format by id")
@Swagger404
public @ResponseBody ResponseEntity<byte[]> getXml(
@Parameter(name = "id", description = "The id of a description to export", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable UUID id
) throws JAXBException, ParserConfigurationException, IOException, InstantiationException, IllegalAccessException, SAXException, InvalidApplicationException {

View File

@ -25,6 +25,8 @@ import org.opencdmp.commons.enums.DmpAccessType;
import org.opencdmp.commons.enums.DmpStatus;
import org.opencdmp.commons.enums.IsActive;
import org.opencdmp.controllers.swagger.SwaggerHelpers;
import org.opencdmp.controllers.swagger.annotation.Swagger404;
import org.opencdmp.controllers.swagger.annotation.SwaggerErrorResponses;
import org.opencdmp.model.DescriptionsToBeFinalized;
import org.opencdmp.model.DmpUser;
import org.opencdmp.model.DmpValidationResult;
@ -66,6 +68,7 @@ import static org.opencdmp.authorization.AuthorizationFlags.Public;
@RestController
@RequestMapping(path = "api/dmp")
@Tag(name = "Plans", description = "Manage plans")
@SwaggerErrorResponses
public class DmpController {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpController.class));
@ -189,6 +192,7 @@ public class DmpController {
@GetMapping("{id}")
@Operation(summary = "Fetch a specific plan by id")
@Swagger404()
public Dmp Get(
@Parameter(name = "id", description = "The id of a plan to fetch", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id,
@Parameter(name = "fieldSet", description = SwaggerHelpers.Commons.fieldset_description, required = true) FieldSet fieldSet,
@ -213,6 +217,7 @@ public class DmpController {
@PostMapping("persist")
@Operation(summary = "Create a new or update an existing plan")
@Swagger404
@Transactional
@ValidationFilterAnnotation(validator = DmpPersist.DmpPersistValidator.ValidatorName, argumentName = "model")
public Dmp Persist(
@ -233,6 +238,7 @@ public class DmpController {
@DeleteMapping("{id}")
@Operation(summary = "Delete a plan by id")
@Swagger404
@Transactional
public void Delete(
@Parameter(name = "id", description = "The id of a plan to delete", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id
@ -246,6 +252,7 @@ public class DmpController {
@PostMapping("finalize/{id}")
@Operation(summary = "Finalize a plan by id")
@Swagger404
@Transactional
public boolean finalize(
@Parameter(name = "id", description = "The id of a plan to finalize", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id,
@ -265,6 +272,7 @@ public class DmpController {
@GetMapping("undo-finalize/{id}")
@Operation(summary = "Undo the finalization of a plan by id (only possible if it is not already deposited)")
@Swagger404
@Transactional
public boolean undoFinalize(
@Parameter(name = "id", description = "The id of a plan to revert the finalization", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id,
@ -302,6 +310,7 @@ public class DmpController {
@PostMapping("clone")
@Operation(summary = "Create a clone of an existing plan")
@Swagger404
@Transactional
@ValidationFilterAnnotation(validator = CloneDmpPersist.CloneDmpPersistValidator.ValidatorName, argumentName = "model")
public Dmp buildClone(
@ -324,6 +333,7 @@ public class DmpController {
@PostMapping("new-version")
@Operation(summary = "Create a new version of an existing plan")
@Swagger404
@Transactional
@ValidationFilterAnnotation(validator = NewVersionDmpPersist.NewVersionDmpPersistValidator.ValidatorName, argumentName = "model")
public Dmp createNewVersion(
@ -380,6 +390,7 @@ public class DmpController {
@GetMapping("{id}/export/{transformerId}/{type}")
@Operation(summary = "Export a plan in various formats by id")
@Swagger404
public ResponseEntity<byte[]> export(
@Parameter(name = "id", description = "The id of a plan to export", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id,
@PathVariable("transformerId") String transformerId,
@ -431,6 +442,7 @@ public class DmpController {
@RequestMapping(method = RequestMethod.GET, value = "/xml/export/{id}", produces = "application/xml")
@Operation(summary = "Export a plan in xml format by id")
@Swagger404
public @ResponseBody ResponseEntity<byte[]> getXml(
@Parameter(name = "id", description = "The id of a plan to export", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable UUID id
) throws JAXBException, ParserConfigurationException, IOException, InstantiationException, IllegalAccessException, SAXException, InvalidApplicationException {

View File

@ -0,0 +1,31 @@
package org.opencdmp.controllers.swagger.annotation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import java.lang.annotation.*;
import static org.opencdmp.controllers.swagger.SwaggerHelpers.Errors.message_403;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@ApiResponse(
description = "This is generally the response you should expect when you don't have sufficient permissions to perform an action.",
responseCode = "403",
content = {
@Content(
examples = {
@ExampleObject(
name = "404 response",
description = "This is the response in case of a 403 error.",
value = message_403
)
}
)
}
)
public @interface Swagger403 {
}

View File

@ -0,0 +1,31 @@
package org.opencdmp.controllers.swagger.annotation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import java.lang.annotation.*;
import static org.opencdmp.controllers.swagger.SwaggerHelpers.Errors.message_404;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@ApiResponse(
description = "This is generally the response you should expect when an entity is not found or you don't have sufficient permissions to view it.",
responseCode = "404",
content = {
@Content(
examples = {
@ExampleObject(
name = "404 response",
description = "This is the response in case of a 404 error where the first placeholder {0} will be replaced by the item id and the second one {1} by the item type.",
value = message_404
)
}
)
}
)
public @interface Swagger404 {
}

View File

@ -0,0 +1,31 @@
package org.opencdmp.controllers.swagger.annotation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import java.lang.annotation.*;
import static org.opencdmp.controllers.swagger.SwaggerHelpers.Errors.message_500;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
@ApiResponse(
description = "This is the response you should expect when an unexpected exception has occurred.",
responseCode = "500",
content = {
@Content(
examples = {
@ExampleObject(
name = "500 response",
description = "This is the response in case of an internal server error.",
value = message_500
)
}
)
}
)
public @interface Swagger500 {
}

View File

@ -0,0 +1,12 @@
package org.opencdmp.controllers.swagger.annotation;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Swagger500
@Swagger403
public @interface SwaggerErrorResponses {
}

View File

@ -1,23 +1,6 @@
package org.opencdmp.interceptors.user;
import org.opencdmp.authorization.AuthorizationProperties;
import org.opencdmp.authorization.ClaimNames;
import org.opencdmp.commons.JsonHandlingService;
import org.opencdmp.commons.enums.ContactInfoType;
import org.opencdmp.commons.enums.IsActive;
import org.opencdmp.commons.lock.LockByKeyManager;
import org.opencdmp.commons.scope.user.UserScope;
import org.opencdmp.commons.types.user.AdditionalInfoEntity;
import org.opencdmp.commons.types.usercredential.UserCredentialDataEntity;
import org.opencdmp.commons.locale.LocaleProperties;
import org.opencdmp.convention.ConventionService;
import org.opencdmp.data.*;
import org.opencdmp.integrationevent.outbox.usertouched.UserTouchedIntegrationEventHandler;
import org.opencdmp.model.UserContactInfo;
import org.opencdmp.model.usercredential.UserCredential;
import org.opencdmp.query.UserContactInfoQuery;
import org.opencdmp.query.UserCredentialQuery;
import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver;
import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractor;
import gr.cite.tools.data.query.QueryFactory;
@ -30,6 +13,23 @@ import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import org.apache.commons.validator.routines.EmailValidator;
import org.opencdmp.authorization.AuthorizationProperties;
import org.opencdmp.authorization.ClaimNames;
import org.opencdmp.commons.JsonHandlingService;
import org.opencdmp.commons.enums.ContactInfoType;
import org.opencdmp.commons.enums.IsActive;
import org.opencdmp.commons.locale.LocaleProperties;
import org.opencdmp.commons.lock.LockByKeyManager;
import org.opencdmp.commons.scope.user.UserScope;
import org.opencdmp.commons.types.user.AdditionalInfoEntity;
import org.opencdmp.commons.types.usercredential.UserCredentialDataEntity;
import org.opencdmp.convention.ConventionService;
import org.opencdmp.data.*;
import org.opencdmp.integrationevent.outbox.usertouched.UserTouchedIntegrationEventHandler;
import org.opencdmp.model.UserContactInfo;
import org.opencdmp.model.usercredential.UserCredential;
import org.opencdmp.query.UserContactInfoQuery;
import org.opencdmp.query.UserCredentialQuery;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
@ -66,6 +66,8 @@ public class UserInterceptor implements WebRequestInterceptor {
private final ConventionService conventionService;
@PersistenceContext
public EntityManager entityManager;
public final TenantEntityManager tenantEntityManager;
@Autowired
public UserInterceptor(
@ -77,7 +79,7 @@ public class UserInterceptor implements WebRequestInterceptor {
JsonHandlingService jsonHandlingService,
QueryFactory queryFactory,
LockByKeyManager lockByKeyManager,
LocaleProperties localeProperties, UserTouchedIntegrationEventHandler userTouchedIntegrationEventHandler, AuthorizationProperties authorizationProperties, ConventionService conventionService) {
LocaleProperties localeProperties, UserTouchedIntegrationEventHandler userTouchedIntegrationEventHandler, AuthorizationProperties authorizationProperties, ConventionService conventionService, TenantEntityManager tenantEntityManager) {
this.userScope = userScope;
this.currentPrincipalResolver = currentPrincipalResolver;
this.claimExtractor = claimExtractor;
@ -90,6 +92,7 @@ public class UserInterceptor implements WebRequestInterceptor {
this.userTouchedIntegrationEventHandler = userTouchedIntegrationEventHandler;
this.authorizationProperties = authorizationProperties;
this.conventionService = conventionService;
this.tenantEntityManager = tenantEntityManager;
}
@Override
@ -101,12 +104,14 @@ public class UserInterceptor implements WebRequestInterceptor {
UserInterceptorCacheService.UserInterceptorCacheValue cacheValue = this.userInterceptorCacheService.lookup(this.userInterceptorCacheService.buildKey(subjectId));
if (cacheValue != null && emailExistsToPrincipal(cacheValue.getProviderEmail()) && userRolesSynced(cacheValue.getRoles()) && providerExistsToPrincipal(cacheValue.getExternalProviderNames())) {
if (cacheValue != null && this.emailExistsToPrincipal(cacheValue.getProviderEmail()) && this.userRolesSynced(cacheValue.getRoles()) && this.providerExistsToPrincipal(cacheValue.getExternalProviderNames())) {
userId = cacheValue.getUserId();
} else {
boolean usedResource = false;
boolean shouldSendUserTouchedIntegrationEvent = false;
try {
this.tenantEntityManager.disableTenantFilters();
usedResource = this.lockByKeyManager.tryLock(subjectId, 5000, TimeUnit.MILLISECONDS);
String email = this.getEmailFromClaims();
@ -116,7 +121,7 @@ public class UserInterceptor implements WebRequestInterceptor {
definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = null;
try {
status = transactionManager.getTransaction(definition);
status = this.transactionManager.getTransaction(definition);
userId = this.findExistingUserFromDb(subjectId);
boolean isNewUser = userId == null;
@ -133,9 +138,9 @@ public class UserInterceptor implements WebRequestInterceptor {
}
this.entityManager.flush();
transactionManager.commit(status);
this.transactionManager.commit(status);
} catch (Exception ex) {
if (status != null) transactionManager.rollback(status);
if (status != null) this.transactionManager.rollback(status);
throw ex;
}
@ -151,6 +156,7 @@ public class UserInterceptor implements WebRequestInterceptor {
this.userInterceptorCacheService.put(cacheValue);
} finally {
if (usedResource) this.lockByKeyManager.unlock(subjectId);
this.tenantEntityManager.reloadTenantFilters();
}
if (shouldSendUserTouchedIntegrationEvent){
this.userTouchedIntegrationEventHandler.handle(userId);
@ -235,7 +241,7 @@ public class UserInterceptor implements WebRequestInterceptor {
}
private List<String> getRolesFromClaims() {
List<String> claimsRoles = this.claimExtractor.asStrings(currentPrincipalResolver.currentPrincipal(), ClaimNames.GlobalRolesClaimName);
List<String> claimsRoles = this.claimExtractor.asStrings(this.currentPrincipalResolver.currentPrincipal(), ClaimNames.GlobalRolesClaimName);
if (claimsRoles == null) claimsRoles = new ArrayList<>();
claimsRoles = claimsRoles.stream().filter(x -> x != null && !x.isBlank() && (this.conventionService.isListNullOrEmpty(this.authorizationProperties.getAllowedGlobalRoles()) || this.authorizationProperties.getAllowedGlobalRoles().contains(x))).distinct().toList();
claimsRoles = claimsRoles.stream().filter(x -> x != null && !x.isBlank()).distinct().toList();

View File

@ -10,7 +10,7 @@ keycloak-resources:
groupId: 88a65fff-dffe-474a-a461-252ff4230203
tenantAuthorities:
TenantAdmin:
parent: 1e650f57-8b7c-4f32-bf5b-e1a9147c597b
parent: 4453d854-4aea-4d19-af80-7f9d85e5a2c9
roleAttributeValueStrategy: 'TenantAdmin:{tenantCode}'
TenantUser:
parent: c7057c4d-e7dc-49ef-aa5d-02ad3a22bff8

View File

@ -188,7 +188,7 @@ export class AppComponent implements OnInit, AfterViewInit {
.subscribe((event: NavigationStart) => {
const enrichedUrl = this.tenantHandlingService.getUrlEnrichedWithTenantCode(event.url, this.authentication.selectedTenant() ?? 'default');
if (event.url != enrichedUrl) {
this.router.navigate([enrichedUrl]);
this.router.navigateByUrl(enrichedUrl);
}
});

View File

@ -1,6 +1,6 @@
import { DOCUMENT, LocationStrategy } from '@angular/common';
import { Inject, Injectable } from '@angular/core';
import { PRIMARY_OUTLET, Router, UrlSegment, UrlSegmentGroup, UrlTree } from '@angular/router';
import { PRIMARY_OUTLET, Router, UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree } from '@angular/router';
@Injectable()
export class TenantHandlingService {
@ -9,6 +9,7 @@ export class TenantHandlingService {
@Inject(DOCUMENT) private readonly document: Document,
private readonly locationStrategy: LocationStrategy,
private readonly router: Router,
private urlSerializer: UrlSerializer
) {
}
@ -25,16 +26,16 @@ export class TenantHandlingService {
getCurrentUrlEnrichedWithTenantCode(tenantCode: string, withOrigin: boolean) {
const path = this.getUrlEnrichedWithTenantCode(this.router.routerState.snapshot.url, tenantCode)
return withOrigin ? this.getBaseUrl() + path.substring(1) : path;
return withOrigin ? this.getBaseUrl() + path.toString().substring(1) : path;
}
getUrlEnrichedWithTenantCode(url: string, tenantCode: string) {
getUrlEnrichedWithTenantCode(url: string, tenantCode: string): string {
const urlTree: UrlTree = this.router.parseUrl(url);
const urlSegmentGroup: UrlSegmentGroup = urlTree.root.children[PRIMARY_OUTLET];
const urlSegments: UrlSegment[] = urlSegmentGroup.segments;
const urlSegments: UrlSegment[] = urlSegmentGroup?.segments;
const tenantParamIndex = urlSegments.findIndex(x => x.path == 't');
const tenantParamIndex = urlSegments?.findIndex(x => x.path == 't');
if (tenantParamIndex >= 0) {
if (tenantCode == 'default') {
@ -49,7 +50,7 @@ export class TenantHandlingService {
}
}
return urlTree.toString();
return this.urlSerializer.serialize(urlTree);
}
getBaseUrl(): string {

View File

@ -173,7 +173,7 @@ export class HybridListingComponent extends BaseComponent implements OnInit, OnC
this.resizeObserver?.unobserve(this.wrapperCard.nativeElement)
this.resizeObserver?.disconnect();
this.resizeObserver = null;
this.resizeSubject$.complete();
this.resizeSubject$?.complete();
}
private resizeObserver: ResizeObserver;

View File

@ -51,10 +51,14 @@ public class DataRepositoryMigrationService {
logger.debug("Migrate DataRepository " + page * PageSize + " of " + total);
for (DataRepository item : items) {
entityManager.detach(item);
if (item.getReference() == null || !item.getReference().contains(":")){
if (item.getReference() == null || item.getReference().isBlank()){
logger.warn("Reference generated because is null DataRepository " + item.getId());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
if (!item.getReference().contains(":")){
logger.warn("Reference generated because is not contains ':' DataRepository " + item.getId() + " reference " + item.getReference());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
eu.old.eudat.models.data.datarepository.DataRepositoryModel model = new eu.old.eudat.models.data.datarepository.DataRepositoryModel().fromDataModel(item);
String[] referenceParts = item.getReference().split(":", 2);

View File

@ -1,5 +1,6 @@
package eu.old.eudat.migration;
import eu.old.eudat.data.entities.DMP;
import org.opencdmp.commons.JsonHandlingService;
import org.opencdmp.commons.XmlHandlingService;
import org.opencdmp.commons.enums.*;
@ -194,7 +195,8 @@ public class DatasetMigrationService {
private List<DmpDescriptionTemplateEntity> getOrCreateDmpDescriptionTemplateEntity(Dataset item, UUID sectionId, UUID groupId, List<DmpDescriptionTemplateEntity> dmpDescriptionTemplateEntities){
List<DmpDescriptionTemplateEntity> itemDescriptionTemplates = dmpDescriptionTemplateEntities.stream().filter(x-> x.getDescriptionTemplateGroupId().equals(groupId) && x.getDmpId().equals(item.getDmp().getId()) && x.getSectionId().equals(sectionId)).toList();
if (itemDescriptionTemplates.isEmpty()) {
if (!item.getStatus().equals(Dataset.Status.DELETED.getValue())) logger.warn("Migrate Dataset " + item.getId() + " cannot found DmpDescriptionTemplateEntity for section " + item.getDmpSectionIndex());
boolean isDeleted = item.getStatus().equals(Dataset.Status.CANCELED.getValue()) ||item.getStatus().equals(Dataset.Status.DELETED.getValue()) || item.getDmp().getStatus().equals(DMP.DMPStatus.DELETED.getValue());
if (!isDeleted) logger.warn("Migrate Dataset " + item.getId() + " cannot found DmpDescriptionTemplateEntity for section " + item.getDmpSectionIndex());
if (dmpDescriptionTemplateEntities.stream().anyMatch(x -> x.getDmpId().equals(item.getDmp().getId()) && x.getSectionId().equals(sectionId))) {
DmpDescriptionTemplateEntity dmpDescriptionTemplateEntity = new DmpDescriptionTemplateEntity();
dmpDescriptionTemplateEntity.setId(UUID.randomUUID());
@ -203,7 +205,7 @@ public class DatasetMigrationService {
dmpDescriptionTemplateEntity.setCreatedAt(item.getCreated() != null ? item.getCreated().toInstant() : Instant.now());
dmpDescriptionTemplateEntity.setUpdatedAt(item.getModified() != null ? item.getModified().toInstant() : Instant.now());
dmpDescriptionTemplateEntity.setSectionId(sectionId);
dmpDescriptionTemplateEntity.setIsActive(!item.getStatus().equals(Dataset.Status.DELETED.getValue()) ? IsActive.Active : IsActive.Inactive);
dmpDescriptionTemplateEntity.setIsActive(!isDeleted ? IsActive.Active : IsActive.Inactive);
this.entityManager.persist(dmpDescriptionTemplateEntity);
this.entityManager.flush();
itemDescriptionTemplates = List.of(dmpDescriptionTemplateEntity);

View File

@ -40,10 +40,14 @@ public class ExternalDatasetMigrationService {
logger.debug("Migrate ExternalDataset " + page * PageSize + " of " + total);
for (ExternalDataset item : items) {
entityManager.detach(item);
if (item.getReference() == null || !item.getReference().contains(":")){
if (item.getReference() == null || item.getReference().isBlank()){
logger.warn("Reference generated because is null ExternalDataset " + item.getId());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
if (!item.getReference().contains(":")){
logger.warn("Reference generated because is not contains ':' ExternalDataset " + item.getId() + " reference " + item.getReference());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
eu.old.eudat.models.data.externaldataset.ExternalDatasetModel model = new eu.old.eudat.models.data.externaldataset.ExternalDatasetModel().fromDataModel(item);
String[] referenceParts = item.getReference().split(":", 2);

View File

@ -44,10 +44,14 @@ public class FunderMigrationService {
logger.debug("Migrate Funder " + page * PageSize + " of " + total);
for (Funder item : items) {
entityManager.detach(item);
if (item.getReference() == null || !item.getReference().contains(":")){
if (item.getReference() == null || item.getReference().isBlank()){
logger.warn("Reference generated because is null Funder " + item.getId());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
if (!item.getReference().contains(":")){
logger.warn("Reference generated because is not contains ':' Funder " + item.getId() + " reference " + item.getReference());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
eu.old.eudat.models.data.funder.Funder model = new eu.old.eudat.models.data.funder.Funder().fromDataModel(item);
String[] referenceParts = item.getReference().split(":", 2);

View File

@ -51,10 +51,14 @@ GrantMigrationService {
logger.debug("Migrate Grant " + page * PageSize + " of " + total);
for (Grant item : items) {
entityManager.detach(item);
if (item.getReference() == null || !item.getReference().contains(":")){
if (item.getReference() == null || item.getReference().isBlank()){
logger.warn("Reference generated because is null Grant " + item.getId());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
if (!item.getReference().contains(":")){
logger.warn("Reference generated because is not contains ':' Grant " + item.getId() + " reference " + item.getReference());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
String[] referenceParts = item.getReference().split(":", 2);
boolean isInternal = referenceParts[0].equals(InternalReferenceSource);

View File

@ -49,10 +49,14 @@ public class OrganizationMigrationService {
logger.debug("Migrate Organisation " + page * PageSize + " of " + total);
for (Organisation item : items) {
entityManager.detach(item);
if (item.getReference() == null || !item.getReference().contains(":")){
if (item.getReference() == null || item.getReference().isBlank()){
logger.warn("Reference generated because is null Organisation " + item.getId());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
if (!item.getReference().contains(":")){
logger.warn("Reference generated because is not contains ':' Organisation " + item.getId() + " reference " + item.getReference());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
eu.old.eudat.models.data.dmp.Organisation model = new eu.old.eudat.models.data.dmp.Organisation().fromDataModel(item);

View File

@ -50,10 +50,14 @@ public class ProjectMigrationService {
logger.debug("Migrate Project " + page * PageSize + " of " + total);
for (Project item : items) {
entityManager.detach(item);
if (item.getReference() == null || !item.getReference().contains(":")){
if (item.getReference() == null || item.getReference().isBlank()){
logger.warn("Reference generated because is null Project " + item.getId());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
if (!item.getReference().contains(":")){
logger.warn("Reference generated because is not contains ':' Project " + item.getId() + " reference " + item.getReference());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
eu.old.eudat.models.data.project.Project model = new eu.old.eudat.models.data.project.Project().fromDataModel(item);
String[] referenceParts = item.getReference().split(":", 2);

View File

@ -49,10 +49,14 @@ public class RegistryMigrationService {
logger.debug("Migrate Registry " + page * PageSize + " of " + total);
for (Registry item : items) {
entityManager.detach(item);
if (item.getReference() == null || !item.getReference().contains(":")){
if (item.getReference() == null || item.getReference().isBlank()){
logger.warn("Reference generated because is null Registry " + item.getId());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
if (!item.getReference().contains(":")){
logger.warn("Reference generated because is not contains ':' Registry " + item.getId() + " reference " + item.getReference());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
eu.old.eudat.models.data.registries.RegistryModel model = new eu.old.eudat.models.data.registries.RegistryModel().fromDataModel(item);
String[] referenceParts = item.getReference().split(":", 2);

View File

@ -50,10 +50,14 @@ public class ResearcherMigrationService {
logger.debug("Migrate Researcher " + page * PageSize + " of " + total);
for (Researcher item : items) {
entityManager.detach(item);
if (item.getReference() == null || !item.getReference().contains(":")){
if (item.getReference() == null || item.getReference().isBlank()){
logger.warn("Reference generated because is null Researcher " + item.getId());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
if (!item.getReference().contains(":")){
logger.warn("Reference generated because is not contains ':' Researcher " + item.getId() + " reference " + item.getReference());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
eu.old.eudat.models.data.dmp.Researcher model = new eu.old.eudat.models.data.dmp.Researcher().fromDataModel(item);
String[] referenceParts = item.getReference().split(":", 2);

View File

@ -48,10 +48,14 @@ public class ServiceMigrationService {
logger.debug("Migrate Service " + page * PageSize + " of " + total);
for (eu.old.eudat.data.entities.Service item : items) {
entityManager.detach(item);
if (item.getReference() == null || !item.getReference().contains(":")){
if (item.getReference() == null || item.getReference().isBlank()){
logger.warn("Reference generated because is null Service " + item.getId());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
if (!item.getReference().contains(":")){
logger.warn("Reference generated because is not contains ':' Service " + item.getId() + " reference " + item.getReference());
item.setReference(InternalReferenceSource + ":" + item.getId().toString().replace("-", "").toLowerCase(Locale.ROOT));
}
eu.old.eudat.models.data.services.ServiceModel model = new eu.old.eudat.models.data.services.ServiceModel().fromDataModel(item);
String[] referenceParts = item.getReference().split(":", 2);

View File

@ -175,6 +175,7 @@ public class MigrationController {
public boolean step3() throws IOException, JAXBException, ParserConfigurationException, InstantiationException, IllegalAccessException, SAXException, NoSuchFieldException, InvalidApplicationException, TransformerException, URISyntaxException {
//Description
this.datasetMigrationService.migrate();
// throw new InvalidApplicationException("");
this.datasetReferenceMigrationService.migrateDatasetReferences();
this.tagMigrationService.migrate();

View File

@ -208,8 +208,6 @@ notification:
optional:
- key: "{expiration_time}"
value: ---
- key: "{tenant-url-path}"
value:
formatting:
'[{userName}]': null
'[{installation-url}]': null
@ -235,8 +233,6 @@ notification:
value: email
- key: "{expiration_time}"
value: --
- key: "{tenant-url-path}"
value:
formatting:
'[{email}]': null
'[{tenant-url-path}]': null

View File

@ -271,7 +271,7 @@
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td> <a href="{installation-url}{tenant-url-path}/login/merge/confirmation/{confirmationToken}" target="_blank">Confirm Merge Request</a> </td>
<td> <a href="{installation-url}/login/merge/confirmation/{confirmationToken}" target="_blank">Confirm Merge Request</a> </td>
</tr>
</tbody>
</table>

View File

@ -9,6 +9,6 @@
<h2>User {userName} have sent you a merge Request.</h2>
<p>Please confirm that you want to merge your {installation-url} account with that account.
<br/>The link will expire in {expiration_time}.</p>
<a href="{installation-url}{tenant-url-path}/login/merge/confirmation/{confirmationToken}" target="_blank">Confirm Merge Request</a>
<a href="{installation-url}/login/merge/confirmation/{confirmationToken}" target="_blank">Confirm Merge Request</a>
</body>
</html>

View File

@ -271,7 +271,7 @@
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td> <a href="{installation-url}{tenant-url-path}/login/unlink/confirmation/{confirmationToken}" target="_blank">Confirm Unlink Request</a> </td>
<td> <a href="{installation-url}/login/unlink/confirmation/{confirmationToken}" target="_blank">Confirm Unlink Request</a> </td>
</tr>
</tbody>
</table>

View File

@ -9,6 +9,6 @@
<h2>You have made a request to unlink your email account in OpenCDMP.</h2>
<p>Please confirm that you want to unlink your {email} account.
<br/>The link will expire in {expiration_time}.</p>
<a href="{installation-url}{tenant-url-path}/login/unlink/confirmation/{confirmationToken}" target="_blank">Confirm Unlink Request</a>
<a href="{installation-url}/login/unlink/confirmation/{confirmationToken}" target="_blank">Confirm Unlink Request</a>
</body>
</html>