Implementing validators for User persist models (completed)

This commit is contained in:
Thomas Georgios Giannos 2024-01-04 12:39:31 +02:00
parent 18a4684859
commit 29022ee1cd
6 changed files with 361 additions and 152 deletions

View File

@ -1,32 +1,41 @@
package eu.eudat.model.persist;
import eu.eudat.commons.validation.old.ValidId;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import eu.eudat.commons.validation.BaseValidator;
import eu.eudat.commons.validation.specification.Specification;
import eu.eudat.convention.ConventionService;
import eu.eudat.errorcode.ErrorThesaurusProperties;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class UserAdditionalInfoPersist {
private String avatarUrl;
@NotNull(message = "{validation.empty}")
@NotEmpty(message = "{validation.empty}")
private String timezone;
@NotNull(message = "{validation.empty}")
@NotEmpty(message = "{validation.empty}")
public static final String _timezone = "timezone";
private String culture;
@NotNull(message = "{validation.empty}")
@NotEmpty(message = "{validation.empty}")
public static final String _culture = "culture";
private String language;
public static final String _language = "language";
private String roleOrganization;
@ValidId(message = "{validation.invalidid}")
private UUID organizationId;
public static final String _organizationId = "organizationId";
public String getAvatarUrl() {
return avatarUrl;
}
@ -74,4 +83,42 @@ public class UserAdditionalInfoPersist {
public void setOrganizationId(UUID organizationId) {
this.organizationId = organizationId;
}
@Component(UserAdditionalInfoPersistValidator.ValidatorName)
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public static class UserAdditionalInfoPersistValidator extends BaseValidator<UserAdditionalInfoPersist> {
public static final String ValidatorName = "UserAdditionalInfoPersistValidator";
private final MessageSource messageSource;
protected UserAdditionalInfoPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) {
super(conventionService, errors);
this.messageSource = messageSource;
}
@Override
protected Class<UserAdditionalInfoPersist> modelClass() {
return UserAdditionalInfoPersist.class;
}
@Override
protected List<Specification> specifications(UserAdditionalInfoPersist item) {
return Arrays.asList(
this.spec()
.must(() -> !this.isEmpty(item.getTimezone()))
.failOn(UserAdditionalInfoPersist._timezone).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserAdditionalInfoPersist._timezone}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isEmpty(item.getCulture()))
.failOn(UserAdditionalInfoPersist._culture).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserAdditionalInfoPersist._culture}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isEmpty(item.getLanguage()))
.failOn(UserAdditionalInfoPersist._language).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserAdditionalInfoPersist._language}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isNull(item.getOrganizationId()))
.failOn(UserAdditionalInfoPersist._organizationId).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserAdditionalInfoPersist._organizationId}, LocaleContextHolder.getLocale()))
);
}
}
}

View File

@ -1,33 +1,37 @@
package eu.eudat.model.persist;
import eu.eudat.commons.validation.old.FieldNotNullIfOtherSet;
import eu.eudat.commons.validation.old.ValidId;
import eu.eudat.commons.validation.BaseValidator;
import eu.eudat.commons.validation.ValidatorFactory;
import eu.eudat.commons.validation.specification.Specification;
import eu.eudat.convention.ConventionService;
import eu.eudat.data.UserEntity;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import eu.eudat.errorcode.ErrorThesaurusProperties;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@FieldNotNullIfOtherSet(message = "{validation.hashempty}")
public class UserPersist {
@ValidId(message = "{validation.invalidid}")
private UUID id;
@NotNull(message = "{validation.empty}")
@NotEmpty(message = "{validation.empty}")
@Size(max = UserEntity._nameLength, message = "{validation.largerthanmax}")
private String name;
public static final String _name = "name";
private String hash;
@Valid
public static final String _hash = "hash";
private UserAdditionalInfoPersist additionalInfo;
public static final String _additionalInfo = "additionalInfo";
public UUID getId() {
return id;
}
@ -59,5 +63,55 @@ public class UserPersist {
public void setAdditionalInfo(UserAdditionalInfoPersist additionalInfo) {
this.additionalInfo = additionalInfo;
}
@Component(UserPersistValidator.ValidatorName)
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public static class UserPersistValidator extends BaseValidator<UserPersist> {
public static final String ValidatorName = "UserPersistValidator";
private final MessageSource messageSource;
private final ValidatorFactory validatorFactory;
protected UserPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource, ValidatorFactory validatorFactory) {
super(conventionService, errors);
this.messageSource = messageSource;
this.validatorFactory = validatorFactory;
}
@Override
protected Class<UserPersist> modelClass() {
return UserPersist.class;
}
@Override
protected List<Specification> specifications(UserPersist item) {
return Arrays.asList(
this.spec()
.iff(() -> this.isValidGuid(item.getId()))
.must(() -> this.isValidHash(item.getHash()))
.failOn(UserPersist._hash).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserPersist._hash}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> !this.isValidGuid(item.getId()))
.must(() -> !this.isValidHash(item.getHash()))
.failOn(UserPersist._hash).failWith(messageSource.getMessage("Validation_OverPosting", new Object[]{}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isEmpty(item.getName()))
.failOn(UserPersist._name).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserPersist._name}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> !this.isEmpty(item.getName()))
.must(() -> this.lessEqualLength(item.getName(), UserEntity._nameLength))
.failOn(UserPersist._name).failWith(messageSource.getMessage("Validation_MaxLength", new Object[]{UserPersist._name}, LocaleContextHolder.getLocale())),
this.refSpec()
.iff(() -> !this.isNull(item.getAdditionalInfo()))
.on(UserPersist._additionalInfo)
.over(item.getAdditionalInfo())
.using(() -> this.validatorFactory.validator(UserAdditionalInfoPersist.UserAdditionalInfoPersistValidator.class))
);
}
}
}

View File

@ -1,27 +1,31 @@
package eu.eudat.model.persist;
import eu.eudat.commons.validation.BaseValidator;
import eu.eudat.commons.validation.specification.Specification;
import eu.eudat.convention.ConventionService;
import eu.eudat.errorcode.ErrorThesaurusProperties;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import eu.eudat.commons.validation.old.FieldNotNullIfOtherSet;
import eu.eudat.commons.validation.old.ValidId;
import jakarta.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@FieldNotNullIfOtherSet(message = "{validation.hashempty}")
public class UserRolePatchPersist {
@NotNull(message = "{validation.empty}")
@ValidId(message = "{validation.invalidid}")
private UUID id;
@NotNull(message = "{validation.empty}")
private List<String> roles;
@NotNull(message = "{validation.empty}")
public static final String _roles = "roles";
private String hash;
public static final String _hash = "hash";
public UUID getId() {
return id;
}
@ -45,5 +49,42 @@ public class UserRolePatchPersist {
public void setHash(String hash) {
this.hash = hash;
}
@Component(UserRolePatchPersistValidator.ValidatorName)
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public static class UserRolePatchPersistValidator extends BaseValidator<UserRolePatchPersist> {
public static final String ValidatorName = "UserRolePatchPersistValidator";
private final MessageSource messageSource;
protected UserRolePatchPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) {
super(conventionService, errors);
this.messageSource = messageSource;
}
@Override
protected Class<UserRolePatchPersist> modelClass() {
return UserRolePatchPersist.class;
}
@Override
protected List<Specification> specifications(UserRolePatchPersist item) {
return Arrays.asList(
this.spec()
.iff(() -> this.isValidGuid(item.getId()))
.must(() -> this.isValidHash(item.getHash()))
.failOn(UserRolePatchPersist._hash).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserRolePatchPersist._hash}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> !this.isValidGuid(item.getId()))
.must(() -> !this.isValidHash(item.getHash()))
.failOn(UserRolePatchPersist._hash).failWith(messageSource.getMessage("Validation_OverPosting", new Object[]{}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isNull(item.getRoles()))
.failOn(UserRolePatchPersist._roles).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserRolePatchPersist._roles}, LocaleContextHolder.getLocale()))
);
}
}
}

View File

@ -1,35 +1,44 @@
package eu.eudat.model.persist;
import eu.eudat.commons.enums.UserSettingsType;
import eu.eudat.commons.validation.old.FieldNotNullIfOtherSet;
import eu.eudat.commons.validation.old.ValidId;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import eu.eudat.commons.validation.BaseValidator;
import eu.eudat.commons.validation.specification.Specification;
import eu.eudat.convention.ConventionService;
import eu.eudat.errorcode.ErrorThesaurusProperties;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@FieldNotNullIfOtherSet(message = "{validation.hashempty}")
public class UserSettingsPersist {
@ValidId(message = "{validation.invalidid}")
private UUID id;
@NotNull(message = "{validation.empty}")
@NotEmpty(message = "{validation.empty}")
private String key;
@NotNull(message = "{validation.empty}")
@NotEmpty(message = "{validation.empty}")
public static final String _key = "key";
private String value;
@ValidId(message = "{validation.invalidid}")
public static final String _value = "value";
private UUID entityId;
@NotNull(message = "{validation.empty}")
public static final String _entityId = "entityId";
private UserSettingsType type;
public static final String _type = "type";
private String hash;
public static final String _hash = "hash";
public UUID getId() {
return id;
}
@ -77,4 +86,50 @@ public class UserSettingsPersist {
public void setValue(String value) {
this.value = value;
}
@Component(UserSettingsPersistValidator.ValidatorName)
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public static class UserSettingsPersistValidator extends BaseValidator<UserSettingsPersist> {
public static final String ValidatorName = "UserSettingsPersistValidator";
private final MessageSource messageSource;
protected UserSettingsPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) {
super(conventionService, errors);
this.messageSource = messageSource;
}
@Override
protected Class<UserSettingsPersist> modelClass() {
return UserSettingsPersist.class;
}
@Override
protected List<Specification> specifications(UserSettingsPersist item) {
return Arrays.asList(
this.spec()
.iff(() -> this.isValidGuid(item.getId()))
.must(() -> this.isValidHash(item.getHash()))
.failOn(UserSettingsPersist._hash).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserSettingsPersist._hash}, LocaleContextHolder.getLocale())),
this.spec()
.iff(() -> !this.isValidGuid(item.getId()))
.must(() -> !this.isValidHash(item.getHash()))
.failOn(UserSettingsPersist._hash).failWith(messageSource.getMessage("Validation_OverPosting", new Object[]{}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isEmpty(item.getKey()))
.failOn(UserSettingsPersist._key).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserSettingsPersist._key}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isEmpty(item.getValue()))
.failOn(UserSettingsPersist._value).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserSettingsPersist._value}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> this.isValidGuid(item.getEntityId()))
.failOn(UserSettingsPersist._entityId).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserSettingsPersist._entityId}, LocaleContextHolder.getLocale())),
this.spec()
.must(() -> !this.isNull(item.getType()))
.failOn(UserSettingsPersist._type).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserSettingsPersist._type}, LocaleContextHolder.getLocale()))
);
}
}
}

View File

@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import eu.eudat.audit.AuditableAction;
import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.commons.validation.ValidationFilterAnnotation;
import eu.eudat.data.UserEntity;
import eu.eudat.model.User;
import eu.eudat.model.UserRole;
@ -43,7 +44,10 @@ import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@RestController
@RequestMapping(path = "api/user")
@ -60,9 +64,11 @@ public class UserController {
private final CensorFactory censorFactory;
private final QueryFactory queryFactory;
private final UserScope userScope;
private final MessageSource messageSource;
private final ResponseUtilsService responseUtilsService;
public UserController(
@ -97,7 +103,6 @@ public class UserController {
long count = (lookup.getMetadata() != null && lookup.getMetadata().getCountAll()) ? query.count() : models.size();
this.auditService.track(AuditableAction.User_Query, "lookup", lookup);
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
return new QueryResult<>(models, count);
}
@ -117,7 +122,6 @@ public class UserController {
new AbstractMap.SimpleEntry<String, Object>("id", id),
new AbstractMap.SimpleEntry<String, Object>("fields", fieldSet)
));
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
return model;
}
@ -137,7 +141,6 @@ public class UserController {
new AbstractMap.SimpleEntry<String, Object>("email", email),
new AbstractMap.SimpleEntry<String, Object>("fields", fieldSet)
));
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
return model;
}
@ -149,10 +152,9 @@ public class UserController {
// this.censorFactory.censor(UserCensor.class).censor(fieldSet, null);
byte[] bytes = this.userTypeService.exportCsv();
this.auditService.track(AuditableAction.User_ExportCsv, Map.ofEntries(
));
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
return this.responseUtilsService.buildResponseFileFromText(new String(bytes, StandardCharsets.UTF_8), "Users_dump.csv");
}
@ -171,7 +173,6 @@ public class UserController {
new AbstractMap.SimpleEntry<String, Object>("id", id),
new AbstractMap.SimpleEntry<String, Object>("fields", fieldSet)
));
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
return model;
}
@ -211,7 +212,8 @@ public class UserController {
@PostMapping("persist")
@Transactional
public User persist(@MyValidate @RequestBody UserPersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException {
@ValidationFilterAnnotation(validator = UserPersist.UserPersistValidator.ValidatorName, argumentName = "model")
public User persist(@RequestBody UserPersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException {
logger.debug(new MapLogEntry("persisting" + User.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet));
User persisted = this.userTypeService.persist(model, fieldSet);
@ -219,13 +221,14 @@ public class UserController {
new AbstractMap.SimpleEntry<String, Object>("model", model),
new AbstractMap.SimpleEntry<String, Object>("fields", fieldSet)
));
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
return persisted;
}
@PostMapping("persist/roles")
@Transactional
public User persistRoles(@MyValidate @RequestBody UserRolePatchPersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException {
@ValidationFilterAnnotation(validator = UserRolePatchPersist.UserRolePatchPersistValidator.ValidatorName, argumentName = "model")
public User persistRoles(@RequestBody UserRolePatchPersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException {
logger.debug(new MapLogEntry("persisting" + UserRole.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet));
User persisted = this.userTypeService.patchRoles(model, fieldSet);
@ -233,7 +236,7 @@ public class UserController {
new AbstractMap.SimpleEntry<String, Object>("model", model),
new AbstractMap.SimpleEntry<String, Object>("fields", fieldSet)
));
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
return persisted;
}
@ -245,12 +248,11 @@ public class UserController {
this.userTypeService.deleteAndSave(id);
this.auditService.track(AuditableAction.User_Delete, "id", id);
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
}
@GetMapping("mine/merge-account-request/{email}")
@Transactional
public ResponseEntity mergeAccount(@PathVariable("email") String email) throws InvalidApplicationException, JAXBException {
public ResponseEntity<ResponseItem<String>> mergeAccount(@PathVariable("email") String email) throws InvalidApplicationException, JAXBException {
logger.debug(new MapLogEntry("merge account to user").And("email", email));
this.userTypeService.sendMergeAccountConfirmation(email);
@ -264,7 +266,7 @@ public class UserController {
@GetMapping("mine/confirm-merge-account/token/{token}")
@Transactional
public ResponseEntity confirmMergeAccount(@PathVariable("token") String token) throws InvalidApplicationException, JAXBException {
public ResponseEntity<ResponseItem<String>> confirmMergeAccount(@PathVariable("token") String token) throws InvalidApplicationException, JAXBException {
logger.debug(new MapLogEntry("confirm merge account to user").And("token", token));
this.userTypeService.confirmMergeAccount(token);
@ -278,7 +280,7 @@ public class UserController {
@GetMapping("mine/remove-credential-request/{email}")
@Transactional
public ResponseEntity removeCredentialAccount(@PathVariable("email") String email) throws InvalidApplicationException, JAXBException {
public ResponseEntity<ResponseItem<String>> removeCredentialAccount(@PathVariable("email") String email) throws InvalidApplicationException, JAXBException {
logger.debug(new MapLogEntry("remove credential request to user").And("email", email));
this.userTypeService.sendRemoveCredentialConfirmation(email);
@ -292,7 +294,7 @@ public class UserController {
@GetMapping("mine/confirm-remove-credential/token/{token}")
@Transactional
public ResponseEntity confirmRemoveCredentialAccount(@PathVariable("token") String token) throws InvalidApplicationException, JAXBException {
public ResponseEntity<ResponseItem<String>> confirmRemoveCredentialAccount(@PathVariable("token") String token) throws InvalidApplicationException, JAXBException {
logger.debug(new MapLogEntry("confirm remove credential to user").And("token", token));
this.userTypeService.confirmRemoveCredential(token);

View File

@ -1,6 +1,8 @@
package eu.eudat.controllers.v2;
import eu.eudat.audit.AuditableAction;
import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.commons.validation.ValidationFilterAnnotation;
import eu.eudat.data.UserSettingsEntity;
import eu.eudat.model.UserSettings;
import eu.eudat.model.builder.UserSettingsBuilder;
@ -29,7 +31,10 @@ import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.*;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@RestController
@RequestMapping(path = "api/user-settings")
@ -38,10 +43,15 @@ public class UserSettingsController {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserSettingsController.class));
private final BuilderFactory builderFactory;
private final AuditService auditService;
private final UserSettingsService settingsService;
private final CensorFactory censorFactory;
private final QueryFactory queryFactory;
private final MessageSource messageSource;
@Autowired
@ -70,7 +80,6 @@ public class UserSettingsController {
long count = (lookup.getMetadata() != null && lookup.getMetadata().getCountAll()) ? query.count() : models.size();
this.auditService.track(AuditableAction.User_Settings_Query, "lookup", lookup);
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
return new QueryResult<>(models, count);
}
@ -102,6 +111,7 @@ public class UserSettingsController {
@PostMapping("persist")
@Transactional
@ValidationFilterAnnotation(validator = UserSettingsPersist.UserSettingsPersistValidator.ValidatorName, argumentName = "model")
public UserSettings Persist(@MyValidate @RequestBody UserSettingsPersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException {
logger.debug(new MapLogEntry("persisting" + UserSettings.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet));
@ -111,7 +121,7 @@ public class UserSettingsController {
new AbstractMap.SimpleEntry<String, Object>("model", model),
new AbstractMap.SimpleEntry<String, Object>("fields", fieldSet)
));
//this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action);
return persisted;
}