#145 [Rights-Module] preparation for module specific roles

This commit is contained in:
Michael Hoennig 2019-06-27 23:48:16 +02:00
parent 7983aa7e52
commit 7db2c23de1
36 changed files with 945 additions and 734 deletions

View File

@ -1,22 +1,25 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.domain; package org.hostsharing.hsadminng.domain;
import org.hostsharing.hsadminng.repository.UserRepository; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.*;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.core.TreeNode;
import org.hostsharing.hsadminng.repository.UserRepository;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.*;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.service.accessfilter.Role.Supporter;
import org.springframework.boot.jackson.JsonComponent; import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Objects; import java.util.Objects;
import javax.persistence.*; import static org.hostsharing.hsadminng.service.util.ReflectionUtil.of;
import javax.validation.constraints.*;
/** /**
* A UserRoleAssignment. * A UserRoleAssignment.
@ -24,41 +27,44 @@ import javax.validation.constraints.*;
@Entity @Entity
@Table(name = "user_role_assignment") @Table(name = "user_role_assignment")
@EntityTypeId(UserRoleAssignment.ENTITY_TYPE_ID) @EntityTypeId(UserRoleAssignment.ENTITY_TYPE_ID)
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE)
public class UserRoleAssignment implements AccessMappings { public class UserRoleAssignment implements AccessMappings {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public static final String ENTITY_TYPE_ID = "rights.UserRoleAssignment"; private static final String USER_FIELD_NAME = "user";
static final String USER_FIELD_NAME = "user"; public static final String ENTITY_TYPE_ID = "rights.UserRoleAssignment";
@Id @Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator")
@SelfId(resolver = UserRoleAssignmentService.class) @SelfId(resolver = UserRoleAssignmentService.class)
@AccessFor(read = Role.SUPPORTER) @AccessFor(read = Supporter.class)
private Long id; private Long id;
@NotNull @NotNull
@Size(max = 32) @Size(max = 32)
@Column(name = "entity_type_id", length = 32, nullable = false) @Column(name = "entity_type_id", length = 32, nullable = false)
@AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = Role.SUPPORTER) @AccessFor(init = Admin.class, update = Admin.class, read = Supporter.class)
private String entityTypeId; private String entityTypeId;
@NotNull @NotNull
@Column(name = "entity_object_id", nullable = false) @Column(name = "entity_object_id", nullable = false)
@AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = Role.SUPPORTER) @AccessFor(init = Admin.class, update = Admin.class, read = Supporter.class)
private Long entityObjectId; private Long entityObjectId;
@NotNull @NotNull
@Enumerated(EnumType.STRING)
@Column(name = "assigned_role", nullable = false) @Column(name = "assigned_role", nullable = false)
@AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = Role.SUPPORTER) @AccessFor(init = Admin.class, update = Admin.class, read = Supporter.class)
private Role assignedRole; private String assignedRole;
@ManyToOne @ManyToOne
@JsonIgnoreProperties("requireds") @JsonIgnoreProperties("requireds")
@AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = Role.SUPPORTER) @AccessFor(init = Admin.class, update = Admin.class, read = Supporter.class)
private User user; private User user;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
@ -103,16 +109,16 @@ public class UserRoleAssignment implements AccessMappings {
} }
public Role getAssignedRole() { public Role getAssignedRole() {
return assignedRole; return assignedRole != null ? Role.of(assignedRole) : null;
} }
public UserRoleAssignment assignedRole(Role assignedRole) { public UserRoleAssignment assignedRole(Role assignedRole) {
this.assignedRole = assignedRole; this.assignedRole = of(assignedRole, Role::name);
return this; return this;
} }
public void setAssignedRole(Role assignedRole) { public void setAssignedRole(Role assignedRole) {
this.assignedRole = assignedRole; this.assignedRole = of(assignedRole, Role::name);
} }
public User getUser() { public User getUser() {
@ -154,9 +160,9 @@ public class UserRoleAssignment implements AccessMappings {
public String toString() { public String toString() {
return "UserRoleAssignment{" + return "UserRoleAssignment{" +
"id=" + getId() + "id=" + getId() +
", entityTypeId='" + getEntityTypeId() + "'" + ", entityTypeId='" + entityTypeId + "'" +
", entityObjectId=" + getEntityObjectId() + ", entityObjectId=" + entityObjectId +
", assignedRole='" + getAssignedRole() + "'" + ", assignedRole='" + assignedRole + "'" +
"}"; "}";
} }
@ -172,9 +178,8 @@ public class UserRoleAssignment implements AccessMappings {
@Override @Override
protected JSonFieldWriter<UserRoleAssignment> jsonFieldWriter(final Field field) { protected JSonFieldWriter<UserRoleAssignment> jsonFieldWriter(final Field field) {
if (USER_FIELD_NAME.equals(field.getName())) { if (USER_FIELD_NAME.equals(field.getName())) {
return (final UserRoleAssignment dto, final JsonGenerator jsonGenerator) -> { return (final UserRoleAssignment dto, final JsonGenerator jsonGenerator) -> jsonGenerator
jsonGenerator.writeNumberField(USER_FIELD_NAME, dto.getUser().getId()); .writeNumberField(USER_FIELD_NAME, dto.getUser().getId());
};
} }
return super.jsonFieldWriter(field); return super.jsonFieldWriter(field);
} }
@ -196,9 +201,8 @@ public class UserRoleAssignment implements AccessMappings {
@Override @Override
protected JSonFieldReader<UserRoleAssignment> jsonFieldReader(final TreeNode treeNode, final Field field) { protected JSonFieldReader<UserRoleAssignment> jsonFieldReader(final TreeNode treeNode, final Field field) {
if ("user".equals(field.getName())) { if ("user".equals(field.getName())) {
return (final UserRoleAssignment target) -> { return (final UserRoleAssignment target) -> target
target.setUser(userRepository.getOne(getSubNode(treeNode, "id").asLong())); .setUser(userRepository.getOne(getSubNode(treeNode, "id").asLong()));
};
} }
return super.jsonFieldReader(treeNode, field); return super.jsonFieldReader(treeNode, field);

View File

@ -1,6 +1,8 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter; package org.hostsharing.hsadminng.service.accessfilter;
import org.hostsharing.hsadminng.service.accessfilter.Role.Nobody;
import java.lang.annotation.*; import java.lang.annotation.*;
@Documented @Documented
@ -8,9 +10,9 @@ import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface AccessFor { public @interface AccessFor {
Role[] init() default Role.NOBODY; Class<? extends Role>[] init() default Nobody.class;
Role[] update() default Role.NOBODY; Class<? extends Role>[] update() default Nobody.class;
Role[] read() default Role.NOBODY; Class<? extends Role>[] read() default Nobody.class;
} }

View File

@ -1,27 +1,28 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter; package org.hostsharing.hsadminng.service.accessfilter;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.Sets.union;
import static java.util.Collections.EMPTY_SET;
import static java.util.Collections.emptySet;
import org.hostsharing.hsadminng.security.SecurityUtils; import org.hostsharing.hsadminng.security.SecurityUtils;
import org.hostsharing.hsadminng.service.IdToDtoResolver; import org.hostsharing.hsadminng.service.IdToDtoResolver;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.dto.MembershipDTO; import org.hostsharing.hsadminng.service.dto.MembershipDTO;
import org.hostsharing.hsadminng.service.util.ReflectionUtil; import org.hostsharing.hsadminng.service.util.ReflectionUtil;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.Sets.union;
import static java.util.Collections.EMPTY_SET;
import static java.util.Collections.emptySet;
abstract class JSonAccessFilter<T extends AccessMappings> { abstract class JSonAccessFilter<T extends AccessMappings> {
private final ApplicationContext ctx; private final ApplicationContext ctx;
@ -58,11 +59,15 @@ abstract class JSonAccessFilter<T extends AccessMappings> {
* @return all roles of the login user in relation to the dto, for which this filter is created. * @return all roles of the login user in relation to the dto, for which this filter is created.
*/ */
Set<Role> getLoginUserRoles() { Set<Role> getLoginUserRoles() {
final Set<Role> independentRoles = Arrays.stream(Role.values()) final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
.filter( if (authentication == null) {
role -> role.getAuthority() return emptySet();
.map(authority -> SecurityUtils.isCurrentUserInRole(authority)) }
.orElse(false)) final Set<Role> independentRoles = authentication
.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.map(Role::of)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
final Set<Role> rolesOnThis = getId() != null ? getLoginUserDirectRolesFor(dto.getClass(), getId()) : EMPTY_SET; final Set<Role> rolesOnThis = getId() != null ? getLoginUserDirectRolesFor(dto.getClass(), getId()) : EMPTY_SET;
@ -93,14 +98,10 @@ abstract class JSonAccessFilter<T extends AccessMappings> {
} }
private Set<Role> getLoginUserDirectRolesFor(final Class<?> dtoClass, final long id) { private Set<Role> getLoginUserDirectRolesFor(final Class<?> dtoClass, final long id) {
if (!SecurityUtils.isAuthenticated()) { verify(SecurityUtils.isAuthenticated());
return emptySet();
}
final EntityTypeId entityTypeId = dtoClass.getAnnotation(EntityTypeId.class); final EntityTypeId entityTypeId = dtoClass.getAnnotation(EntityTypeId.class);
if (entityTypeId == null) { verify(entityTypeId != null, "@" + EntityTypeId.class.getSimpleName() + " missing on " + dtoClass.getName());
return emptySet();
}
return userRoleAssignmentService.getEffectiveRoleOfCurrentUser(entityTypeId.value(), id); return userRoleAssignmentService.getEffectiveRoleOfCurrentUser(entityTypeId.value(), id);
} }

View File

@ -1,13 +1,6 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter; package org.hostsharing.hsadminng.service.accessfilter;
import static com.google.common.base.Verify.verify;
import static org.hostsharing.hsadminng.service.util.ReflectionUtil.unchecked;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.util.ReflectionUtil;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationContext;
@ -15,9 +8,11 @@ import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.*; import com.fasterxml.jackson.databind.node.*;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.NotImplementedException;
import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.ObjectUtils;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.util.ReflectionUtil;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -26,6 +21,9 @@ import java.time.LocalDate;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import static com.google.common.base.Verify.verify;
import static org.hostsharing.hsadminng.service.util.ReflectionUtil.unchecked;
public abstract class JsonDeserializerWithAccessFilter<T extends AccessMappings> extends JsonDeserializer<T> { public abstract class JsonDeserializerWithAccessFilter<T extends AccessMappings> extends JsonDeserializer<T> {
private final ApplicationContext ctx; private final ApplicationContext ctx;
@ -85,31 +83,30 @@ public abstract class JsonDeserializerWithAccessFilter<T extends AccessMappings>
private Object readValueFromJSon(final TreeNode treeNode, final String fieldName, final Class<?> fieldClass) { private Object readValueFromJSon(final TreeNode treeNode, final String fieldName, final Class<?> fieldClass) {
// FIXME can be removed? final TreeNode fieldNode = treeNode.get(fieldName); // FIXME can be removed? final TreeNode fieldNode = treeNode.get(fieldName);
final TreeNode fieldNode = treeNode; if (treeNode instanceof NullNode) {
if (fieldNode instanceof NullNode) {
return null; return null;
} }
if (fieldNode instanceof TextNode) { if (treeNode instanceof TextNode) {
return ((TextNode) fieldNode).asText(); return ((TextNode) treeNode).asText();
} }
if (fieldNode instanceof IntNode) { if (treeNode instanceof IntNode) {
return ((IntNode) fieldNode).asInt(); return ((IntNode) treeNode).asInt();
} }
if (fieldNode instanceof LongNode) { if (treeNode instanceof LongNode) {
return ((LongNode) fieldNode).asLong(); return ((LongNode) treeNode).asLong();
} }
if (fieldNode instanceof DoubleNode) { if (treeNode instanceof DoubleNode) {
// TODO: we need to figure out, why DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS does not work // TODO: we need to figure out, why DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS does not work
return ((DoubleNode) fieldNode).asDouble(); return ((DoubleNode) treeNode).asDouble();
} }
if (fieldNode instanceof ArrayNode && LocalDate.class.isAssignableFrom(fieldClass)) { if (treeNode instanceof ArrayNode && LocalDate.class.isAssignableFrom(fieldClass)) {
return LocalDate.of( return LocalDate.of(
((ArrayNode) fieldNode).get(0).asInt(), ((ArrayNode) treeNode).get(0).asInt(),
((ArrayNode) fieldNode).get(1).asInt(), ((ArrayNode) treeNode).get(1).asInt(),
((ArrayNode) fieldNode).get(2).asInt()); ((ArrayNode) treeNode).get(2).asInt());
} }
throw new NotImplementedException( throw new NotImplementedException(
"JSon node type not implemented: " + fieldNode.getClass() + " -> " + fieldName + ": " + fieldClass); "JSon node type not implemented: " + treeNode.getClass() + " -> " + fieldName + ": " + fieldClass);
} }
private void writeValueToDto(final T dto, final Field field, final Object value) { private void writeValueToDto(final T dto, final Field field, final Object value) {
@ -223,25 +220,29 @@ public abstract class JsonDeserializerWithAccessFilter<T extends AccessMappings>
throw new BadRequestAlertException( throw new BadRequestAlertException(
"Initialization of field " + toDisplay(field) "Initialization of field " + toDisplay(field)
+ " prohibited for current user role(s): " + " prohibited for current user role(s): "
+ Joiner.on("+").join(roles), + asString(roles),
toDisplay(field), toDisplay(field),
"initializationProhibited"); "initializationProhibited");
} else { } else {
throw new BadRequestAlertException( throw new BadRequestAlertException(
"Referencing field " + toDisplay(field) "Referencing field " + toDisplay(field)
+ " prohibited for current user role(s): " + " prohibited for current user role(s): "
+ Joiner.on("+").join(roles), + asString(roles),
toDisplay(field), toDisplay(field),
"referencingProhibited"); "referencingProhibited");
} }
} }
} }
private String asString(Set<Role> roles) {
return Joiner.on("+").join(roles.stream().map(Role::name).toArray());
}
private void validateUpdateAccess(Field field, Set<Role> roles) { private void validateUpdateAccess(Field field, Set<Role> roles) {
if (!Role.toBeIgnoredForUpdates(field) && !isAllowedToUpdate(getLoginUserRoles(), field)) { if (!Role.toBeIgnoredForUpdates(field) && !isAllowedToUpdate(getLoginUserRoles(), field)) {
throw new BadRequestAlertException( throw new BadRequestAlertException(
"Update of field " + toDisplay(field) + " prohibited for current user role(s): " "Update of field " + toDisplay(field) + " prohibited for current user role(s): "
+ Joiner.on("+").join(roles), + asString(roles),
toDisplay(field), toDisplay(field),
"updateProhibited"); "updateProhibited");
} }

View File

@ -1,14 +1,12 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter; package org.hostsharing.hsadminng.service.accessfilter;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.util.ReflectionUtil;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.NotImplementedException;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.util.ReflectionUtil;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import java.io.IOException; import java.io.IOException;
@ -131,7 +129,7 @@ public abstract class JsonSerializerWithAccessFilter<T extends AccessMappings> e
return true; return true;
} }
} }
return Role.ANYBODY.isAllowedToRead(field); return ReflectionUtil.newInstance(Role.Anybody.class).isAllowedToRead(field); // TODO
} }
} }

View File

@ -1,35 +1,128 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter; package org.hostsharing.hsadminng.service.accessfilter;
import static com.google.common.base.Verify.verify; import org.apache.commons.lang3.ArrayUtils;
import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.User; import org.hostsharing.hsadminng.domain.User;
import org.hostsharing.hsadminng.domain.UserRoleAssignment; import org.hostsharing.hsadminng.domain.UserRoleAssignment;
import org.hostsharing.hsadminng.security.AuthoritiesConstants; import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.util.ReflectionUtil;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Optional; import java.util.HashMap;
import java.util.Map;
import static com.google.common.base.Verify.verify;
import static org.hostsharing.hsadminng.service.util.ReflectionUtil.initialize;
/** /**
* These enum values are used to specify the minimum role required to grant access to resources, * These enum values are used to specify the minimum role required to grant access to resources,
* see usages of {@link AccessFor}. * see usages of {@link AccessFor}.
* also they can be assigned to users via {@link UserRoleAssignment}. * Also they can be assigned to users via {@link UserRoleAssignment}.
* Some of the concrete values make only sense in one of these contexts. * Some of the concrete values make only sense in one of these contexts.
* <p> * <p>
* Further, there are two kinds of roles: independent and dependent. * There are two kinds of roles: independent and dependent.
* Independent roles like {@link #HOSTMASTER} are absolute roles which means unrelated to any concrete entity. * Independent roles like {@link Hostmaster} are absolute roles which means unrelated to any concrete entity.
* Dependent roles like {@link #CUSTOMER_CONTRACTUAL_CONTACT} are relative to a specific entity, * Dependent roles like {@link CustomerContractualContact} are relative to a specific entity,
* in this case to a specific {@link Customer}. * in this case to a specific {@link Customer}.
* <p> * <p>
* <p>
* Separate classes are used to make it possible to use roles in Java annotations
* and also make it possible to have roles spread over multiple modules.
* </p>
*/ */
/* public abstract class Role {
* TODO: Maybe splitting it up into UserRole and RequiredRole would make it more clear?
* And maybe instead of a level, we could then add the comprised roles in the constructor? // TODO mhoennig: We need to make sure that the classes are loaded
* This could also be a better way to express that the financial contact has no rights to // and thus the static initializers were called
* other users resources (see also ACTUAL_CUSTOMER_USER vs. ANY_CUSTOMER_USER). // before these maps are used in production code.
*/ private static Map<Class<? extends Role>, Role> rolesByClass = new HashMap<>();
public enum Role { private static Map<String, Role> rolesByName = new HashMap<>();
private final String authority;
private final LazyRoles comprises;
Role() {
this.authority = AuthoritiesConstants.USER;
// noinspection unchecked
this.comprises = new LazyRoles();
}
@SafeVarargs
Role(final Class<? extends Role>... comprisedRoleClasses) {
this.authority = AuthoritiesConstants.USER;
// noinspection unchecked
this.comprises = new LazyRoles(comprisedRoleClasses);
}
@SafeVarargs
Role(final String authority, final Class<? extends Role>... comprisedRoleClasses) {
this.authority = authority;
// noinspection unchecked
this.comprises = new LazyRoles(comprisedRoleClasses);
}
public static Role of(final String authority) {
final Role role = rolesByName.get(authority);
verify(
role != null,
"unknown authority: %s, available authorities: ",
authority,
ArrayUtils.toString(rolesByName.keySet()));
return role;
}
public static <T extends Role> T of(final Class<T> roleClass) {
// prevent initialization and thus recursive call to `Role.of(...)` within `newInstance(...)`
final Class<T> initializedRoleClass = initialize(roleClass);
{
final T role = (T) rolesByClass.get(initializedRoleClass);
if (role != null) {
return role;
}
}
{
T newRole = (T) ReflectionUtil.newInstance(initializedRoleClass);
rolesByClass.put(initializedRoleClass, newRole);
rolesByName.put(newRole.name(), newRole);
return newRole;
}
}
@Override
public String toString() {
return getClass().getName() + "(" + name() + ")";
}
public abstract String name();
public static class IndependentRole extends Role {
@SafeVarargs
IndependentRole(final String authority, final Class<? extends Role>... comprisedRoleClasses) {
super(authority, comprisedRoleClasses);
}
public String name() {
return authority();
}
}
public static class DependentRole extends Role {
DependentRole() {
}
@SafeVarargs
DependentRole(final Class<? extends Role>... comprisedRoleClasses) {
super(AuthoritiesConstants.USER, comprisedRoleClasses);
}
public String name() {
return getClass().getSimpleName(); // TODO: decide if it's ok for use in the DB table
}
}
/** /**
* Default for access rights requirement. You can read it as: 'Nobody is allowed to ...'. * Default for access rights requirement. You can read it as: 'Nobody is allowed to ...'.
* This is usually used for fields which are managed by hsadminNg itself. * This is usually used for fields which are managed by hsadminNg itself.
@ -37,31 +130,43 @@ public enum Role {
* This role cannot be assigned to a user. * This role cannot be assigned to a user.
* </p> * </p>
*/ */
NOBODY(0), public static class Nobody extends DependentRole {
public static final Nobody ROLE = Role.of(Nobody.class);
}
/** /**
* Hostmasters are initialize/update/read and field which, except where NOBODY is allowed to. * Hostmasters are initialize/update/read and field which, except where NOBODY is allowed to.
* <p>
* This role can be assigned to a user via {@link User#setAuthorities}.
* </p>
*/ */
HOSTMASTER(1, AuthoritiesConstants.HOSTMASTER), public static class Hostmaster extends IndependentRole {
/** /**
* This role is for administrators, e.g. to create memberships and book shared and assets. * Hostmasters role to be assigned to users via via {@link User#setAuthorities}.
* <p> */
* This role can be assigned to a user via {@link User#setAuthorities}. public static final Hostmaster ROLE = Role.of(Hostmaster.class);
* </p>
*/
ADMIN(2, AuthoritiesConstants.ADMIN),
/** Hostmaster() {
* This role is for members of the support team. super(AuthoritiesConstants.HOSTMASTER, Admin.class);
* <p> }
* This role can be assigned to a user via {@link User#setAuthorities}. }
* </p>
*/ public static class Admin extends IndependentRole {
SUPPORTER(3, AuthoritiesConstants.SUPPORTER),
public static final Admin ROLE = Role.of(Admin.class);
Admin() {
super(AuthoritiesConstants.ADMIN, Supporter.class);
}
}
public static class Supporter extends IndependentRole {
public static final Supporter ROLE = Role.of(Supporter.class);
Supporter() {
super(AuthoritiesConstants.SUPPORTER, CustomerContractualContact.class);
}
}
/** /**
* This role is for contractual contacts of a customer, like a director of the company. * This role is for contractual contacts of a customer, like a director of the company.
@ -72,66 +177,76 @@ public enum Role {
* This role can be assigned to a user via {@link UserRoleAssignment}. * This role can be assigned to a user via {@link UserRoleAssignment}.
* </p> * </p>
*/ */
CUSTOMER_CONTRACTUAL_CONTACT(20), public static class CustomerContractualContact extends DependentRole {
/** public static final CustomerContractualContact ROLE = Role.of(CustomerContractualContact.class);
* This role is for financial contacts of a customer, e.g. for accessing billing data.
* <p>
* The financial contact only covers {@link Role#CUSTOMER_FINANCIAL_CONTACT}, {@link Role#ANY_CUSTOMER_CONTACT} and
* {@link Role#ANYBODY}, but not other <em>normal</em> user roles.
* </p>
* <p>
* This role can be assigned to a user via {@link UserRoleAssignment}.
* </p>
*/
CUSTOMER_FINANCIAL_CONTACT(22) {
@Override CustomerContractualContact() {
public boolean covers(final Role role) { super(CustomerFinancialContact.class, CustomerTechnicalContact.class);
return role == CUSTOMER_FINANCIAL_CONTACT || role == ANY_CUSTOMER_CONTACT || role == ANYBODY;
} }
}, }
/** public static class CustomerFinancialContact extends DependentRole {
* This role is for technical contacts of a customer.
* <p>
* This role can be assigned to a user via {@link UserRoleAssignment}.
* </p>
*/
CUSTOMER_TECHNICAL_CONTACT(22),
/** public static final CustomerFinancialContact ROLE = Role.of(CustomerFinancialContact.class);
* This meta-role is to specify that any kind of customer contact can get access to the resource.
* <p>
* It's only used to specify the required role and cannot be assigned to a user.
* </p>
*/
ANY_CUSTOMER_CONTACT(29),
/** CustomerFinancialContact() {
* Some user belonging to a customer without a more precise role. super(AnyCustomerContact.class);
*/ }
// TODO: It's mostly a placeholder for more precise future roles like a "webspace admin". }
// This also shows that it's a bit ugly that we need the roles of all modules in this enum
// because types for attributes of annotations are quite limited in Java.
ACTUAL_CUSTOMER_USER(80),
/** public static class CustomerTechnicalContact extends DependentRole {
* Use this to grant rights to any user, also special function users who have no
* rights on other users resources. public static final CustomerTechnicalContact ROLE = Role.of(CustomerTechnicalContact.class);
* <p>
* It's only used to specify the required role and cannot be assigned to a user. CustomerTechnicalContact() {
* </p> super(
*/ AnyCustomerContact.class,
ANY_CUSTOMER_USER(89), AnyCustomerUser.class); // TODO mhoennig: how to add roles of other modules?
}
}
public static class AnyCustomerContact extends DependentRole {
public static final AnyCustomerContact ROLE = Role.of(AnyCustomerContact.class);
AnyCustomerContact() {
super(Anybody.class);
}
}
public static class ActualCustomerUser extends DependentRole {
public static final ActualCustomerUser ROLE = Role.of(ActualCustomerUser.class);
ActualCustomerUser() {
super(AnyCustomerUser.class);
}
}
public static class AnyCustomerUser extends DependentRole {
public static final Role ROLE = Role.of(AnyCustomerUser.class);
AnyCustomerUser() {
super(Anybody.class);
}
}
/** /**
* This role is meant to specify that a resources can be accessed by anybody, even without login. * This role is meant to specify that a resources can be accessed by anybody, even without login.
* <p> * <p>
* It can be used to specify the required role and is the implicit role for un-authenticated users. * It can be used to specify to grant rights to any use, even if unauthorized.
* </p> * </p>
*/ */
ANYBODY(99, AuthoritiesConstants.ANONYMOUS), public static class Anybody extends IndependentRole {
public static final Role ROLE = Role.of(Anybody.class);
Anybody() {
super(AuthoritiesConstants.ANONYMOUS);
}
}
/** /**
* Pseudo-role to mark init/update access as ignored because the field is display-only. * Pseudo-role to mark init/update access as ignored because the field is display-only.
@ -139,27 +254,12 @@ public enum Role {
* This allows REST clients to send the whole response back as a new update request. * This allows REST clients to send the whole response back as a new update request.
* This role is not covered by any and covers itself no role. * This role is not covered by any and covers itself no role.
* <p> * <p>
* It's only used to specify the required role and cannot be assigned to a user. * It's only used to ignore the field.
* </p> * </p>
*/ */
IGNORED; public static class Ignored extends DependentRole {
private final Integer level; public static final Role ROLE = Role.of(Ignored.class);
private final Optional<String> authority;
Role(final int level, final String authority) {
this.level = level;
this.authority = Optional.of(authority);
}
Role(final int level) {
this.level = level;
this.authority = Optional.empty();
}
Role() {
this.level = null;
this.authority = Optional.empty();
} }
/** /**
@ -171,32 +271,25 @@ public enum Role {
if (accessForAnnot == null) { if (accessForAnnot == null) {
return true; return true;
} }
final Role[] updateAccessFor = field.getAnnotation(AccessFor.class).update(); final Class<? extends Role>[] updateAccessFor = field.getAnnotation(AccessFor.class).update();
return updateAccessFor.length == 1 && updateAccessFor[0].isIgnored(); return updateAccessFor.length == 1 && updateAccessFor[0] == Ignored.class;
} }
/** /**
* @return the independent authority related 1:1 to this Role or empty if no independent authority is related 1:1 * @return the independent authority related 1:1 to this Role or empty if no independent authority is related 1:1
* @see AuthoritiesConstants * @see AuthoritiesConstants
*/ */
public Optional<String> getAuthority() { public String authority() {
return authority; return authority;
} }
/**
* @return true if the role is the IGNORED role
*/
public boolean isIgnored() {
return this == Role.IGNORED;
}
/** /**
* @return the role with the broadest access rights * @return the role with the broadest access rights
*/ */
public static Role broadest(final Role role, final Role... roles) { public static Role broadest(final Role role, final Role... roles) {
Role broadests = role; Role broadests = role;
for (Role r : roles) { for (Role r : roles) {
if (r.covers(broadests)) { if (r.covers(broadests.getClass())) {
broadests = r; broadests = r;
} }
} }
@ -209,17 +302,25 @@ public enum Role {
* Where 'this' means the Java instance itself as a role of a system user. * Where 'this' means the Java instance itself as a role of a system user.
* <p> * <p>
* {@code * {@code
* Role.HOSTMASTER.covers(Role.ANY_CUSTOMER_USER) == true * AssignedHostmaster.ROLE.covers(AssignedRole.ANY_CUSTOMER_USER) == true
* } * }
* *
* @param role The required role for a resource. * @param roleClass The required role for a resource.
* @return whether this role comprises the given role * @return whether this role comprises the given role
*/ */
public boolean covers(final Role role) { public boolean covers(final Class<? extends Role> roleClass) {
if (this.isIgnored() || role.isIgnored()) { if (getClass() == Ignored.class || roleClass == Ignored.class) {
return false; return false;
} }
return this == role || this.level < role.level; if (getClass() == roleClass) {
return true;
}
for (Role role : comprises.get()) {
if (role.covers(roleClass)) {
return true;
}
}
return false;
} }
/** /**
@ -228,17 +329,17 @@ public enum Role {
* Where 'this' means the Java instance itself as a role of a system user. * Where 'this' means the Java instance itself as a role of a system user.
* <p> * <p>
* {@code * {@code
* Role.HOSTMASTER.coversAny(Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT) == true * AssignedHostmaster.ROLE.coversAny(AssignedRole.CUSTOMER_CONTRACTUAL_CONTACT, AssignedRole.CUSTOMER_FINANCIAL_CONTACT) == true
* } * }
* *
* @param roles The alternatively required roles for a resource. Must be at least one. * @param roleClasses The alternatively required roles for a resource. Must be at least one.
* @return whether this role comprises any of the given roles * @return whether this role comprises any of the given roles
*/ */
public boolean coversAny(final Role... roles) { public boolean coversAny(final Class<? extends Role>... roleClasses) {
verify(roles != null && roles.length > 0, "roles expected"); verify(roleClasses != null && roleClasses.length > 0, "role classes expected");
for (Role role : roles) { for (Class<? extends Role> roleClass : roleClasses) {
if (this.covers(role)) { if (this.covers(roleClass)) {
return true; return true;
} }
} }
@ -258,7 +359,7 @@ public enum Role {
return false; return false;
} }
return isRoleCovered(accessFor.init()); return coversAny(accessFor.init());
} }
/** /**
@ -274,7 +375,7 @@ public enum Role {
return false; return false;
} }
return isRoleCovered(accessFor.update()); return coversAny(accessFor.update());
} }
/** /**
@ -290,15 +391,26 @@ public enum Role {
return false; return false;
} }
return isRoleCovered(accessFor.read()); return coversAny(accessFor.read());
} }
}
private boolean isRoleCovered(final Role[] requiredRoles) {
for (Role accessAllowedForRole : requiredRoles) { class LazyRoles {
if (this.covers(accessAllowedForRole)) {
return true; private final Class<? extends Role>[] comprisedRoleClasses;
} private Role[] comprisedRoles = null;
}
return false; LazyRoles(Class<? extends Role>... comprisedRoleClasses) {
this.comprisedRoleClasses = comprisedRoleClasses;
}
Role[] get() {
if (comprisedRoles == null) {
comprisedRoles = new Role[comprisedRoleClasses.length];
for (int n = 0; n < comprisedRoleClasses.length; ++n) {
comprisedRoles[n] = Role.of(comprisedRoleClasses[n]);
}
}
return comprisedRoles;
} }
} }

View File

@ -7,18 +7,17 @@ import org.hostsharing.hsadminng.service.AssetService;
import org.hostsharing.hsadminng.service.MembershipService; import org.hostsharing.hsadminng.service.MembershipService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.*; import org.hostsharing.hsadminng.service.accessfilter.*;
import org.hostsharing.hsadminng.service.accessfilter.Role.*;
import org.springframework.boot.jackson.JsonComponent; import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable; import java.io.Serializable;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.Objects; import java.util.Objects;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/** /**
* A DTO for the Asset entity. * A DTO for the Asset entity.
*/ */
@ -26,34 +25,34 @@ import javax.validation.constraints.Size;
public class AssetDTO implements Serializable, AccessMappings { public class AssetDTO implements Serializable, AccessMappings {
@SelfId(resolver = AssetService.class) @SelfId(resolver = AssetService.class)
@AccessFor(read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private Long id; private Long id;
@NotNull @NotNull
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate documentDate; private LocalDate documentDate;
@NotNull @NotNull
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate valueDate; private LocalDate valueDate;
@NotNull @NotNull
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private AssetAction action; private AssetAction action;
@NotNull @NotNull
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private BigDecimal amount; private BigDecimal amount;
@Size(max = 160) @Size(max = 160)
@AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = Role.SUPPORTER) @AccessFor(init = Admin.class, update = Admin.class, read = Supporter.class)
private String remark; private String remark;
@ParentId(resolver = MembershipService.class) @ParentId(resolver = MembershipService.class)
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private Long membershipId; private Long membershipId;
@AccessFor(update = Role.IGNORED, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(update = Ignored.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private String membershipDisplayLabel; private String membershipDisplayLabel;
public Long getId() { public Long getId() {

View File

@ -7,14 +7,14 @@ import org.hostsharing.hsadminng.domain.enumeration.VatRegion;
import org.hostsharing.hsadminng.service.CustomerService; import org.hostsharing.hsadminng.service.CustomerService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.*; import org.hostsharing.hsadminng.service.accessfilter.*;
import org.springframework.boot.jackson.JsonComponent; import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import javax.validation.constraints.*;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.Objects; import java.util.Objects;
import javax.validation.constraints.*; import static org.hostsharing.hsadminng.service.accessfilter.Role.*;
/** /**
* A DTO for the Customer entity. * A DTO for the Customer entity.
@ -23,99 +23,99 @@ import javax.validation.constraints.*;
public class CustomerDTO implements AccessMappings, FluentBuilder<CustomerDTO> { public class CustomerDTO implements AccessMappings, FluentBuilder<CustomerDTO> {
@SelfId(resolver = CustomerService.class) @SelfId(resolver = CustomerService.class)
@AccessFor(read = Role.ANY_CUSTOMER_USER) @AccessFor(read = AnyCustomerUser.class)
private Long id; private Long id;
@NotNull @NotNull
@Min(value = 10000) @Min(value = 10000)
@Max(value = 99999) @Max(value = 99999)
@AccessFor(init = Role.ADMIN, read = Role.ANY_CUSTOMER_USER) @AccessFor(init = Admin.class, read = AnyCustomerUser.class)
private Integer reference; private Integer reference;
@NotNull @NotNull
@Size(max = 3) @Size(max = 3)
@Pattern(regexp = "[a-z][a-z0-9]+") @Pattern(regexp = "[a-z][a-z0-9]+")
@AccessFor(init = Role.ADMIN, read = Role.ANY_CUSTOMER_USER) @AccessFor(init = Admin.class, read = AnyCustomerUser.class)
private String prefix; private String prefix;
@NotNull @NotNull
@Size(max = 80) @Size(max = 80)
@AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = Role.ANY_CUSTOMER_USER) @AccessFor(init = Admin.class, update = Admin.class, read = AnyCustomerUser.class)
private String name; private String name;
@NotNull @NotNull
@AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = Role.CUSTOMER_CONTRACTUAL_CONTACT) @AccessFor(init = Admin.class, update = Admin.class, read = CustomerContractualContact.class)
private CustomerKind kind; private CustomerKind kind;
@AccessFor( @AccessFor(
init = Role.ADMIN, init = Admin.class,
update = Role.ADMIN, update = Admin.class,
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate birthDate; private LocalDate birthDate;
@Size(max = 80) @Size(max = 80)
@AccessFor( @AccessFor(
init = Role.ADMIN, init = Admin.class,
update = Role.ADMIN, update = Admin.class,
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private String birthPlace; private String birthPlace;
@Size(max = 80) @Size(max = 80)
@AccessFor( @AccessFor(
init = Role.ADMIN, init = Admin.class,
update = Role.ADMIN, update = Admin.class,
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private String registrationCourt; private String registrationCourt;
@Size(max = 80) @Size(max = 80)
@AccessFor( @AccessFor(
init = Role.ADMIN, init = Admin.class,
update = Role.ADMIN, update = Admin.class,
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private String registrationNumber; private String registrationNumber;
@NotNull @NotNull
@AccessFor( @AccessFor(
init = Role.ADMIN, init = Admin.class,
update = Role.ADMIN, update = Admin.class,
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private VatRegion vatRegion; private VatRegion vatRegion;
@Size(max = 40) @Size(max = 40)
@AccessFor( @AccessFor(
init = Role.ADMIN, init = Admin.class,
update = Role.ADMIN, update = Admin.class,
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private String vatNumber; private String vatNumber;
@Size(max = 80) @Size(max = 80)
@AccessFor(init = Role.ADMIN, update = Role.CUSTOMER_CONTRACTUAL_CONTACT, read = Role.CUSTOMER_CONTRACTUAL_CONTACT) @AccessFor(init = Admin.class, update = CustomerContractualContact.class, read = CustomerContractualContact.class)
private String contractualSalutation; private String contractualSalutation;
@NotNull @NotNull
@Size(max = 400) @Size(max = 400)
@AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = Role.CUSTOMER_CONTRACTUAL_CONTACT) @AccessFor(init = Admin.class, update = Admin.class, read = CustomerContractualContact.class)
private String contractualAddress; private String contractualAddress;
@Size(max = 80) @Size(max = 80)
@AccessFor( @AccessFor(
init = Role.ADMIN, init = Admin.class,
update = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }, update = { CustomerContractualContact.class, CustomerFinancialContact.class },
read = Role.CUSTOMER_CONTRACTUAL_CONTACT) read = CustomerContractualContact.class)
private String billingSalutation; private String billingSalutation;
@Size(max = 400) @Size(max = 400)
@AccessFor( @AccessFor(
init = Role.ADMIN, init = Admin.class,
update = Role.ADMIN, update = Admin.class,
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private String billingAddress; private String billingAddress;
@Size(max = 160) @Size(max = 160)
@AccessFor(init = Role.ADMIN, update = Role.SUPPORTER, read = Role.SUPPORTER) @AccessFor(init = Admin.class, update = Supporter.class, read = Supporter.class)
private String remark; private String remark;
@AccessFor(init = Role.ANYBODY, update = Role.ANYBODY, read = Role.ANY_CUSTOMER_USER) @AccessFor(init = Anybody.class, update = Anybody.class, read = AnyCustomerUser.class)
private String displayLabel; private String displayLabel;
public Long getId() { public Long getId() {

View File

@ -6,15 +6,14 @@ import org.hostsharing.hsadminng.service.CustomerService;
import org.hostsharing.hsadminng.service.MembershipService; import org.hostsharing.hsadminng.service.MembershipService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.*; import org.hostsharing.hsadminng.service.accessfilter.*;
import org.hostsharing.hsadminng.service.accessfilter.Role.*;
import org.springframework.boot.jackson.JsonComponent; import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import java.time.LocalDate;
import java.util.Objects;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.time.LocalDate;
import java.util.Objects;
/** /**
* A DTO for the Membership entity. * A DTO for the Membership entity.
@ -23,44 +22,44 @@ import javax.validation.constraints.Size;
public class MembershipDTO implements AccessMappings, FluentBuilder<MembershipDTO> { public class MembershipDTO implements AccessMappings, FluentBuilder<MembershipDTO> {
@SelfId(resolver = MembershipService.class) @SelfId(resolver = MembershipService.class)
@AccessFor(read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private Long id; private Long id;
@NotNull @NotNull
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate admissionDocumentDate; private LocalDate admissionDocumentDate;
@AccessFor( @AccessFor(
init = Role.ADMIN, init = Admin.class,
update = Role.ADMIN, update = Admin.class,
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate cancellationDocumentDate; private LocalDate cancellationDocumentDate;
@NotNull @NotNull
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate memberFromDate; private LocalDate memberFromDate;
@AccessFor( @AccessFor(
init = Role.ADMIN, init = Admin.class,
update = Role.ADMIN, update = Admin.class,
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate memberUntilDate; private LocalDate memberUntilDate;
@Size(max = 160) @Size(max = 160)
@AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = Role.SUPPORTER) @AccessFor(init = Admin.class, update = Admin.class, read = Supporter.class)
private String remark; private String remark;
@ParentId(resolver = CustomerService.class) @ParentId(resolver = CustomerService.class)
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private Long customerId; private Long customerId;
@AccessFor(update = Role.IGNORED, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(update = Ignored.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private String customerPrefix; private String customerPrefix;
@AccessFor(update = Role.IGNORED, read = Role.CUSTOMER_FINANCIAL_CONTACT) @AccessFor(update = Ignored.class, read = CustomerFinancialContact.class)
private String customerDisplayLabel; private String customerDisplayLabel;
@AccessFor(update = Role.IGNORED, read = Role.CUSTOMER_FINANCIAL_CONTACT) @AccessFor(update = Ignored.class, read = CustomerFinancialContact.class)
private String displayLabel; private String displayLabel;
public Long getId() { public Long getId() {

View File

@ -6,15 +6,14 @@ import org.hostsharing.hsadminng.service.CustomerService;
import org.hostsharing.hsadminng.service.SepaMandateService; import org.hostsharing.hsadminng.service.SepaMandateService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.*; import org.hostsharing.hsadminng.service.accessfilter.*;
import org.hostsharing.hsadminng.service.accessfilter.Role.*;
import org.springframework.boot.jackson.JsonComponent; import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import java.time.LocalDate;
import java.util.Objects;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.time.LocalDate;
import java.util.Objects;
/** /**
* A DTO for the SepaMandate entity. * A DTO for the SepaMandate entity.
@ -23,69 +22,69 @@ import javax.validation.constraints.Size;
public class SepaMandateDTO implements AccessMappings, FluentBuilder<SepaMandateDTO> { public class SepaMandateDTO implements AccessMappings, FluentBuilder<SepaMandateDTO> {
@SelfId(resolver = SepaMandateService.class) @SelfId(resolver = SepaMandateService.class)
@AccessFor(read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private Long id; private Long id;
@NotNull @NotNull
@Size(max = 40) @Size(max = 40)
@AccessFor( @AccessFor(
init = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }, init = { CustomerContractualContact.class, CustomerFinancialContact.class },
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private String reference; private String reference;
@Size(max = 34) @Size(max = 34)
@AccessFor( @AccessFor(
init = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }, init = { CustomerContractualContact.class, CustomerFinancialContact.class },
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private String iban; private String iban;
@Size(max = 11) @Size(max = 11)
@AccessFor( @AccessFor(
init = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }, init = { CustomerContractualContact.class, CustomerFinancialContact.class },
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private String bic; private String bic;
@NotNull @NotNull
@AccessFor( @AccessFor(
init = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }, init = { CustomerContractualContact.class, CustomerFinancialContact.class },
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate grantingDocumentDate; private LocalDate grantingDocumentDate;
@AccessFor( @AccessFor(
init = Role.ADMIN, init = Admin.class,
update = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }, update = { CustomerContractualContact.class, CustomerFinancialContact.class },
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate revokationDocumentDate; private LocalDate revokationDocumentDate;
@NotNull @NotNull
@AccessFor( @AccessFor(
init = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }, init = { CustomerContractualContact.class, CustomerFinancialContact.class },
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate validFromDate; private LocalDate validFromDate;
@AccessFor( @AccessFor(
init = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }, init = { CustomerContractualContact.class, CustomerFinancialContact.class },
update = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }, update = { CustomerContractualContact.class, CustomerFinancialContact.class },
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate validUntilDate; private LocalDate validUntilDate;
@AccessFor( @AccessFor(
init = Role.ADMIN, init = Admin.class,
update = Role.ADMIN, update = Admin.class,
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate lastUsedDate; private LocalDate lastUsedDate;
@Size(max = 160) @Size(max = 160)
@AccessFor(init = Role.ADMIN, update = Role.SUPPORTER, read = Role.SUPPORTER) @AccessFor(init = Admin.class, update = Supporter.class, read = Supporter.class)
private String remark; private String remark;
@ParentId(resolver = CustomerService.class) @ParentId(resolver = CustomerService.class)
@AccessFor( @AccessFor(
init = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }, init = { CustomerContractualContact.class, CustomerFinancialContact.class },
read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private Long customerId; private Long customerId;
@AccessFor(update = Role.IGNORED, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(update = Ignored.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private String customerDisplayLabel; private String customerDisplayLabel;
public Long getId() { public Long getId() {

View File

@ -7,17 +7,16 @@ import org.hostsharing.hsadminng.service.MembershipService;
import org.hostsharing.hsadminng.service.ShareService; import org.hostsharing.hsadminng.service.ShareService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.*; import org.hostsharing.hsadminng.service.accessfilter.*;
import org.hostsharing.hsadminng.service.accessfilter.Role.*;
import org.springframework.boot.jackson.JsonComponent; import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable; import java.io.Serializable;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.Objects; import java.util.Objects;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/** /**
* A DTO for the Share entity. * A DTO for the Share entity.
*/ */
@ -25,34 +24,34 @@ import javax.validation.constraints.Size;
public class ShareDTO implements Serializable, AccessMappings { public class ShareDTO implements Serializable, AccessMappings {
@SelfId(resolver = ShareService.class) @SelfId(resolver = ShareService.class)
@AccessFor(read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private Long id; private Long id;
@NotNull @NotNull
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate documentDate; private LocalDate documentDate;
@NotNull @NotNull
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private LocalDate valueDate; private LocalDate valueDate;
@NotNull @NotNull
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private ShareAction action; private ShareAction action;
@NotNull @NotNull
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private Integer quantity; private Integer quantity;
@Size(max = 160) @Size(max = 160)
@AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = Role.SUPPORTER) @AccessFor(init = Admin.class, update = Admin.class, read = Supporter.class)
private String remark; private String remark;
@ParentId(resolver = MembershipService.class) @ParentId(resolver = MembershipService.class)
@AccessFor(init = Role.ADMIN, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(init = Admin.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private Long membershipId; private Long membershipId;
@AccessFor(update = Role.IGNORED, read = { Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT }) @AccessFor(update = Ignored.class, read = { CustomerContractualContact.class, CustomerFinancialContact.class })
private String membershipDisplayLabel; private String membershipDisplayLabel;
public Long getId() { public Long getId() {

View File

@ -1,8 +1,6 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import io.github.jhipster.service.filter.Filter; import io.github.jhipster.service.filter.Filter;
import io.github.jhipster.service.filter.LongFilter; import io.github.jhipster.service.filter.LongFilter;
import io.github.jhipster.service.filter.StringFilter; import io.github.jhipster.service.filter.StringFilter;
@ -23,7 +21,7 @@ public class UserRoleAssignmentCriteria implements Serializable {
/** /**
* Class for filtering UserRole * Class for filtering UserRole
*/ */
public static class UserRoleFilter extends Filter<Role> { private static class UserRoleFilter extends Filter<String> {
} }
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;

View File

@ -1,9 +1,14 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.util; package org.hostsharing.hsadminng.service.util;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Optional;
import java.util.function.Function;
public class ReflectionUtil { public class ReflectionUtil {
@ -131,12 +136,32 @@ public class ReflectionUtil {
return Enum.valueOf((Class<E>) type, value.toString()); return Enum.valueOf((Class<E>) type, value.toString());
} }
public static Role newInstance(final Class<? extends Role> clazz) {
return unchecked(() -> accessible(clazz.getDeclaredConstructor()).newInstance());
}
@FunctionalInterface @FunctionalInterface
public interface ThrowingSupplier<T> { public interface ThrowingSupplier<T> {
T get() throws Exception; T get() throws Exception;
} }
/**
* Makes the given object accessible as if it were public.
*
* @param accessible field or method
* @param <T> type of accessible
* @return the given object
*/
private static <T extends AccessibleObject> T accessible(final T accessible) {
try {
accessible.setAccessible(true);
return accessible;
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
/** /**
* Catches checked exceptions and wraps these into an unchecked RuntimeException. * Catches checked exceptions and wraps these into an unchecked RuntimeException.
* <p> * <p>
@ -159,4 +184,35 @@ public class ReflectionUtil {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
/**
* Calling a method on a potentially null object. Similar to the ?: operator in Kotlin.
*
* @param source some object of type T
* @param f some function mapping T to R
* @param <T> the source type
* @param <R> the result type
* @return the result of f if source is not null, null otherwise
*/
public static <T, R> R of(T source, Function<T, R> f) {
return Optional.ofNullable(source).map(f).orElse(null);
}
/**
* Forces the initialization of the given class, this means, static initialization takes place.
*
* If the class is already initialized, this methods does nothing.
*
* @param clazz the class to be initialized
* @return the initialized class
*
*/
public static <T> Class<T> initialize(Class<T> clazz) {
try {
Class.forName(clazz.getName(), true, clazz.getClassLoader());
} catch (ClassNotFoundException e) {
throw new AssertionError(e); // Can't happen
}
return clazz;
}
} }

View File

@ -30,7 +30,7 @@
<th style="width: 10%"> <th style="width: 10%">
<select class="form-control" [(ngModel)]="filter.criteria.assignedRole" (change)="filter.trigger($event)"> <select class="form-control" [(ngModel)]="filter.criteria.assignedRole" (change)="filter.trigger($event)">
<option value=""></option> <option value=""></option>
<option value="HOSTMASTER" jhiTranslate="{{'hsadminNgApp.UserRole.HOSTMASTER'}}">HOSTMASTER</option> <option value="HOSTMASTER" jhiTranslate="{{'hsadminNgApp.UserHostmaster.ROLE'}}">HOSTMASTER</option>
<option value="ADMIN" jhiTranslate="{{'hsadminNgApp.UserRole.ADMIN'}}">ADMIN</option> <option value="ADMIN" jhiTranslate="{{'hsadminNgApp.UserRole.ADMIN'}}">ADMIN</option>
<option value="SUPPORTER" jhiTranslate="{{'hsadminNgApp.UserRole.SUPPORTER'}}">SUPPORTER</option> <option value="SUPPORTER" jhiTranslate="{{'hsadminNgApp.UserRole.SUPPORTER'}}">SUPPORTER</option>
<option value="CONTRACTUAL_CONTACT" jhiTranslate="{{'hsadminNgApp.UserRole.CUSTOMER_CONTRACTUAL_CONTACT'}}">CONTRACTUAL_CONTACT</option> <option value="CONTRACTUAL_CONTACT" jhiTranslate="{{'hsadminNgApp.UserRole.CUSTOMER_CONTRACTUAL_CONTACT'}}">CONTRACTUAL_CONTACT</option>

View File

@ -1,17 +1,14 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service; package org.hostsharing.hsadminng.service;
import static org.assertj.core.api.Assertions.assertThat; import com.google.common.base.VerifyException;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.UserRoleAssignment; import org.hostsharing.hsadminng.domain.UserRoleAssignment;
import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository; import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerFinancialContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerTechnicalContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextFake; import org.hostsharing.hsadminng.service.accessfilter.SecurityContextFake;
import com.google.common.base.VerifyException;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
@ -22,6 +19,10 @@ import org.mockito.junit.MockitoRule;
import java.util.Arrays; import java.util.Arrays;
import java.util.Set; import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.BDDMockito.given;
public class UserRoleAssignmentServiceUnitTest { public class UserRoleAssignmentServiceUnitTest {
@Rule @Rule
@ -65,23 +66,24 @@ public class UserRoleAssignmentServiceUnitTest {
Arrays.asList( Arrays.asList(
new UserRoleAssignment().entityTypeId("test.SomethingElse") new UserRoleAssignment().entityTypeId("test.SomethingElse")
.entityObjectId(givenEntityObjectId) .entityObjectId(givenEntityObjectId)
.assignedRole(Role.CUSTOMER_CONTRACTUAL_CONTACT), .assignedRole(CustomerContractualContact.ROLE),
new UserRoleAssignment().entityTypeId(givenEntityTypeId) new UserRoleAssignment().entityTypeId(givenEntityTypeId)
.entityObjectId(givenEntityObjectId) .entityObjectId(givenEntityObjectId)
.assignedRole(Role.CUSTOMER_FINANCIAL_CONTACT), .assignedRole(CustomerFinancialContact.ROLE),
new UserRoleAssignment().entityTypeId(givenEntityTypeId) new UserRoleAssignment().entityTypeId(givenEntityTypeId)
.entityObjectId(givenEntityObjectId) .entityObjectId(givenEntityObjectId)
.assignedRole(Role.CUSTOMER_TECHNICAL_CONTACT), .assignedRole(CustomerTechnicalContact.ROLE),
new UserRoleAssignment().entityTypeId(givenEntityTypeId) new UserRoleAssignment().entityTypeId(givenEntityTypeId)
.entityObjectId(3L) .entityObjectId(3L)
.assignedRole(Role.CUSTOMER_CONTRACTUAL_CONTACT))); .assignedRole(CustomerContractualContact.ROLE)));
// when // when
final Set<Role> actual = userRoleAssignmentService final Set<Role> actual = userRoleAssignmentService
.getEffectiveRoleOfCurrentUser(givenEntityTypeId, givenEntityObjectId); .getEffectiveRoleOfCurrentUser(givenEntityTypeId, givenEntityObjectId);
// then // then
assertThat(actual).containsExactlyInAnyOrder(Role.CUSTOMER_FINANCIAL_CONTACT, Role.CUSTOMER_TECHNICAL_CONTACT); assertThat(actual)
.containsExactlyInAnyOrder(Role.of(CustomerFinancialContact.class), Role.of(CustomerTechnicalContact.class));
} }
@Test @Test

View File

@ -0,0 +1,33 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.junit.Test;
import org.mockito.Mock;
import static org.assertj.core.api.Assertions.assertThat;
public class JSonAccessFilterTest {
@Mock
private UserRoleAssignmentService userRoleAssignmentService;
@Test
public void getLoginUserRoles() {
SecurityContextFake.havingUnauthenticatedUser();
new JSonAccessFilter<TestEntity>(null, userRoleAssignmentService, new TestEntity()) {
{
assertThat(this.getLoginUserRoles()).hasSize(0);
}
};
}
private static class TestEntity implements AccessMappings {
@Override
public Long getId() {
return null;
}
}
}

View File

@ -1,17 +1,16 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter; package org.hostsharing.hsadminng.service.accessfilter;
import static org.hostsharing.hsadminng.service.accessfilter.Role.*; import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.hostsharing.hsadminng.service.IdToDtoResolver; import org.hostsharing.hsadminng.service.IdToDtoResolver;
import org.hostsharing.hsadminng.service.dto.FluentBuilder; import org.hostsharing.hsadminng.service.dto.FluentBuilder;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.time.LocalDate; import java.time.LocalDate;
import static org.hostsharing.hsadminng.service.accessfilter.Role.*;
public class JSonAccessFilterTestFixture { public class JSonAccessFilterTestFixture {
static GivenDto createSampleDto() { static GivenDto createSampleDto() {
@ -37,10 +36,10 @@ public class JSonAccessFilterTestFixture {
static class GivenCustomerDto implements FluentBuilder<GivenCustomerDto> { static class GivenCustomerDto implements FluentBuilder<GivenCustomerDto> {
@SelfId(resolver = GivenService.class) @SelfId(resolver = GivenService.class)
@AccessFor(read = ANYBODY) @AccessFor(read = Anybody.class)
Long id; Long id;
@AccessFor(update = IGNORED, read = ANYBODY) @AccessFor(update = Ignored.class, read = Anybody.class)
String displayLabel; String displayLabel;
} }
@ -52,62 +51,62 @@ public class JSonAccessFilterTestFixture {
static class GivenDto implements AccessMappings, FluentBuilder<GivenDto> { static class GivenDto implements AccessMappings, FluentBuilder<GivenDto> {
@SelfId(resolver = GivenService.class) @SelfId(resolver = GivenService.class)
@AccessFor(read = ANYBODY) @AccessFor(read = Anybody.class)
Long id; Long id;
@ParentId(resolver = GivenCustomerService.class) @ParentId(resolver = GivenCustomerService.class)
@AccessFor(init = ANY_CUSTOMER_USER, update = ANY_CUSTOMER_USER, read = ANY_CUSTOMER_USER) @AccessFor(init = AnyCustomerUser.class, update = AnyCustomerUser.class, read = AnyCustomerUser.class)
Long customerId; Long customerId;
@AccessFor( @AccessFor(
init = { CUSTOMER_TECHNICAL_CONTACT, CUSTOMER_FINANCIAL_CONTACT }, init = { CustomerTechnicalContact.class, CustomerFinancialContact.class },
update = { CUSTOMER_TECHNICAL_CONTACT, CUSTOMER_FINANCIAL_CONTACT }, update = { CustomerTechnicalContact.class, CustomerFinancialContact.class },
read = { CUSTOMER_TECHNICAL_CONTACT, CUSTOMER_FINANCIAL_CONTACT }) read = { CustomerTechnicalContact.class, CustomerFinancialContact.class })
String restrictedField; String restrictedField;
@AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY) @AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
String openStringField; String openStringField;
@AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY) @AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
Integer openIntegerField; Integer openIntegerField;
@AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY) @AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
int openPrimitiveIntField; int openPrimitiveIntField;
@AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY) @AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
Long openLongField; Long openLongField;
@AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY) @AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
long openPrimitiveLongField; long openPrimitiveLongField;
@AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY) @AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
Boolean openBooleanField; Boolean openBooleanField;
@AccessFor(read = ANYBODY) @AccessFor(read = Anybody.class)
boolean openPrimitiveBooleanField; boolean openPrimitiveBooleanField;
@AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY) @AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
LocalDate openLocalDateField; LocalDate openLocalDateField;
transient String openLocalDateFieldAsString; transient String openLocalDateFieldAsString;
@AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY) @AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
LocalDate openLocalDateField2; LocalDate openLocalDateField2;
transient String openLocalDateField2AsString; transient String openLocalDateField2AsString;
@AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY) @AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
TestEnum openEnumField; TestEnum openEnumField;
transient String openEnumFieldAsString; transient String openEnumFieldAsString;
@AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY) @AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
BigDecimal openBigDecimalField; BigDecimal openBigDecimalField;
@AccessFor(init = SUPPORTER, update = SUPPORTER, read = SUPPORTER) @AccessFor(init = Supporter.class, update = Supporter.class, read = Supporter.class)
BigDecimal restrictedBigDecimalField; BigDecimal restrictedBigDecimalField;
@AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY) @AccessFor(init = Anybody.class, update = Anybody.class, read = Anybody.class)
int[] openArrayField; int[] openArrayField;
@AccessFor(init = IGNORED, update = IGNORED, read = ANYBODY) @AccessFor(init = Ignored.class, update = Ignored.class, read = Anybody.class)
String displayLabel; String displayLabel;
@Override @Override
@ -130,21 +129,21 @@ public class JSonAccessFilterTestFixture {
public static class GivenChildDto implements AccessMappings, FluentBuilder<GivenChildDto> { public static class GivenChildDto implements AccessMappings, FluentBuilder<GivenChildDto> {
@SelfId(resolver = GivenChildService.class) @SelfId(resolver = GivenChildService.class)
@AccessFor(read = Role.ANY_CUSTOMER_USER) @AccessFor(read = AnyCustomerUser.class)
Long id; Long id;
@AccessFor( @AccessFor(
init = Role.CUSTOMER_CONTRACTUAL_CONTACT, init = CustomerContractualContact.class,
update = Role.CUSTOMER_CONTRACTUAL_CONTACT, update = CustomerContractualContact.class,
read = ANY_CUSTOMER_USER) read = AnyCustomerUser.class)
@ParentId(resolver = GivenService.class) @ParentId(resolver = GivenService.class)
Long parentId; Long parentId;
@AccessFor( @AccessFor(
init = { CUSTOMER_TECHNICAL_CONTACT, CUSTOMER_FINANCIAL_CONTACT }, init = { CustomerTechnicalContact.class, CustomerFinancialContact.class },
update = { update = {
CUSTOMER_TECHNICAL_CONTACT, CustomerTechnicalContact.class,
CUSTOMER_FINANCIAL_CONTACT }) CustomerFinancialContact.class })
String restrictedField; String restrictedField;
@Override @Override
@ -156,11 +155,11 @@ public class JSonAccessFilterTestFixture {
public static class GivenDtoWithMultipleSelfId implements AccessMappings { public static class GivenDtoWithMultipleSelfId implements AccessMappings {
@SelfId(resolver = GivenChildService.class) @SelfId(resolver = GivenChildService.class)
@AccessFor(read = Role.ANY_CUSTOMER_USER) @AccessFor(read = AnyCustomerUser.class)
Long id; Long id;
@SelfId(resolver = GivenChildService.class) @SelfId(resolver = GivenChildService.class)
@AccessFor(read = Role.ANY_CUSTOMER_USER) @AccessFor(read = AnyCustomerUser.class)
Long id2; Long id2;
@Override @Override
@ -172,10 +171,10 @@ public class JSonAccessFilterTestFixture {
public static class GivenDtoWithUnknownFieldType implements AccessMappings { public static class GivenDtoWithUnknownFieldType implements AccessMappings {
@SelfId(resolver = GivenChildService.class) @SelfId(resolver = GivenChildService.class)
@AccessFor(read = Role.ANYBODY) @AccessFor(read = Anybody.class)
Long id; Long id;
@AccessFor(init = Role.ANYBODY, read = Role.ANYBODY) @AccessFor(init = Anybody.class, read = Anybody.class)
Arbitrary unknown; Arbitrary unknown;
@Override @Override
@ -184,14 +183,14 @@ public class JSonAccessFilterTestFixture {
} }
} }
public static class Arbitrary { static class Arbitrary {
} }
@EntityTypeId("givenParent") @EntityTypeId("givenParent")
public static class GivenParent implements AccessMappings, FluentBuilder<GivenParent> { public static class GivenParent implements AccessMappings, FluentBuilder<GivenParent> {
@SelfId(resolver = GivenParentService.class) @SelfId(resolver = GivenParentService.class)
@AccessFor(read = Role.ANY_CUSTOMER_USER) @AccessFor(read = AnyCustomerUser.class)
Long id; Long id;
@Override @Override
@ -208,21 +207,21 @@ public class JSonAccessFilterTestFixture {
public static class GivenChild implements AccessMappings, FluentBuilder<GivenChild> { public static class GivenChild implements AccessMappings, FluentBuilder<GivenChild> {
@SelfId(resolver = GivenChildService.class) @SelfId(resolver = GivenChildService.class)
@AccessFor(read = Role.ANY_CUSTOMER_USER) @AccessFor(read = AnyCustomerUser.class)
Long id; Long id;
@AccessFor( @AccessFor(
init = Role.CUSTOMER_CONTRACTUAL_CONTACT, init = CustomerContractualContact.class,
update = Role.CUSTOMER_CONTRACTUAL_CONTACT, update = CustomerContractualContact.class,
read = ANY_CUSTOMER_USER) read = AnyCustomerUser.class)
@ParentId(resolver = GivenParentService.class) @ParentId(resolver = GivenParentService.class)
GivenParent parent; GivenParent parent;
@AccessFor( @AccessFor(
init = { CUSTOMER_TECHNICAL_CONTACT, CUSTOMER_FINANCIAL_CONTACT }, init = { CustomerTechnicalContact.class, CustomerFinancialContact.class },
update = { update = {
CUSTOMER_TECHNICAL_CONTACT, CustomerTechnicalContact.class,
CUSTOMER_FINANCIAL_CONTACT }) CustomerFinancialContact.class })
String restrictedField; String restrictedField;
@Override @Override

View File

@ -32,37 +32,37 @@ public class JSonBuilder {
} }
public JSonBuilder withFieldValue(String name, String value) { public JSonBuilder withFieldValue(String name, String value) {
json.append(inQuotes(name) + ":" + (value != null ? inQuotes(value) : "null") + ","); json.append(inQuotes(name)).append(":").append(value != null ? inQuotes(value) : "null").append(",");
return this; return this;
} }
public JSonBuilder withFieldValue(String name, Number value) { public JSonBuilder withFieldValue(String name, Number value) {
json.append(inQuotes(name) + ":" + (value != null ? value : "null") + ","); json.append(inQuotes(name)).append(":").append(value != null ? value : "null").append(",");
return this; return this;
} }
public JSonBuilder toJSonNullFieldDefinition(String name) { public JSonBuilder toJSonNullFieldDefinition(String name) {
json.append(inQuotes(name) + ":null,"); json.append(inQuotes(name)).append(":null,");
return this; return this;
} }
public JSonBuilder withFieldValueIfPresent(String name, String value) { public JSonBuilder withFieldValueIfPresent(String name, String value) {
if (value != null) { if (value != null) {
json.append(inQuotes(name) + ":" + inQuotes(value) + ","); json.append(inQuotes(name)).append(":").append(inQuotes(value)).append(",");
} }
return this; return this;
} }
public JSonBuilder withFieldValueIfPresent(String name, Number value) { public JSonBuilder withFieldValueIfPresent(String name, Number value) {
if (value != null) { if (value != null) {
json.append(inQuotes(name) + ":" + value + ","); json.append(inQuotes(name)).append(":").append(value).append(",");
} }
return this; return this;
} }
public <E extends Enum<E>> JSonBuilder withFieldValueIfPresent(final String name, final E value) { public <E extends Enum<E>> JSonBuilder withFieldValueIfPresent(final String name, final Role value) {
if (value != null) { if (value != null) {
json.append(inQuotes(name) + ":" + inQuotes(value.name()) + ","); json.append(inQuotes(name)).append(":").append(inQuotes(value.name())).append(",");
} }
return this; return this;
} }

View File

@ -1,26 +1,18 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter; package org.hostsharing.hsadminng.service.accessfilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.Assumptions.assumeThat;
import static org.hostsharing.hsadminng.service.accessfilter.JSonAccessFilterTestFixture.*;
import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.NotImplementedException;
import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutablePair;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -37,6 +29,13 @@ import java.time.LocalDate;
import java.util.Arrays; import java.util.Arrays;
import java.util.Optional; import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.Assumptions.assumeThat;
import static org.hostsharing.hsadminng.service.accessfilter.JSonAccessFilterTestFixture.*;
import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon;
import static org.mockito.BDDMockito.given;
@SuppressWarnings("ALL") @SuppressWarnings("ALL")
public class JSonDeserializationWithAccessFilterUnitTest { public class JSonDeserializationWithAccessFilterUnitTest {
@ -83,7 +82,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
public void init() { public void init() {
securityContext = SecurityContextMock.usingMock(userRoleAssignmentService) securityContext = SecurityContextMock.usingMock(userRoleAssignmentService)
.havingAuthenticatedUser() .havingAuthenticatedUser()
.withRole(GivenDto.class, 1234L, Role.ANY_CUSTOMER_USER); .withRole(GivenDto.class, 1234L, Role.AnyCustomerUser.ROLE);
given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory); given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory);
given(autowireCapableBeanFactory.createBean(GivenService.class)).willReturn(givenService); given(autowireCapableBeanFactory.createBean(GivenService.class)).willReturn(givenService);
@ -244,7 +243,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
public void shouldDeserializeStringFieldIfRequiredRoleIsCoveredByUser() throws IOException { public void shouldDeserializeStringFieldIfRequiredRoleIsCoveredByUser() throws IOException {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.CUSTOMER_FINANCIAL_CONTACT); .withRole(GivenCustomerDto.class, 888L, Role.CustomerFinancialContact.ROLE);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("id", 1234L), ImmutablePair.of("id", 1234L),
@ -262,7 +261,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
public void shouldDeserializeUnchangedStringFieldIfRequiredRoleIsNotCoveredByUser() throws IOException { public void shouldDeserializeUnchangedStringFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.CUSTOMER_FINANCIAL_CONTACT); .withRole(GivenCustomerDto.class, 888L, Role.CustomerFinancialContact.ROLE);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("id", 1234L), ImmutablePair.of("id", 1234L),
@ -280,7 +279,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
public void shouldNotDeserializeUpatedStringFieldIfRequiredRoleIsNotCoveredByUser() throws IOException { public void shouldNotDeserializeUpatedStringFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER); .withRole(GivenCustomerDto.class, 888L, Role.ActualCustomerUser.ROLE);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("customerId", 888L), ImmutablePair.of("customerId", 888L),
@ -297,10 +296,10 @@ public class JSonDeserializationWithAccessFilterUnitTest {
} }
@Test @Test
public void shouldInitializeFieldIfRequiredRoleIsNotCoveredByUser() throws IOException { public void shouldNotInitializeFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER); .withRole(GivenCustomerDto.class, 888L, Role.ActualCustomerUser.ROLE);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("customerId", 888L), ImmutablePair.of("customerId", 888L),
@ -320,7 +319,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
public void shouldNotCreateIfRoleRequiredByParentEntityIsNotCoveredByUser() throws IOException { public void shouldNotCreateIfRoleRequiredByParentEntityIsNotCoveredByUser() throws IOException {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 9999L, Role.CUSTOMER_CONTRACTUAL_CONTACT); .withRole(GivenCustomerDto.class, 9999L, Role.CustomerContractualContact.ROLE);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("parentId", 1234L))); ImmutablePair.of("parentId", 1234L)));
@ -340,7 +339,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
public void shouldCreateIfRoleRequiredByReferencedEntityIsCoveredByUser() throws IOException { public void shouldCreateIfRoleRequiredByReferencedEntityIsCoveredByUser() throws IOException {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.CUSTOMER_CONTRACTUAL_CONTACT); .withRole(GivenCustomerDto.class, 888L, Role.CustomerContractualContact.ROLE);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("parentId", 1234L))); ImmutablePair.of("parentId", 1234L)));
@ -357,7 +356,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
public void shouldResolveParentIdFromIdOfSerializedSubEntity() throws IOException { public void shouldResolveParentIdFromIdOfSerializedSubEntity() throws IOException {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(GivenParent.class, 1234L, Role.CUSTOMER_CONTRACTUAL_CONTACT); .withRole(GivenParent.class, 1234L, Role.CustomerContractualContact.ROLE);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of( ImmutablePair.of(
@ -377,7 +376,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
public void shouldNotUpdateFieldIfRequiredRoleIsNotCoveredByUser() throws IOException { public void shouldNotUpdateFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER); .withRole(GivenCustomerDto.class, 888L, Role.ActualCustomerUser.ROLE);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("id", 1234L), ImmutablePair.of("id", 1234L),
@ -475,7 +474,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Test @Test
public void shouldIgnorePropertyToIgnoreForInit() throws IOException { public void shouldIgnorePropertyToIgnoreForInit() throws IOException {
// given // given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN); securityContext.havingAuthenticatedUser().withAuthority(Admin.ROLE.authority());
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("displayLabel", "Some Value"))); ImmutablePair.of("displayLabel", "Some Value")));

View File

@ -1,18 +1,9 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter; package org.hostsharing.hsadminng.service.accessfilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.JSonAccessFilterTestFixture.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.NotImplementedException;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -25,6 +16,13 @@ import org.springframework.context.ApplicationContext;
import java.io.IOException; import java.io.IOException;
import java.util.Optional; import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.JSonAccessFilterTestFixture.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
public class JSonSerializationWithAccessFilterUnitTest { public class JSonSerializationWithAccessFilterUnitTest {
@Rule @Rule
@ -53,7 +51,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
public void init() { public void init() {
securityContext = SecurityContextMock.usingMock(userRoleAssignmentService) securityContext = SecurityContextMock.usingMock(userRoleAssignmentService)
.havingAuthenticatedUser() .havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.ANY_CUSTOMER_USER); .withRole(GivenCustomerDto.class, 888L, Role.AnyCustomerUser.ROLE);
given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory); given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory);
given(autowireCapableBeanFactory.createBean(GivenCustomerService.class)).willReturn(givenCustomerService); given(autowireCapableBeanFactory.createBean(GivenCustomerService.class)).willReturn(givenCustomerService);
@ -157,7 +155,8 @@ public class JSonSerializationWithAccessFilterUnitTest {
public void shouldSerializeRestrictedFieldIfRequiredRoleIsCoveredByUser() throws IOException { public void shouldSerializeRestrictedFieldIfRequiredRoleIsCoveredByUser() throws IOException {
// given // given
securityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 888L, Role.CUSTOMER_FINANCIAL_CONTACT); securityContext.havingAuthenticatedUser()
.withRole(GivenCustomerDto.class, 888L, Role.of(Role.CustomerFinancialContact.class));
// when // when
serialize(givenDTO); serialize(givenDTO);
@ -170,7 +169,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
public void shouldNotSerializeRestrictedFieldIfRequiredRoleIsNotCoveredByUser() throws IOException { public void shouldNotSerializeRestrictedFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given // given
securityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 888L, Role.ANY_CUSTOMER_USER); securityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 888L, Role.AnyCustomerUser.ROLE);
// when // when
serialize(givenDTO); serialize(givenDTO);
@ -188,7 +187,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
} }
class GivenDtoWithUnimplementedFieldType implements AccessMappings { class GivenDtoWithUnimplementedFieldType implements AccessMappings {
@AccessFor(read = Role.ANYBODY) @AccessFor(read = Role.Anybody.class)
Arbitrary fieldWithUnimplementedType = new Arbitrary(); Arbitrary fieldWithUnimplementedType = new Arbitrary();
@Override @Override
@ -208,7 +207,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
// --- fixture code below --- // --- fixture code below ---
public <T extends AccessMappings> void serialize(final T dto) throws IOException { private <T extends AccessMappings> void serialize(final T dto) throws IOException {
// @formatter:off // @formatter:off
new JsonSerializerWithAccessFilter<T>(ctx, userRoleAssignmentService) {} new JsonSerializerWithAccessFilter<T>(ctx, userRoleAssignmentService) {}
.serialize(dto, jsonGenerator, null); .serialize(dto, jsonGenerator, null);

View File

@ -1,118 +1,113 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.accessfilter; package org.hostsharing.hsadminng.service.accessfilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import com.google.common.base.VerifyException; import com.google.common.base.VerifyException;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.accessfilter.Role.*;
import org.junit.Test; import org.junit.Test;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
public class RoleUnitTest { public class RoleUnitTest {
@Test @Test
public void allUserRolesShouldCoverSameRequiredRole() { public void allUserRolesShouldCoverSameRequiredRole() {
assertThat(Role.HOSTMASTER.covers(Role.HOSTMASTER)).isTrue(); assertThat(Hostmaster.ROLE.covers(Hostmaster.class)).isTrue();
assertThat(Role.ADMIN.covers(Role.ADMIN)).isTrue(); assertThat(Admin.ROLE.covers(Admin.class)).isTrue();
assertThat(Role.SUPPORTER.covers(Role.SUPPORTER)).isTrue(); assertThat(Supporter.ROLE.covers(Supporter.class)).isTrue();
assertThat(Role.CUSTOMER_CONTRACTUAL_CONTACT.covers(Role.CUSTOMER_CONTRACTUAL_CONTACT)).isTrue(); assertThat(Role.CustomerContractualContact.ROLE.covers(Role.CustomerContractualContact.class)).isTrue();
assertThat(Role.CUSTOMER_FINANCIAL_CONTACT.covers(Role.CUSTOMER_FINANCIAL_CONTACT)).isTrue(); assertThat(CustomerFinancialContact.ROLE.covers(CustomerFinancialContact.class)).isTrue();
assertThat(Role.CUSTOMER_TECHNICAL_CONTACT.covers(Role.CUSTOMER_TECHNICAL_CONTACT)).isTrue(); assertThat(CustomerTechnicalContact.ROLE.covers(CustomerTechnicalContact.class)).isTrue();
assertThat(Role.ACTUAL_CUSTOMER_USER.covers((Role.ACTUAL_CUSTOMER_USER))).isTrue(); assertThat(ActualCustomerUser.ROLE.covers((ActualCustomerUser.class))).isTrue();
assertThat(Role.ANY_CUSTOMER_USER.covers((Role.ANY_CUSTOMER_USER))).isTrue(); assertThat(AnyCustomerUser.ROLE.covers((Role.AnyCustomerUser.class))).isTrue();
} }
@Test @Test
public void lowerUserRolesShouldNotCoverHigherRequiredRoles() { public void lowerUserRolesShouldNotCoverHigherRequiredRoles() {
assertThat(Role.HOSTMASTER.covers(Role.NOBODY)).isFalse(); assertThat(Hostmaster.ROLE.covers(Nobody.class)).isFalse();
assertThat(Role.ADMIN.covers(Role.HOSTMASTER)).isFalse(); assertThat(Admin.ROLE.covers(Hostmaster.class)).isFalse();
assertThat(Role.SUPPORTER.covers(Role.ADMIN)).isFalse(); assertThat(Supporter.ROLE.covers(Admin.class)).isFalse();
assertThat(Role.ANY_CUSTOMER_CONTACT.covers(Role.SUPPORTER)).isFalse(); assertThat(AnyCustomerContact.ROLE.covers(Supporter.class)).isFalse();
assertThat(Role.ANY_CUSTOMER_CONTACT.covers(Role.CUSTOMER_CONTRACTUAL_CONTACT)).isFalse(); assertThat(AnyCustomerContact.ROLE.covers(Role.CustomerContractualContact.class)).isFalse();
assertThat(Role.CUSTOMER_FINANCIAL_CONTACT.covers(Role.CUSTOMER_CONTRACTUAL_CONTACT)).isFalse(); assertThat(CustomerFinancialContact.ROLE.covers(Role.CustomerContractualContact.class)).isFalse();
assertThat(Role.CUSTOMER_FINANCIAL_CONTACT.covers(Role.CUSTOMER_TECHNICAL_CONTACT)).isFalse(); assertThat(CustomerFinancialContact.ROLE.covers(CustomerTechnicalContact.class)).isFalse();
assertThat(Role.CUSTOMER_TECHNICAL_CONTACT.covers(Role.CUSTOMER_CONTRACTUAL_CONTACT)).isFalse(); assertThat(CustomerTechnicalContact.ROLE.covers(Role.CustomerContractualContact.class)).isFalse();
assertThat(Role.CUSTOMER_TECHNICAL_CONTACT.covers(Role.CUSTOMER_FINANCIAL_CONTACT)).isFalse(); assertThat(CustomerTechnicalContact.ROLE.covers(CustomerFinancialContact.class)).isFalse();
assertThat(Role.ACTUAL_CUSTOMER_USER.covers((Role.ANY_CUSTOMER_CONTACT))).isFalse(); assertThat(ActualCustomerUser.ROLE.covers((AnyCustomerContact.class))).isFalse();
assertThat(Role.ACTUAL_CUSTOMER_USER.covers((Role.CUSTOMER_CONTRACTUAL_CONTACT))).isFalse(); assertThat(ActualCustomerUser.ROLE.covers((Role.CustomerContractualContact.class))).isFalse();
assertThat(Role.ACTUAL_CUSTOMER_USER.covers((Role.CUSTOMER_TECHNICAL_CONTACT))).isFalse(); assertThat(ActualCustomerUser.ROLE.covers((CustomerTechnicalContact.class))).isFalse();
assertThat(Role.ACTUAL_CUSTOMER_USER.covers((Role.CUSTOMER_FINANCIAL_CONTACT))).isFalse(); assertThat(ActualCustomerUser.ROLE.covers((CustomerFinancialContact.class))).isFalse();
assertThat(Role.ANY_CUSTOMER_USER.covers((Role.ACTUAL_CUSTOMER_USER))).isFalse(); assertThat(AnyCustomerUser.ROLE.covers((ActualCustomerUser.class))).isFalse();
assertThat(Role.ANY_CUSTOMER_USER.covers((Role.ANY_CUSTOMER_CONTACT))).isFalse(); assertThat(AnyCustomerUser.ROLE.covers((AnyCustomerContact.class))).isFalse();
assertThat(Role.ANY_CUSTOMER_USER.covers((Role.CUSTOMER_CONTRACTUAL_CONTACT))).isFalse(); assertThat(AnyCustomerUser.ROLE.covers((Role.CustomerContractualContact.class))).isFalse();
assertThat(Role.ANY_CUSTOMER_USER.covers((Role.CUSTOMER_TECHNICAL_CONTACT))).isFalse(); assertThat(AnyCustomerUser.ROLE.covers((CustomerTechnicalContact.class))).isFalse();
assertThat(Role.ANY_CUSTOMER_USER.covers((Role.CUSTOMER_FINANCIAL_CONTACT))).isFalse(); assertThat(AnyCustomerUser.ROLE.covers((CustomerFinancialContact.class))).isFalse();
assertThat(Role.ANYBODY.covers((Role.ANY_CUSTOMER_USER))).isFalse(); assertThat(Anybody.ROLE.covers((Role.AnyCustomerUser.class))).isFalse();
} }
@Test @Test
public void higherUserRolesShouldCoverLowerRequiredRoles() { public void higherUserRolesShouldCoverLowerRequiredRoles() {
assertThat(Role.HOSTMASTER.covers(Role.SUPPORTER)).isTrue(); assertThat(Hostmaster.ROLE.covers(Supporter.class)).isTrue();
assertThat(Role.ADMIN.covers(Role.SUPPORTER)).isTrue(); assertThat(Admin.ROLE.covers(Supporter.class)).isTrue();
assertThat(Role.SUPPORTER.covers(Role.ANY_CUSTOMER_CONTACT)).isTrue(); assertThat(Supporter.ROLE.covers(AnyCustomerContact.class)).isTrue();
assertThat(Role.CUSTOMER_CONTRACTUAL_CONTACT.covers(Role.ANY_CUSTOMER_CONTACT)).isTrue(); assertThat(Role.CustomerContractualContact.ROLE.covers(AnyCustomerContact.class)).isTrue();
assertThat(Role.CUSTOMER_CONTRACTUAL_CONTACT.covers(Role.CUSTOMER_FINANCIAL_CONTACT)).isTrue(); assertThat(Role.CustomerContractualContact.ROLE.covers(CustomerFinancialContact.class)).isTrue();
assertThat(Role.CUSTOMER_CONTRACTUAL_CONTACT.covers(Role.CUSTOMER_TECHNICAL_CONTACT)).isTrue(); assertThat(Role.CustomerContractualContact.ROLE.covers(CustomerTechnicalContact.class)).isTrue();
assertThat(Role.CUSTOMER_TECHNICAL_CONTACT.covers(Role.ANY_CUSTOMER_USER)).isTrue(); assertThat(CustomerTechnicalContact.ROLE.covers(Role.AnyCustomerUser.class)).isTrue();
assertThat(Role.ACTUAL_CUSTOMER_USER.covers((Role.ANY_CUSTOMER_USER))).isTrue(); assertThat(ActualCustomerUser.ROLE.covers((Role.AnyCustomerUser.class))).isTrue();
assertThat(Role.ANY_CUSTOMER_USER.covers((Role.ANYBODY))).isTrue(); assertThat(AnyCustomerUser.ROLE.covers((Anybody.class))).isTrue();
} }
@Test @Test
public void financialContactShouldNotCoverAnyOtherRealRoleRequirement() { public void financialContactShouldNotCoverAnyOtherRealRoleRequirement() {
assertThat(Role.CUSTOMER_FINANCIAL_CONTACT.covers(Role.ANY_CUSTOMER_USER)).isFalse(); assertThat(CustomerFinancialContact.ROLE.covers(Role.AnyCustomerUser.class)).isFalse();
assertThat(Role.CUSTOMER_FINANCIAL_CONTACT.covers(Role.ACTUAL_CUSTOMER_USER)).isFalse(); assertThat(CustomerFinancialContact.ROLE.covers(ActualCustomerUser.class)).isFalse();
assertThat(Role.CUSTOMER_FINANCIAL_CONTACT.covers(Role.ANY_CUSTOMER_USER)).isFalse(); assertThat(CustomerFinancialContact.ROLE.covers(Role.AnyCustomerUser.class)).isFalse();
} }
@Test @Test
public void ignoredCoversNothingAndIsNotCovered() { public void ignoredCoversNothingAndIsNotCovered() {
assertThat(Role.IGNORED.covers(Role.HOSTMASTER)).isFalse(); assertThat(Ignored.ROLE.covers(Hostmaster.class)).isFalse();
assertThat(Role.IGNORED.covers(Role.ANYBODY)).isFalse(); assertThat(Ignored.ROLE.covers(Anybody.class)).isFalse();
assertThat(Role.IGNORED.covers(Role.IGNORED)).isFalse(); assertThat(Ignored.ROLE.covers(Ignored.class)).isFalse();
assertThat(Role.HOSTMASTER.covers(Role.IGNORED)).isFalse(); assertThat(Hostmaster.ROLE.covers(Ignored.class)).isFalse();
assertThat(Role.ANYBODY.covers(Role.IGNORED)).isFalse(); assertThat(Anybody.ROLE.covers(Ignored.class)).isFalse();
} }
@Test @Test
public void coversAny() { public void coversAny() {
assertThat(Role.HOSTMASTER.coversAny(Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT)).isTrue(); assertThat(Hostmaster.ROLE.coversAny(Role.CustomerContractualContact.class, CustomerFinancialContact.class)).isTrue();
assertThat( assertThat(
Role.CUSTOMER_CONTRACTUAL_CONTACT.coversAny(Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT)) Role.CustomerContractualContact.ROLE.coversAny(
.isTrue(); Role.CustomerContractualContact.class,
CustomerFinancialContact.class))
.isTrue();
assertThat( assertThat(
Role.CUSTOMER_FINANCIAL_CONTACT.coversAny(Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT)) CustomerFinancialContact.ROLE.coversAny(
.isTrue(); Role.CustomerContractualContact.class,
CustomerFinancialContact.class))
.isTrue();
assertThat(Role.ANY_CUSTOMER_USER.coversAny(Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.CUSTOMER_FINANCIAL_CONTACT)) assertThat(Role.AnyCustomerUser.ROLE.coversAny(Role.CustomerContractualContact.class, CustomerFinancialContact.class))
.isFalse(); .isFalse();
assertThat(catchThrowable(() -> Role.HOSTMASTER.coversAny())).isInstanceOf(VerifyException.class); assertThat(catchThrowable(Hostmaster.ROLE::coversAny)).isInstanceOf(VerifyException.class);
assertThat(catchThrowable(() -> Role.HOSTMASTER.coversAny((Role[]) null))).isInstanceOf(VerifyException.class); assertThat(
} catchThrowable(
() -> Hostmaster.ROLE.coversAny(
@Test (Class<Role>[]) null))).isInstanceOf(VerifyException.class);
public void isIgnored() {
for (Role role : Role.values()) {
if (role == Role.IGNORED) {
assertThat(role.isIgnored()).isTrue();
} else {
assertThat(role.isIgnored()).isFalse();
}
}
} }
@Test @Test
@ -125,54 +120,54 @@ public class RoleUnitTest {
@Test @Test
public void getAuthority() { public void getAuthority() {
assertThat(Role.NOBODY.getAuthority()).isEmpty(); assertThat(Nobody.ROLE.authority()).isEqualTo(AuthoritiesConstants.USER);
assertThat(Role.HOSTMASTER.getAuthority()).hasValue(AuthoritiesConstants.HOSTMASTER); assertThat(Hostmaster.ROLE.authority()).isEqualTo(AuthoritiesConstants.HOSTMASTER);
assertThat(Role.ADMIN.getAuthority()).hasValue(AuthoritiesConstants.ADMIN); assertThat(Admin.ROLE.authority()).isEqualTo(AuthoritiesConstants.ADMIN);
assertThat(Role.SUPPORTER.getAuthority()).hasValue(AuthoritiesConstants.SUPPORTER); assertThat(Supporter.ROLE.authority()).isEqualTo(AuthoritiesConstants.SUPPORTER);
assertThat(Role.CUSTOMER_CONTRACTUAL_CONTACT.getAuthority()).isEmpty(); assertThat(Role.CustomerContractualContact.ROLE.authority()).isEqualTo(AuthoritiesConstants.USER);
assertThat(Role.ANYBODY.getAuthority()).hasValue(AuthoritiesConstants.ANONYMOUS); assertThat(Anybody.ROLE.authority()).isEqualTo(AuthoritiesConstants.ANONYMOUS);
} }
@Test @Test
public void isBroadest() { public void isBroadest() {
assertThat(Role.broadest(Role.HOSTMASTER, Role.CUSTOMER_CONTRACTUAL_CONTACT)).isEqualTo(Role.HOSTMASTER); assertThat(Role.broadest(Hostmaster.ROLE, Role.CustomerContractualContact.ROLE)).isEqualTo(Hostmaster.ROLE);
assertThat(Role.broadest(Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.HOSTMASTER)).isEqualTo(Role.HOSTMASTER); assertThat(Role.broadest(Role.CustomerContractualContact.ROLE, Hostmaster.ROLE)).isEqualTo(Hostmaster.ROLE);
assertThat(Role.broadest(Role.CUSTOMER_CONTRACTUAL_CONTACT, Role.ANY_CUSTOMER_USER)) assertThat(Role.broadest(Role.CustomerContractualContact.ROLE, Role.AnyCustomerUser.ROLE))
.isEqualTo(Role.CUSTOMER_CONTRACTUAL_CONTACT); .isEqualTo(Role.CustomerContractualContact.ROLE);
} }
@Test @Test
public void isAllowedToInit() { public void isAllowedToInit() {
assertThat(Role.HOSTMASTER.isAllowedToInit(someFieldWithoutAccessForAnnotation)).isFalse(); assertThat(Hostmaster.ROLE.isAllowedToInit(someFieldWithoutAccessForAnnotation)).isFalse();
assertThat(Role.SUPPORTER.isAllowedToInit(someFieldWithoutAccessForAnnotation)).isFalse(); assertThat(Supporter.ROLE.isAllowedToInit(someFieldWithoutAccessForAnnotation)).isFalse();
assertThat(Role.ADMIN.isAllowedToInit(someFieldWithAccessForAnnotation)).isTrue(); assertThat(Admin.ROLE.isAllowedToInit(someFieldWithAccessForAnnotation)).isTrue();
} }
@Test @Test
public void isAllowedToUpdate() { public void isAllowedToUpdate() {
assertThat(Role.HOSTMASTER.isAllowedToUpdate(someFieldWithoutAccessForAnnotation)).isFalse(); assertThat(Hostmaster.ROLE.isAllowedToUpdate(someFieldWithoutAccessForAnnotation)).isFalse();
assertThat(Role.ANY_CUSTOMER_CONTACT.isAllowedToUpdate(someFieldWithAccessForAnnotation)).isFalse(); assertThat(AnyCustomerContact.ROLE.isAllowedToUpdate(someFieldWithAccessForAnnotation)).isFalse();
assertThat(Role.SUPPORTER.isAllowedToUpdate(someFieldWithAccessForAnnotation)).isTrue(); assertThat(Supporter.ROLE.isAllowedToUpdate(someFieldWithAccessForAnnotation)).isTrue();
} }
@Test @Test
public void isAllowedToRead() { public void isAllowedToRead() {
assertThat(Role.HOSTMASTER.isAllowedToRead(someFieldWithoutAccessForAnnotation)).isFalse(); assertThat(Hostmaster.ROLE.isAllowedToRead(someFieldWithoutAccessForAnnotation)).isFalse();
assertThat(Role.ANY_CUSTOMER_USER.isAllowedToRead(someFieldWithAccessForAnnotation)).isFalse(); assertThat(Role.AnyCustomerUser.ROLE.isAllowedToRead(someFieldWithAccessForAnnotation)).isFalse();
assertThat(Role.ANY_CUSTOMER_CONTACT.isAllowedToRead(someFieldWithAccessForAnnotation)).isTrue(); assertThat(AnyCustomerContact.ROLE.isAllowedToRead(someFieldWithAccessForAnnotation)).isTrue();
} }
// --- only test fixture below --- // --- only test fixture below ---
static class TestDto { private static class TestDto {
@AccessFor(init = Role.ADMIN, update = Role.SUPPORTER, read = Role.ANY_CUSTOMER_CONTACT) @AccessFor(init = Admin.class, update = Supporter.class, read = AnyCustomerContact.class)
private Integer someFieldWithAccessForAnnotation; private Integer someFieldWithAccessForAnnotation;
@AccessFor(update = Role.IGNORED, read = Role.ANY_CUSTOMER_CONTACT) @AccessFor(update = Ignored.class, read = AnyCustomerContact.class)
private Integer someFieldWithAccessForAnnotationToBeIgnoredForUpdates; private Integer someFieldWithAccessForAnnotationToBeIgnoredForUpdates;
@AccessFor(update = { Role.IGNORED, Role.SUPPORTER }, read = Role.ANY_CUSTOMER_CONTACT) @AccessFor(update = { Ignored.class, Supporter.class }, read = AnyCustomerContact.class)
private Integer someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers; private Integer someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers;
private Integer someFieldWithoutAccessForAnnotation; private Integer someFieldWithoutAccessForAnnotation;

View File

@ -3,6 +3,11 @@ package org.hostsharing.hsadminng.service.accessfilter;
public class SecurityContextFake extends SecurityContextDouble<SecurityContextFake> { public class SecurityContextFake extends SecurityContextDouble<SecurityContextFake> {
public static SecurityContextFake havingUnauthenticatedUser() {
final SecurityContextFake securityContext = new SecurityContextFake();
return securityContext;
}
public static SecurityContextFake havingAuthenticatedUser() { public static SecurityContextFake havingAuthenticatedUser() {
return havingAuthenticatedUser("dummyUser"); return havingAuthenticatedUser("dummyUser");
} }

View File

@ -1,14 +1,9 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import static org.apache.commons.lang3.StringUtils.removeEnd; import org.apache.commons.lang3.RandomUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import org.hostsharing.hsadminng.service.accessfilter.*; import org.hostsharing.hsadminng.service.accessfilter.*;
import org.hostsharing.hsadminng.service.util.ReflectionUtil; import org.hostsharing.hsadminng.service.util.ReflectionUtil;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.jackson.JsonComponent; import org.springframework.boot.jackson.JsonComponent;
@ -21,6 +16,10 @@ import java.util.function.BiFunction;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.removeEnd;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
/** /**
* Usually base classes for unit tests are not a good idea, but because * Usually base classes for unit tests are not a good idea, but because
* DTOs which implement AccessMapping are more like a DSL, * DTOs which implement AccessMapping are more like a DSL,
@ -117,7 +116,7 @@ public abstract class AccessMappingsUnitTestBase<D> {
private final String[] namesOfFieldsWithAccessForAnnotation; private final String[] namesOfFieldsWithAccessForAnnotation;
private final String[] namesOfAccessibleFields; private final String[] namesOfAccessibleFields;
AccessRightsMatcher(final Class dtoClass, final Role role, final Function<AccessFor, Role[]> access) { AccessRightsMatcher(final Class dtoClass, final Role role, final Function<AccessFor, Class<? extends Role>[]> access) {
this.dtoClass = dtoClass; this.dtoClass = dtoClass;
this.role = role; this.role = role;
@ -159,10 +158,14 @@ public abstract class AccessMappingsUnitTestBase<D> {
return fieldsWithAccessForAnnotation; return fieldsWithAccessForAnnotation;
} }
private static boolean allows(final Field field, final Function<AccessFor, Role[]> access, final Role role) { private static boolean allows(
final Field field,
final Function<AccessFor, Class<? extends Role>[]> access,
final Role role) {
if (field.isAnnotationPresent(AccessFor.class)) { if (field.isAnnotationPresent(AccessFor.class)) {
final AccessFor accessFor = field.getAnnotation(AccessFor.class); final AccessFor accessFor = field.getAnnotation(AccessFor.class);
return role.coversAny(access.apply(accessFor)); Class<? extends Role>[] roleClasses = access.apply(accessFor);
return role.coversAny(roleClasses);
} }
return false; return false;
} }

View File

@ -1,11 +1,9 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.JsonProcessingException;
import static org.assertj.core.api.Assertions.catchThrowable; import com.fasterxml.jackson.databind.ObjectMapper;
import static org.junit.Assert.assertEquals; import org.apache.commons.lang3.RandomUtils;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.Asset; import org.hostsharing.hsadminng.domain.Asset;
import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.Membership; import org.hostsharing.hsadminng.domain.Membership;
@ -20,17 +18,14 @@ import org.hostsharing.hsadminng.service.MembershipValidator;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder; import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerFinancialContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock; import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.mapper.AssetMapper; import org.hostsharing.hsadminng.service.mapper.AssetMapper;
import org.hostsharing.hsadminng.service.mapper.AssetMapperImpl; import org.hostsharing.hsadminng.service.mapper.AssetMapperImpl;
import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl; import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl;
import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl; import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -43,12 +38,16 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import java.io.IOException; import java.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.Optional; import java.util.Optional;
import javax.persistence.EntityManager; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
@JsonTest @JsonTest
@SpringBootTest( @SpringBootTest(
@ -129,7 +128,7 @@ public class AssetDTOIntTest {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CUSTOMER_FINANCIAL_CONTACT); .withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.of(CustomerFinancialContact.class));
final AssetDTO given = createSomeAssetDTO(SOME_ASSET_ID); final AssetDTO given = createSomeAssetDTO(SOME_ASSET_ID);
@ -159,7 +158,7 @@ public class AssetDTOIntTest {
public void shouldNotDeserializeForContractualCustomerContact() { public void shouldNotDeserializeForContractualCustomerContact() {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CUSTOMER_CONTRACTUAL_CONTACT); .withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.of(CustomerContractualContact.class));
final String json = new JSonBuilder() final String json = new JSonBuilder()
.withFieldValue("id", SOME_ASSET_ID) .withFieldValue("id", SOME_ASSET_ID)
.withFieldValue("remark", "Updated Remark") .withFieldValue("remark", "Updated Remark")
@ -173,7 +172,7 @@ public class AssetDTOIntTest {
BadRequestAlertException.class, BadRequestAlertException.class,
bre -> assertThat(bre.getMessage()) bre -> assertThat(bre.getMessage())
.isEqualTo( .isEqualTo(
"Update of field AssetDTO.remark prohibited for current user role(s): CUSTOMER_CONTRACTUAL_CONTACT")); "Update of field AssetDTO.remark prohibited for current user role(s): CustomerContractualContact"));
} }
@Test @Test

View File

@ -1,12 +1,13 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import org.hostsharing.hsadminng.domain.enumeration.AssetAction;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.util.RandomUtil;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.RandomUtils;
import org.hostsharing.hsadminng.domain.enumeration.AssetAction;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.util.RandomUtil;
import org.junit.Test; import org.junit.Test;
import java.math.BigDecimal; import java.math.BigDecimal;
@ -20,22 +21,22 @@ public class AssetDTOUnitTest extends AccessMappingsUnitTestBase<AssetDTO> {
@Test @Test
public void shouldHaveProperAccessForAdmin() { public void shouldHaveProperAccessForAdmin() {
initAccessFor(AssetDTO.class, Role.ADMIN).shouldBeExactlyFor( initAccessFor(AssetDTO.class, Admin.ROLE).shouldBeExactlyFor(
"membershipId", "membershipId",
"documentDate", "documentDate",
"amount", "amount",
"action", "action",
"valueDate", "valueDate",
"remark"); "remark");
updateAccessFor(AssetDTO.class, Role.ADMIN).shouldBeExactlyFor("remark"); updateAccessFor(AssetDTO.class, Admin.ROLE).shouldBeExactlyFor("remark");
readAccessFor(AssetDTO.class, Role.ADMIN).shouldBeForAllFields(); readAccessFor(AssetDTO.class, Admin.ROLE).shouldBeForAllFields();
} }
@Test @Test
public void shouldHaveProperAccessForContractualContact() { public void shouldHaveProperAccessForContractualContact() {
initAccessFor(AssetDTO.class, Role.CUSTOMER_CONTRACTUAL_CONTACT).shouldBeForNothing(); initAccessFor(AssetDTO.class, CustomerContractualContact.ROLE).shouldBeForNothing();
updateAccessFor(AssetDTO.class, Role.CUSTOMER_CONTRACTUAL_CONTACT).shouldBeForNothing(); updateAccessFor(AssetDTO.class, CustomerContractualContact.ROLE).shouldBeForNothing();
readAccessFor(AssetDTO.class, Role.CUSTOMER_CONTRACTUAL_CONTACT).shouldBeExactlyFor( readAccessFor(AssetDTO.class, CustomerContractualContact.ROLE).shouldBeExactlyFor(
"id", "id",
"membershipId", "membershipId",
"documentDate", "documentDate",
@ -47,21 +48,21 @@ public class AssetDTOUnitTest extends AccessMappingsUnitTestBase<AssetDTO> {
@Test @Test
public void shouldHaveNoAccessForTechnicalContact() { public void shouldHaveNoAccessForTechnicalContact() {
initAccessFor(AssetDTO.class, Role.CUSTOMER_TECHNICAL_CONTACT).shouldBeForNothing(); initAccessFor(AssetDTO.class, Role.CustomerTechnicalContact.ROLE).shouldBeForNothing();
updateAccessFor(AssetDTO.class, Role.CUSTOMER_TECHNICAL_CONTACT).shouldBeForNothing(); updateAccessFor(AssetDTO.class, Role.CustomerTechnicalContact.ROLE).shouldBeForNothing();
readAccessFor(AssetDTO.class, Role.CUSTOMER_TECHNICAL_CONTACT).shouldBeForNothing(); readAccessFor(AssetDTO.class, Role.CustomerTechnicalContact.ROLE).shouldBeForNothing();
} }
@Test @Test
public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() { public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() {
initAccessFor(AssetDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing(); initAccessFor(AssetDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
updateAccessFor(AssetDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing(); updateAccessFor(AssetDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
readAccessFor(AssetDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing(); readAccessFor(AssetDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
} }
// --- only test fixture below --- // --- only test fixture below ---
public static AssetDTO createSampleDTO(final Long id, final Long parentId) { private static AssetDTO createSampleDTO(final Long id, final Long parentId) {
final AssetDTO dto = new AssetDTO(); final AssetDTO dto = new AssetDTO();
dto.setId(id); dto.setId(id);
dto.setDocumentDate(LocalDate.parse("2000-12-07")); dto.setDocumentDate(LocalDate.parse("2000-12-07"));
@ -74,7 +75,7 @@ public class AssetDTOUnitTest extends AccessMappingsUnitTestBase<AssetDTO> {
return dto; return dto;
} }
public static AssetDTO createRandomDTO(final Long id, final Long parentId) { private static AssetDTO createRandomDTO(final Long id, final Long parentId) {
final AssetDTO dto = new AssetDTO(); final AssetDTO dto = new AssetDTO();
dto.setId(id); dto.setId(id);
final LocalDate randomDate = LocalDate.parse("2000-12-07").plusDays(RandomUtils.nextInt(1, 999)); final LocalDate randomDate = LocalDate.parse("2000-12-07").plusDays(RandomUtils.nextInt(1, 999));

View File

@ -1,10 +1,8 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.JsonProcessingException;
import static org.junit.Assert.assertEquals; import com.fasterxml.jackson.databind.ObjectMapper;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.enumeration.CustomerKind; import org.hostsharing.hsadminng.domain.enumeration.CustomerKind;
import org.hostsharing.hsadminng.domain.enumeration.VatRegion; import org.hostsharing.hsadminng.domain.enumeration.VatRegion;
@ -14,13 +12,11 @@ import org.hostsharing.hsadminng.service.CustomerService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder; import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerTechnicalContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock; import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.mapper.CustomerMapper; import org.hostsharing.hsadminng.service.mapper.CustomerMapper;
import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl; import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -36,6 +32,10 @@ import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException; import java.io.IOException;
import java.util.Optional; import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
@JsonTest @JsonTest
@SpringBootTest( @SpringBootTest(
classes = { classes = {
@ -76,7 +76,7 @@ public class CustomerDTOUnitTest {
public void testSerializationAsContractualCustomerContact() throws JsonProcessingException { public void testSerializationAsContractualCustomerContact() throws JsonProcessingException {
// given // given
securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.CUSTOMER_CONTRACTUAL_CONTACT); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.of(CustomerContractualContact.class));
CustomerDTO given = createSomeCustomerDTO(1234L); CustomerDTO given = createSomeCustomerDTO(1234L);
// when // when
@ -91,7 +91,7 @@ public class CustomerDTOUnitTest {
public void testSerializationAsTechnicalCustomerUser() throws JsonProcessingException { public void testSerializationAsTechnicalCustomerUser() throws JsonProcessingException {
// given // given
securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.CUSTOMER_TECHNICAL_CONTACT); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.of(CustomerTechnicalContact.class));
CustomerDTO given = createSomeCustomerDTO(1234L); CustomerDTO given = createSomeCustomerDTO(1234L);
// when // when
@ -125,7 +125,7 @@ public class CustomerDTOUnitTest {
@Test @Test
public void testDeserializeAsContractualCustomerContact() throws IOException { public void testDeserializeAsContractualCustomerContact() throws IOException {
// given // given
securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.CUSTOMER_CONTRACTUAL_CONTACT); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.of(CustomerContractualContact.class));
given(customerRepository.findById(1234L)).willReturn(Optional.of(new Customer().id(1234L))); given(customerRepository.findById(1234L)).willReturn(Optional.of(new Customer().id(1234L)));
String json = "{\"id\":1234,\"contractualSalutation\":\"Hallo Updated\",\"billingSalutation\":\"Moin Updated\"}"; String json = "{\"id\":1234,\"contractualSalutation\":\"Hallo Updated\",\"billingSalutation\":\"Moin Updated\"}";

View File

@ -1,12 +1,9 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.JsonProcessingException;
import static org.assertj.core.api.Assertions.catchThrowable; import com.fasterxml.jackson.databind.ObjectMapper;
import static org.hostsharing.hsadminng.service.dto.MembershipDTOUnitTest.createSampleDTO; import org.apache.commons.lang3.RandomUtils;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.Membership; import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.repository.CustomerRepository; import org.hostsharing.hsadminng.repository.CustomerRepository;
@ -16,17 +13,13 @@ import org.hostsharing.hsadminng.service.MembershipService;
import org.hostsharing.hsadminng.service.MembershipValidator; import org.hostsharing.hsadminng.service.MembershipValidator;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder; import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerFinancialContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock; import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl; import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl;
import org.hostsharing.hsadminng.service.mapper.MembershipMapper; import org.hostsharing.hsadminng.service.mapper.MembershipMapper;
import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl; import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -39,11 +32,16 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import javax.persistence.EntityManager; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.dto.MembershipDTOUnitTest.createSampleDTO;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
@JsonTest @JsonTest
@SpringBootTest( @SpringBootTest(
@ -112,7 +110,7 @@ public class MembershipDTOIntTest {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CUSTOMER_FINANCIAL_CONTACT); .withRole(CustomerDTO.class, SOME_CUSTOMER_ID, CustomerFinancialContact.ROLE);
final MembershipDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID); final MembershipDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID);
// when // when
@ -141,7 +139,7 @@ public class MembershipDTOIntTest {
public void shouldNotDeserializeForContractualCustomerContact() { public void shouldNotDeserializeForContractualCustomerContact() {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CUSTOMER_CONTRACTUAL_CONTACT); .withRole(CustomerDTO.class, SOME_CUSTOMER_ID, CustomerContractualContact.ROLE);
final String json = new JSonBuilder() final String json = new JSonBuilder()
.withFieldValue("id", SOME_SEPA_MANDATE_ID) .withFieldValue("id", SOME_SEPA_MANDATE_ID)
.withFieldValue("remark", "Updated Remark") .withFieldValue("remark", "Updated Remark")
@ -154,7 +152,7 @@ public class MembershipDTOIntTest {
assertThat(actual).isInstanceOfSatisfying( assertThat(actual).isInstanceOfSatisfying(
BadRequestAlertException.class, BadRequestAlertException.class,
bre -> assertThat(bre.getMessage()).isEqualTo( bre -> assertThat(bre.getMessage()).isEqualTo(
"Update of field MembershipDTO.remark prohibited for current user role(s): CUSTOMER_CONTRACTUAL_CONTACT")); "Update of field MembershipDTO.remark prohibited for current user role(s): CustomerContractualContact"));
} }
@Test @Test

View File

@ -1,10 +1,13 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.RandomUtils;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerTechnicalContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.Supporter;
import org.junit.Test; import org.junit.Test;
import java.time.LocalDate; import java.time.LocalDate;
@ -17,32 +20,32 @@ public class MembershipDTOUnitTest extends AccessMappingsUnitTestBase<Membership
@Test @Test
public void shouldHaveProperAccessForAdmin() { public void shouldHaveProperAccessForAdmin() {
initAccessFor(MembershipDTO.class, Role.ADMIN).shouldBeExactlyFor( initAccessFor(MembershipDTO.class, Admin.ROLE).shouldBeExactlyFor(
"admissionDocumentDate", "admissionDocumentDate",
"cancellationDocumentDate", "cancellationDocumentDate",
"memberFromDate", "memberFromDate",
"memberUntilDate", "memberUntilDate",
"customerId", "customerId",
"remark"); "remark");
updateAccessFor(MembershipDTO.class, Role.ADMIN).shouldBeExactlyFor( updateAccessFor(MembershipDTO.class, Admin.ROLE).shouldBeExactlyFor(
"cancellationDocumentDate", "cancellationDocumentDate",
"memberUntilDate", "memberUntilDate",
"remark"); "remark");
readAccessFor(MembershipDTO.class, Role.ADMIN).shouldBeForAllFields(); readAccessFor(MembershipDTO.class, Admin.ROLE).shouldBeForAllFields();
} }
@Test @Test
public void shouldHaveProperAccessForSupporter() { public void shouldHaveProperAccessForSupporter() {
initAccessFor(MembershipDTO.class, Role.SUPPORTER).shouldBeForNothing(); initAccessFor(MembershipDTO.class, Supporter.ROLE).shouldBeForNothing();
updateAccessFor(MembershipDTO.class, Role.SUPPORTER).shouldBeForNothing(); updateAccessFor(MembershipDTO.class, Supporter.ROLE).shouldBeForNothing();
readAccessFor(MembershipDTO.class, Role.SUPPORTER).shouldBeForAllFields(); readAccessFor(MembershipDTO.class, Supporter.ROLE).shouldBeForAllFields();
} }
@Test @Test
public void shouldHaveProperAccessForContractualContact() { public void shouldHaveProperAccessForContractualContact() {
initAccessFor(MembershipDTO.class, Role.CUSTOMER_CONTRACTUAL_CONTACT).shouldBeForNothing(); initAccessFor(MembershipDTO.class, CustomerContractualContact.ROLE).shouldBeForNothing();
updateAccessFor(MembershipDTO.class, Role.CUSTOMER_CONTRACTUAL_CONTACT).shouldBeForNothing(); updateAccessFor(MembershipDTO.class, CustomerContractualContact.ROLE).shouldBeForNothing();
readAccessFor(MembershipDTO.class, Role.CUSTOMER_CONTRACTUAL_CONTACT).shouldBeExactlyFor( readAccessFor(MembershipDTO.class, CustomerContractualContact.ROLE).shouldBeExactlyFor(
"id", "id",
"admissionDocumentDate", "admissionDocumentDate",
"cancellationDocumentDate", "cancellationDocumentDate",
@ -56,21 +59,21 @@ public class MembershipDTOUnitTest extends AccessMappingsUnitTestBase<Membership
@Test @Test
public void shouldHaveNoAccessForTechnicalContact() { public void shouldHaveNoAccessForTechnicalContact() {
initAccessFor(MembershipDTO.class, Role.CUSTOMER_TECHNICAL_CONTACT).shouldBeForNothing(); initAccessFor(MembershipDTO.class, CustomerTechnicalContact.ROLE).shouldBeForNothing();
updateAccessFor(MembershipDTO.class, Role.CUSTOMER_TECHNICAL_CONTACT).shouldBeForNothing(); updateAccessFor(MembershipDTO.class, CustomerTechnicalContact.ROLE).shouldBeForNothing();
readAccessFor(MembershipDTO.class, Role.CUSTOMER_TECHNICAL_CONTACT).shouldBeForNothing(); readAccessFor(MembershipDTO.class, CustomerTechnicalContact.ROLE).shouldBeForNothing();
} }
@Test @Test
public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() { public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() {
initAccessFor(MembershipDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing(); initAccessFor(MembershipDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
updateAccessFor(MembershipDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing(); updateAccessFor(MembershipDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
readAccessFor(MembershipDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing(); readAccessFor(MembershipDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
} }
// --- only test fixture below --- // --- only test fixture below ---
public static MembershipDTO createSampleDTO(final Long id, final Long parentId) { static MembershipDTO createSampleDTO(final Long id, final Long parentId) {
final MembershipDTO dto = new MembershipDTO(); final MembershipDTO dto = new MembershipDTO();
dto.setId(id); dto.setId(id);
final LocalDate referenceDate = LocalDate.parse("2000-12-07"); final LocalDate referenceDate = LocalDate.parse("2000-12-07");

View File

@ -1,12 +1,9 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.JsonProcessingException;
import static org.assertj.core.api.Assertions.catchThrowable; import com.fasterxml.jackson.databind.ObjectMapper;
import static org.hostsharing.hsadminng.service.dto.SepaMandateDTOUnitTest.createSampleDTO; import org.apache.commons.lang3.RandomUtils;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.SepaMandate; import org.hostsharing.hsadminng.domain.SepaMandate;
import org.hostsharing.hsadminng.repository.CustomerRepository; import org.hostsharing.hsadminng.repository.CustomerRepository;
@ -18,17 +15,14 @@ import org.hostsharing.hsadminng.service.SepaMandateService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder; import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerFinancialContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock; import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl; import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl;
import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl; import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl;
import org.hostsharing.hsadminng.service.mapper.SepaMandateMapper; import org.hostsharing.hsadminng.service.mapper.SepaMandateMapper;
import org.hostsharing.hsadminng.service.mapper.SepaMandateMapperImpl; import org.hostsharing.hsadminng.service.mapper.SepaMandateMapperImpl;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -41,11 +35,16 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import javax.persistence.EntityManager; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.dto.SepaMandateDTOUnitTest.createSampleDTO;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
@JsonTest @JsonTest
@SpringBootTest( @SpringBootTest(
@ -117,7 +116,7 @@ public class SepaMandateDTOIntTest {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CUSTOMER_FINANCIAL_CONTACT); .withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.of(CustomerFinancialContact.class));
final SepaMandateDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID); final SepaMandateDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID);
// when // when
@ -146,7 +145,7 @@ public class SepaMandateDTOIntTest {
public void shouldNotDeserializeForContractualCustomerContact() { public void shouldNotDeserializeForContractualCustomerContact() {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CUSTOMER_CONTRACTUAL_CONTACT); .withRole(CustomerDTO.class, SOME_CUSTOMER_ID, CustomerContractualContact.ROLE);
final String json = new JSonBuilder() final String json = new JSonBuilder()
.withFieldValue("id", SOME_SEPA_MANDATE_ID) .withFieldValue("id", SOME_SEPA_MANDATE_ID)
.withFieldValue("remark", "Updated Remark") .withFieldValue("remark", "Updated Remark")
@ -159,7 +158,7 @@ public class SepaMandateDTOIntTest {
assertThat(actual).isInstanceOfSatisfying( assertThat(actual).isInstanceOfSatisfying(
BadRequestAlertException.class, BadRequestAlertException.class,
bre -> assertThat(bre.getMessage()).isEqualTo( bre -> assertThat(bre.getMessage()).isEqualTo(
"Update of field SepaMandateDTO.remark prohibited for current user role(s): CUSTOMER_CONTRACTUAL_CONTACT")); "Update of field SepaMandateDTO.remark prohibited for current user role(s): CustomerContractualContact"));
} }
@Test @Test

View File

@ -1,10 +1,13 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.RandomUtils;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerTechnicalContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.Supporter;
import org.junit.Test; import org.junit.Test;
import java.time.LocalDate; import java.time.LocalDate;
@ -17,7 +20,7 @@ public class SepaMandateDTOUnitTest extends AccessMappingsUnitTestBase<SepaManda
@Test @Test
public void shouldHaveProperAccessForAdmin() { public void shouldHaveProperAccessForAdmin() {
initAccessFor(SepaMandateDTO.class, Role.ADMIN).shouldBeExactlyFor( initAccessFor(SepaMandateDTO.class, Role.of(Admin.class)).shouldBeExactlyFor(
"grantingDocumentDate", "grantingDocumentDate",
"bic", "bic",
"remark", "remark",
@ -28,17 +31,17 @@ public class SepaMandateDTOUnitTest extends AccessMappingsUnitTestBase<SepaManda
"revokationDocumentDate", "revokationDocumentDate",
"lastUsedDate", "lastUsedDate",
"reference"); "reference");
updateAccessFor(SepaMandateDTO.class, Role.ADMIN).shouldBeExactlyFor( updateAccessFor(SepaMandateDTO.class, Role.of(Admin.class)).shouldBeExactlyFor(
"remark", "remark",
"validUntilDate", "validUntilDate",
"revokationDocumentDate", "revokationDocumentDate",
"lastUsedDate"); "lastUsedDate");
readAccessFor(SepaMandateDTO.class, Role.ADMIN).shouldBeForAllFields(); readAccessFor(SepaMandateDTO.class, Role.of(Admin.class)).shouldBeForAllFields();
} }
@Test @Test
public void shouldHaveProperAccessForSupporter() { public void shouldHaveProperAccessForSupporter() {
initAccessFor(SepaMandateDTO.class, Role.SUPPORTER).shouldBeExactlyFor( initAccessFor(SepaMandateDTO.class, Role.of(Supporter.class)).shouldBeExactlyFor(
"grantingDocumentDate", "grantingDocumentDate",
"bic", "bic",
"validUntilDate", "validUntilDate",
@ -46,16 +49,16 @@ public class SepaMandateDTOUnitTest extends AccessMappingsUnitTestBase<SepaManda
"validFromDate", "validFromDate",
"iban", "iban",
"reference"); "reference");
updateAccessFor(SepaMandateDTO.class, Role.SUPPORTER).shouldBeExactlyFor( updateAccessFor(SepaMandateDTO.class, Role.of(Supporter.class)).shouldBeExactlyFor(
"remark", "remark",
"validUntilDate", "validUntilDate",
"revokationDocumentDate"); "revokationDocumentDate");
readAccessFor(SepaMandateDTO.class, Role.SUPPORTER).shouldBeForAllFields(); readAccessFor(SepaMandateDTO.class, Role.of(Supporter.class)).shouldBeForAllFields();
} }
@Test @Test
public void shouldHaveProperAccessForContractualContact() { public void shouldHaveProperAccessForContractualContact() {
initAccessFor(SepaMandateDTO.class, Role.CUSTOMER_CONTRACTUAL_CONTACT).shouldBeExactlyFor( initAccessFor(SepaMandateDTO.class, Role.of(CustomerContractualContact.class)).shouldBeExactlyFor(
"grantingDocumentDate", "grantingDocumentDate",
"bic", "bic",
"validUntilDate", "validUntilDate",
@ -63,10 +66,10 @@ public class SepaMandateDTOUnitTest extends AccessMappingsUnitTestBase<SepaManda
"validFromDate", "validFromDate",
"iban", "iban",
"reference"); "reference");
updateAccessFor(SepaMandateDTO.class, Role.CUSTOMER_CONTRACTUAL_CONTACT).shouldBeExactlyFor( updateAccessFor(SepaMandateDTO.class, Role.of(CustomerContractualContact.class)).shouldBeExactlyFor(
"validUntilDate", "validUntilDate",
"revokationDocumentDate"); "revokationDocumentDate");
readAccessFor(SepaMandateDTO.class, Role.CUSTOMER_CONTRACTUAL_CONTACT).shouldBeExactlyFor( readAccessFor(SepaMandateDTO.class, Role.of(CustomerContractualContact.class)).shouldBeExactlyFor(
"grantingDocumentDate", "grantingDocumentDate",
"bic", "bic",
"id", "id",
@ -82,16 +85,16 @@ public class SepaMandateDTOUnitTest extends AccessMappingsUnitTestBase<SepaManda
@Test @Test
public void shouldHaveNoAccessForTechnicalContact() { public void shouldHaveNoAccessForTechnicalContact() {
initAccessFor(SepaMandateDTO.class, Role.CUSTOMER_TECHNICAL_CONTACT).shouldBeForNothing(); initAccessFor(SepaMandateDTO.class, Role.of(CustomerTechnicalContact.class)).shouldBeForNothing();
updateAccessFor(SepaMandateDTO.class, Role.CUSTOMER_TECHNICAL_CONTACT).shouldBeForNothing(); updateAccessFor(SepaMandateDTO.class, Role.of(CustomerTechnicalContact.class)).shouldBeForNothing();
readAccessFor(SepaMandateDTO.class, Role.CUSTOMER_TECHNICAL_CONTACT).shouldBeForNothing(); readAccessFor(SepaMandateDTO.class, Role.of(CustomerTechnicalContact.class)).shouldBeForNothing();
} }
@Test @Test
public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() { public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() {
initAccessFor(SepaMandateDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing(); initAccessFor(SepaMandateDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
updateAccessFor(SepaMandateDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing(); updateAccessFor(SepaMandateDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
readAccessFor(SepaMandateDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing(); readAccessFor(SepaMandateDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
} }
// --- only test fixture below --- // --- only test fixture below ---

View File

@ -1,11 +1,9 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.JsonProcessingException;
import static org.assertj.core.api.Assertions.catchThrowable; import com.fasterxml.jackson.databind.ObjectMapper;
import static org.junit.Assert.assertEquals; import org.apache.commons.lang3.RandomUtils;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.Membership; import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.domain.Share; import org.hostsharing.hsadminng.domain.Share;
@ -13,24 +11,20 @@ import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
import org.hostsharing.hsadminng.repository.CustomerRepository; import org.hostsharing.hsadminng.repository.CustomerRepository;
import org.hostsharing.hsadminng.repository.MembershipRepository; import org.hostsharing.hsadminng.repository.MembershipRepository;
import org.hostsharing.hsadminng.repository.ShareRepository; import org.hostsharing.hsadminng.repository.ShareRepository;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.MembershipValidator; import org.hostsharing.hsadminng.service.MembershipValidator;
import org.hostsharing.hsadminng.service.ShareService; import org.hostsharing.hsadminng.service.ShareService;
import org.hostsharing.hsadminng.service.ShareValidator; import org.hostsharing.hsadminng.service.ShareValidator;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder; import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerFinancialContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock; import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl; import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl;
import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl; import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl;
import org.hostsharing.hsadminng.service.mapper.ShareMapper; import org.hostsharing.hsadminng.service.mapper.ShareMapper;
import org.hostsharing.hsadminng.service.mapper.ShareMapperImpl; import org.hostsharing.hsadminng.service.mapper.ShareMapperImpl;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -43,11 +37,15 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import java.io.IOException; import java.io.IOException;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.Optional; import java.util.Optional;
import javax.persistence.EntityManager; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
@JsonTest @JsonTest
@SpringBootTest( @SpringBootTest(
@ -129,7 +127,7 @@ public class ShareDTOIntTest {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CUSTOMER_FINANCIAL_CONTACT); .withRole(CustomerDTO.class, SOME_CUSTOMER_ID, CustomerFinancialContact.ROLE);
final ShareDTO given = createSomeShareDTO(SOME_SHARE_ID); final ShareDTO given = createSomeShareDTO(SOME_SHARE_ID);
// when // when
@ -144,7 +142,7 @@ public class ShareDTOIntTest {
public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException { public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException {
// given // given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.SUPPORTER); securityContext.havingAuthenticatedUser().withAuthority(Role.Supporter.ROLE.authority());
final ShareDTO given = createSomeShareDTO(SOME_SHARE_ID); final ShareDTO given = createSomeShareDTO(SOME_SHARE_ID);
// when // when
@ -158,7 +156,7 @@ public class ShareDTOIntTest {
public void shouldNotDeserializeForContractualCustomerContact() { public void shouldNotDeserializeForContractualCustomerContact() {
// given // given
securityContext.havingAuthenticatedUser() securityContext.havingAuthenticatedUser()
.withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CUSTOMER_CONTRACTUAL_CONTACT); .withRole(CustomerDTO.class, SOME_CUSTOMER_ID, CustomerContractualContact.ROLE);
final String json = new JSonBuilder() final String json = new JSonBuilder()
.withFieldValue("id", SOME_SHARE_ID) .withFieldValue("id", SOME_SHARE_ID)
.withFieldValue("remark", "Updated Remark") .withFieldValue("remark", "Updated Remark")
@ -172,13 +170,13 @@ public class ShareDTOIntTest {
BadRequestAlertException.class, BadRequestAlertException.class,
bre -> assertThat(bre.getMessage()) bre -> assertThat(bre.getMessage())
.isEqualTo( .isEqualTo(
"Update of field ShareDTO.remark prohibited for current user role(s): CUSTOMER_CONTRACTUAL_CONTACT")); "Update of field ShareDTO.remark prohibited for current user role(s): CustomerContractualContact"));
} }
@Test @Test
public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException { public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException {
// given // given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN); securityContext.havingAuthenticatedUser().withAuthority(Role.Admin.ROLE.authority());
final String json = new JSonBuilder() final String json = new JSonBuilder()
.withFieldValue("id", SOME_SHARE_ID) .withFieldValue("id", SOME_SHARE_ID)
.withFieldValue("remark", "Updated Remark") .withFieldValue("remark", "Updated Remark")

View File

@ -1,12 +1,14 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.util.RandomUtil;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.RandomUtils;
import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerTechnicalContact;
import org.hostsharing.hsadminng.service.util.RandomUtil;
import org.junit.Test; import org.junit.Test;
import java.time.LocalDate; import java.time.LocalDate;
@ -19,22 +21,22 @@ public class ShareDTOUnitTest extends AccessMappingsUnitTestBase<ShareDTO> {
@Test @Test
public void shouldHaveProperAccessForAdmin() { public void shouldHaveProperAccessForAdmin() {
initAccessFor(ShareDTO.class, Role.ADMIN).shouldBeExactlyFor( initAccessFor(ShareDTO.class, Admin.ROLE).shouldBeExactlyFor(
"membershipId", "membershipId",
"documentDate", "documentDate",
"quantity", "quantity",
"action", "action",
"valueDate", "valueDate",
"remark"); "remark");
updateAccessFor(ShareDTO.class, Role.ADMIN).shouldBeExactlyFor("remark"); updateAccessFor(ShareDTO.class, Admin.ROLE).shouldBeExactlyFor("remark");
readAccessFor(ShareDTO.class, Role.ADMIN).shouldBeForAllFields(); readAccessFor(ShareDTO.class, Admin.ROLE).shouldBeForAllFields();
} }
@Test @Test
public void shouldHaveProperAccessForContractualContact() { public void shouldHaveProperAccessForContractualContact() {
initAccessFor(ShareDTO.class, Role.CUSTOMER_CONTRACTUAL_CONTACT).shouldBeForNothing(); initAccessFor(ShareDTO.class, CustomerContractualContact.ROLE).shouldBeForNothing();
updateAccessFor(ShareDTO.class, Role.CUSTOMER_CONTRACTUAL_CONTACT).shouldBeForNothing(); updateAccessFor(ShareDTO.class, CustomerContractualContact.ROLE).shouldBeForNothing();
readAccessFor(ShareDTO.class, Role.CUSTOMER_CONTRACTUAL_CONTACT).shouldBeExactlyFor( readAccessFor(ShareDTO.class, CustomerContractualContact.ROLE).shouldBeExactlyFor(
"id", "id",
"membershipId", "membershipId",
"documentDate", "documentDate",
@ -46,21 +48,21 @@ public class ShareDTOUnitTest extends AccessMappingsUnitTestBase<ShareDTO> {
@Test @Test
public void shouldHaveNoAccessForTechnicalContact() { public void shouldHaveNoAccessForTechnicalContact() {
initAccessFor(ShareDTO.class, Role.CUSTOMER_TECHNICAL_CONTACT).shouldBeForNothing(); initAccessFor(ShareDTO.class, CustomerTechnicalContact.ROLE).shouldBeForNothing();
updateAccessFor(ShareDTO.class, Role.CUSTOMER_TECHNICAL_CONTACT).shouldBeForNothing(); updateAccessFor(ShareDTO.class, CustomerTechnicalContact.ROLE).shouldBeForNothing();
readAccessFor(ShareDTO.class, Role.CUSTOMER_TECHNICAL_CONTACT).shouldBeForNothing(); readAccessFor(ShareDTO.class, CustomerTechnicalContact.ROLE).shouldBeForNothing();
} }
@Test @Test
public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() { public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() {
initAccessFor(ShareDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing(); initAccessFor(ShareDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
updateAccessFor(ShareDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing(); updateAccessFor(ShareDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
readAccessFor(ShareDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing(); readAccessFor(ShareDTO.class, Role.AnyCustomerUser.ROLE).shouldBeForNothing();
} }
// --- only test fixture below --- // --- only test fixture below ---
public static ShareDTO createSampleDTO(final Long id, final Long parentId) { private static ShareDTO createSampleDTO(final Long id, final Long parentId) {
final ShareDTO dto = new ShareDTO(); final ShareDTO dto = new ShareDTO();
dto.setId(id); dto.setId(id);
dto.setMembershipId(parentId); dto.setMembershipId(parentId);
@ -73,7 +75,7 @@ public class ShareDTOUnitTest extends AccessMappingsUnitTestBase<ShareDTO> {
return dto; return dto;
} }
public static ShareDTO createRandomDTO(final Long id, final Long parentId) { private static ShareDTO createRandomDTO(final Long id, final Long parentId) {
final ShareDTO dto = new ShareDTO(); final ShareDTO dto = new ShareDTO();
dto.setId(id); dto.setId(id);
dto.setMembershipId(parentId); dto.setMembershipId(parentId);

View File

@ -1,25 +1,17 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import static org.apache.commons.lang3.tuple.ImmutablePair.of; import com.fasterxml.jackson.core.JsonProcessingException;
import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.databind.ObjectMapper;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.Customer;
import org.hostsharing.hsadminng.domain.User; import org.hostsharing.hsadminng.domain.User;
import org.hostsharing.hsadminng.domain.UserRoleAssignment; import org.hostsharing.hsadminng.domain.UserRoleAssignment;
import org.hostsharing.hsadminng.repository.UserRepository; import org.hostsharing.hsadminng.repository.UserRepository;
import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository; import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder; import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock; import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -35,6 +27,11 @@ import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException; import java.io.IOException;
import java.util.Optional; import java.util.Optional;
import static org.apache.commons.lang3.tuple.ImmutablePair.of;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
@JsonTest @JsonTest
@SpringBootTest( @SpringBootTest(
classes = { classes = {
@ -45,9 +42,9 @@ import java.util.Optional;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
public class UserRoleAssignmentUnitTest { public class UserRoleAssignmentUnitTest {
public static final long USER_ROLE_ASSIGNMENT_ID = 1234L; private static final long USER_ROLE_ASSIGNMENT_ID = 1234L;
public static final long CUSTOMER_ID = 888L; private static final long CUSTOMER_ID = 888L;
public static final long USER_ID = 42L; private static final long USER_ID = 42L;
@Rule @Rule
public MockitoRule mockito = MockitoJUnit.rule(); public MockitoRule mockito = MockitoJUnit.rule();
@ -75,7 +72,11 @@ public class UserRoleAssignmentUnitTest {
public void testSerializationAsContractualCustomerContact() throws JsonProcessingException { public void testSerializationAsContractualCustomerContact() throws JsonProcessingException {
// given // given
securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, CUSTOMER_ID, Role.CUSTOMER_CONTRACTUAL_CONTACT); securityContext.havingAuthenticatedUser()
.withRole(
CustomerDTO.class,
CUSTOMER_ID,
Role.CustomerContractualContact.ROLE);
UserRoleAssignment given = createSomeUserRoleAssignment(USER_ROLE_ASSIGNMENT_ID); UserRoleAssignment given = createSomeUserRoleAssignment(USER_ROLE_ASSIGNMENT_ID);
// when // when
@ -89,7 +90,7 @@ public class UserRoleAssignmentUnitTest {
public void testSerializationAsSupporter() throws JsonProcessingException { public void testSerializationAsSupporter() throws JsonProcessingException {
// given // given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.SUPPORTER); securityContext.havingAuthenticatedUser().withAuthority(Role.Supporter.ROLE.authority());
UserRoleAssignment given = createSomeUserRoleAssignment(USER_ROLE_ASSIGNMENT_ID); UserRoleAssignment given = createSomeUserRoleAssignment(USER_ROLE_ASSIGNMENT_ID);
// when // when
@ -102,7 +103,7 @@ public class UserRoleAssignmentUnitTest {
@Test @Test
public void testDeserializeAsAdmin() throws IOException { public void testDeserializeAsAdmin() throws IOException {
// given // given
securityContext.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN); securityContext.havingAuthenticatedUser().withAuthority(Role.Admin.ROLE.authority());
given(userRoleAssignmentRepository.findById(USER_ROLE_ASSIGNMENT_ID)) given(userRoleAssignmentRepository.findById(USER_ROLE_ASSIGNMENT_ID))
.willReturn(Optional.of(new UserRoleAssignment().id(USER_ROLE_ASSIGNMENT_ID))); .willReturn(Optional.of(new UserRoleAssignment().id(USER_ROLE_ASSIGNMENT_ID)));
final User expectedUser = new User().id(USER_ID); final User expectedUser = new User().id(USER_ID);
@ -115,7 +116,7 @@ public class UserRoleAssignmentUnitTest {
"user", "user",
JSonBuilder.asJSon( JSonBuilder.asJSon(
of("id", USER_ID))), of("id", USER_ID))),
of("assignedRole", Role.CUSTOMER_TECHNICAL_CONTACT.name())); of("assignedRole", Role.CustomerTechnicalContact.ROLE.name()));
// when // when
UserRoleAssignment actual = objectMapper.readValue(json, UserRoleAssignment.class); UserRoleAssignment actual = objectMapper.readValue(json, UserRoleAssignment.class);
@ -125,11 +126,17 @@ public class UserRoleAssignmentUnitTest {
expected.setId(USER_ROLE_ASSIGNMENT_ID); expected.setId(USER_ROLE_ASSIGNMENT_ID);
expected.setEntityTypeId(Customer.ENTITY_TYPE_ID); expected.setEntityTypeId(Customer.ENTITY_TYPE_ID);
expected.setEntityObjectId(CUSTOMER_ID); expected.setEntityObjectId(CUSTOMER_ID);
expected.setAssignedRole(Role.CUSTOMER_TECHNICAL_CONTACT); expected.setAssignedRole(Role.CustomerTechnicalContact.ROLE);
expected.setUser(expectedUser); expected.setUser(expectedUser);
assertThat(actual).isEqualToComparingFieldByField(expected); assertThat(actual).isEqualToComparingFieldByField(expected);
} }
@Test
public void getAssignedRoleHandlesNullValue() {
assertThat(new UserRoleAssignment().assignedRole(null).getAssignedRole()).isNull();
assertThat(new UserRoleAssignment().assignedRole(Role.Admin.ROLE).getAssignedRole()).isEqualTo(Role.Admin.ROLE);
}
// --- only test fixture below --- // --- only test fixture below ---
public static String createExpectedJSon(UserRoleAssignment dto) { public static String createExpectedJSon(UserRoleAssignment dto) {
@ -148,7 +155,7 @@ public class UserRoleAssignmentUnitTest {
given.setEntityTypeId(Customer.ENTITY_TYPE_ID); given.setEntityTypeId(Customer.ENTITY_TYPE_ID);
given.setEntityObjectId(CUSTOMER_ID); given.setEntityObjectId(CUSTOMER_ID);
given.setUser(new User().id(USER_ID)); given.setUser(new User().id(USER_ID));
given.setAssignedRole(Role.CUSTOMER_TECHNICAL_CONTACT); given.setAssignedRole(Role.CustomerTechnicalContact.ROLE);
return given; return given;
} }
} }

View File

@ -1,26 +1,19 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest; package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.domain.Asset; import org.hostsharing.hsadminng.domain.Asset;
import org.hostsharing.hsadminng.domain.Membership; import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.domain.enumeration.AssetAction; import org.hostsharing.hsadminng.domain.enumeration.AssetAction;
import org.hostsharing.hsadminng.repository.AssetRepository; import org.hostsharing.hsadminng.repository.AssetRepository;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.AssetQueryService; import org.hostsharing.hsadminng.service.AssetQueryService;
import org.hostsharing.hsadminng.service.AssetService; import org.hostsharing.hsadminng.service.AssetService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock; import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.dto.AssetDTO; import org.hostsharing.hsadminng.service.dto.AssetDTO;
import org.hostsharing.hsadminng.service.mapper.AssetMapper; import org.hostsharing.hsadminng.service.mapper.AssetMapper;
import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator; import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -37,13 +30,18 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator; import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.ZoneId; import java.time.ZoneId;
import java.util.List; import java.util.List;
import javax.persistence.EntityManager; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/** /**
* Test class for the AssetResource REST controller. * Test class for the AssetResource REST controller.
@ -107,7 +105,7 @@ public class AssetResourceIntTest {
public void setup() { public void setup() {
SecurityContextMock.usingMock(userRoleAssignmentService) SecurityContextMock.usingMock(userRoleAssignmentService)
.havingAuthenticatedUser() .havingAuthenticatedUser()
.withAuthority(AuthoritiesConstants.ADMIN); .withAuthority(Role.Admin.ROLE.authority());
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
final AssetResource assetResource = new AssetResource(assetService, assetQueryService); final AssetResource assetResource = new AssetResource(assetService, assetQueryService);

View File

@ -1,26 +1,19 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest; package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.domain.Membership; import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.domain.Share; import org.hostsharing.hsadminng.domain.Share;
import org.hostsharing.hsadminng.domain.enumeration.ShareAction; import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
import org.hostsharing.hsadminng.repository.ShareRepository; import org.hostsharing.hsadminng.repository.ShareRepository;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.ShareQueryService; import org.hostsharing.hsadminng.service.ShareQueryService;
import org.hostsharing.hsadminng.service.ShareService; import org.hostsharing.hsadminng.service.ShareService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock; import org.hostsharing.hsadminng.service.accessfilter.SecurityContextMock;
import org.hostsharing.hsadminng.service.dto.ShareDTO; import org.hostsharing.hsadminng.service.dto.ShareDTO;
import org.hostsharing.hsadminng.service.mapper.ShareMapper; import org.hostsharing.hsadminng.service.mapper.ShareMapper;
import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator; import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -37,11 +30,16 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator; import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.ZoneId; import java.time.ZoneId;
import java.util.List; import java.util.List;
import javax.persistence.EntityManager; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/** /**
* Test class for the ShareResource REST controller. * Test class for the ShareResource REST controller.
@ -105,7 +103,7 @@ public class ShareResourceIntTest {
public void setup() { public void setup() {
SecurityContextMock.usingMock(userRoleAssignmentService) SecurityContextMock.usingMock(userRoleAssignmentService)
.havingAuthenticatedUser() .havingAuthenticatedUser()
.withAuthority(AuthoritiesConstants.ADMIN); .withAuthority(Role.Admin.ROLE.authority());
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
final ShareResource shareResource = new ShareResource(shareService, shareQueryService); final ShareResource shareResource = new ShareResource(shareService, shareQueryService);

View File

@ -1,23 +1,18 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.web.rest; package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.HsadminNgApp;
import org.hostsharing.hsadminng.domain.User; import org.hostsharing.hsadminng.domain.User;
import org.hostsharing.hsadminng.domain.UserRoleAssignment; import org.hostsharing.hsadminng.domain.UserRoleAssignment;
import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository; import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import org.hostsharing.hsadminng.service.UserRoleAssignmentQueryService; import org.hostsharing.hsadminng.service.UserRoleAssignmentQueryService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService; import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.accessfilter.Role.Admin;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerContractualContact;
import org.hostsharing.hsadminng.service.accessfilter.Role.CustomerTechnicalContact;
import org.hostsharing.hsadminng.service.accessfilter.SecurityContextFake; import org.hostsharing.hsadminng.service.accessfilter.SecurityContextFake;
import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator; import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -33,9 +28,14 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator; import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.util.List; import java.util.List;
import javax.persistence.EntityManager; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/** /**
* Test class for the UserRoleAssignmentResource REST controller. * Test class for the UserRoleAssignmentResource REST controller.
@ -43,7 +43,7 @@ import javax.persistence.EntityManager;
* @see UserRoleAssignmentResource * @see UserRoleAssignmentResource
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = HsadminNgApp.class) @SpringBootTest(classes = { HsadminNgApp.class })
public class UserRoleAssignmentResourceIntTest { public class UserRoleAssignmentResourceIntTest {
private static final String DEFAULT_ENTITY_TYPE_ID = "AAAAAAAAAA"; private static final String DEFAULT_ENTITY_TYPE_ID = "AAAAAAAAAA";
@ -52,8 +52,8 @@ public class UserRoleAssignmentResourceIntTest {
private static final Long DEFAULT_ENTITY_OBJECT_ID = 1L; private static final Long DEFAULT_ENTITY_OBJECT_ID = 1L;
private static final Long UPDATED_ENTITY_OBJECT_ID = 2L; private static final Long UPDATED_ENTITY_OBJECT_ID = 2L;
private static final Role DEFAULT_ASSIGNED_ROLE = Role.HOSTMASTER; private static final Role DEFAULT_ASSIGNED_ROLE = CustomerTechnicalContact.ROLE;
private static final Role UPDATED_ASSIGNED_ROLE = Role.ADMIN; private static final Role UPDATED_ASSIGNED_ROLE = CustomerContractualContact.ROLE;
@Autowired @Autowired
private UserRoleAssignmentRepository userRoleAssignmentRepository; private UserRoleAssignmentRepository userRoleAssignmentRepository;
@ -97,7 +97,7 @@ public class UserRoleAssignmentResourceIntTest {
.setValidator(validator) .setValidator(validator)
.build(); .build();
SecurityContextFake.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.SUPPORTER); SecurityContextFake.havingAuthenticatedUser().withAuthority(Role.Supporter.ROLE.authority());
} }
/** /**
@ -110,12 +110,11 @@ public class UserRoleAssignmentResourceIntTest {
User user = UserResourceIntTest.createEntity(em); User user = UserResourceIntTest.createEntity(em);
em.persist(user); em.persist(user);
em.flush(); em.flush();
UserRoleAssignment userRoleAssignment = new UserRoleAssignment() return new UserRoleAssignment()
.entityTypeId(DEFAULT_ENTITY_TYPE_ID) .entityTypeId(DEFAULT_ENTITY_TYPE_ID)
.entityObjectId(DEFAULT_ENTITY_OBJECT_ID) .entityObjectId(DEFAULT_ENTITY_OBJECT_ID)
.user(user) .user(user)
.assignedRole(DEFAULT_ASSIGNED_ROLE); .assignedRole(DEFAULT_ASSIGNED_ROLE);
return userRoleAssignment;
} }
@Before @Before
@ -129,7 +128,7 @@ public class UserRoleAssignmentResourceIntTest {
int databaseSizeBeforeCreate = userRoleAssignmentRepository.findAll().size(); int databaseSizeBeforeCreate = userRoleAssignmentRepository.findAll().size();
// Create the UserRoleAssignment // Create the UserRoleAssignment
SecurityContextFake.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN); SecurityContextFake.havingAuthenticatedUser().withAuthority(Admin.ROLE.authority());
restUserRoleAssignmentMockMvc.perform( restUserRoleAssignmentMockMvc.perform(
post("/api/user-role-assignments") post("/api/user-role-assignments")
.contentType(TestUtil.APPLICATION_JSON_UTF8) .contentType(TestUtil.APPLICATION_JSON_UTF8)
@ -142,6 +141,7 @@ public class UserRoleAssignmentResourceIntTest {
UserRoleAssignment testUserRoleAssignment = userRoleAssignmentList.get(userRoleAssignmentList.size() - 1); UserRoleAssignment testUserRoleAssignment = userRoleAssignmentList.get(userRoleAssignmentList.size() - 1);
assertThat(testUserRoleAssignment.getEntityTypeId()).isEqualTo(DEFAULT_ENTITY_TYPE_ID); assertThat(testUserRoleAssignment.getEntityTypeId()).isEqualTo(DEFAULT_ENTITY_TYPE_ID);
assertThat(testUserRoleAssignment.getEntityObjectId()).isEqualTo(DEFAULT_ENTITY_OBJECT_ID); assertThat(testUserRoleAssignment.getEntityObjectId()).isEqualTo(DEFAULT_ENTITY_OBJECT_ID);
assertThat(testUserRoleAssignment.getAssignedRole().name()).isEqualTo(DEFAULT_ASSIGNED_ROLE.name());
assertThat(testUserRoleAssignment.getAssignedRole()).isEqualTo(DEFAULT_ASSIGNED_ROLE); assertThat(testUserRoleAssignment.getAssignedRole()).isEqualTo(DEFAULT_ASSIGNED_ROLE);
} }
@ -233,9 +233,9 @@ public class UserRoleAssignmentResourceIntTest {
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(userRoleAssignment.getId().intValue()))) .andExpect(jsonPath("$.[*].id").value(hasItem(userRoleAssignment.getId().intValue())))
.andExpect(jsonPath("$.[*].entityTypeId").value(hasItem(DEFAULT_ENTITY_TYPE_ID.toString()))) .andExpect(jsonPath("$.[*].entityTypeId").value(hasItem(DEFAULT_ENTITY_TYPE_ID)))
.andExpect(jsonPath("$.[*].entityObjectId").value(hasItem(DEFAULT_ENTITY_OBJECT_ID.intValue()))) .andExpect(jsonPath("$.[*].entityObjectId").value(hasItem(DEFAULT_ENTITY_OBJECT_ID.intValue())))
.andExpect(jsonPath("$.[*].assignedRole").value(hasItem(DEFAULT_ASSIGNED_ROLE.toString()))); .andExpect(jsonPath("$.[*].assignedRole").value(hasItem(DEFAULT_ASSIGNED_ROLE.name())));
} }
@Test @Test
@ -249,9 +249,9 @@ public class UserRoleAssignmentResourceIntTest {
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(userRoleAssignment.getId().intValue())) .andExpect(jsonPath("$.id").value(userRoleAssignment.getId().intValue()))
.andExpect(jsonPath("$.entityTypeId").value(DEFAULT_ENTITY_TYPE_ID.toString())) .andExpect(jsonPath("$.entityTypeId").value(DEFAULT_ENTITY_TYPE_ID))
.andExpect(jsonPath("$.entityObjectId").value(DEFAULT_ENTITY_OBJECT_ID.intValue())) .andExpect(jsonPath("$.entityObjectId").value(DEFAULT_ENTITY_OBJECT_ID.intValue()))
.andExpect(jsonPath("$.assignedRole").value(DEFAULT_ASSIGNED_ROLE.toString())); .andExpect(jsonPath("$.assignedRole").value(DEFAULT_ASSIGNED_ROLE.name()));
} }
@Test @Test
@ -366,10 +366,10 @@ public class UserRoleAssignmentResourceIntTest {
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where assignedRole equals to DEFAULT_ASSIGNED_ROLE // Get all the userRoleAssignmentList where assignedRole equals to DEFAULT_ASSIGNED_ROLE
defaultUserRoleAssignmentShouldBeFound("assignedRole.equals=" + DEFAULT_ASSIGNED_ROLE); defaultUserRoleAssignmentShouldBeFound("assignedRole.equals=" + DEFAULT_ASSIGNED_ROLE.name());
// Get all the userRoleAssignmentList where assignedRole equals to UPDATED_ASSIGNED_ROLE // Get all the userRoleAssignmentList where assignedRole equals to UPDATED_ASSIGNED_ROLE
defaultUserRoleAssignmentShouldNotBeFound("assignedRole.equals=" + UPDATED_ASSIGNED_ROLE); defaultUserRoleAssignmentShouldNotBeFound("assignedRole.equals=" + UPDATED_ASSIGNED_ROLE.name());
} }
@Test @Test
@ -379,10 +379,11 @@ public class UserRoleAssignmentResourceIntTest {
userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); userRoleAssignmentRepository.saveAndFlush(userRoleAssignment);
// Get all the userRoleAssignmentList where assignedRole in DEFAULT_ASSIGNED_ROLE or UPDATED_ASSIGNED_ROLE // Get all the userRoleAssignmentList where assignedRole in DEFAULT_ASSIGNED_ROLE or UPDATED_ASSIGNED_ROLE
defaultUserRoleAssignmentShouldBeFound("assignedRole.in=" + DEFAULT_ASSIGNED_ROLE + "," + UPDATED_ASSIGNED_ROLE); defaultUserRoleAssignmentShouldBeFound(
"assignedRole.in=" + DEFAULT_ASSIGNED_ROLE.name() + "," + UPDATED_ASSIGNED_ROLE.name());
// Get all the userRoleAssignmentList where assignedRole equals to UPDATED_ASSIGNED_ROLE // Get all the userRoleAssignmentList where assignedRole equals to UPDATED_ASSIGNED_ROLE
defaultUserRoleAssignmentShouldNotBeFound("assignedRole.in=" + UPDATED_ASSIGNED_ROLE); defaultUserRoleAssignmentShouldNotBeFound("assignedRole.in=" + UPDATED_ASSIGNED_ROLE.name());
} }
@Test @Test
@ -426,7 +427,7 @@ public class UserRoleAssignmentResourceIntTest {
.andExpect(jsonPath("$.[*].id").value(hasItem(userRoleAssignment.getId().intValue()))) .andExpect(jsonPath("$.[*].id").value(hasItem(userRoleAssignment.getId().intValue())))
.andExpect(jsonPath("$.[*].entityTypeId").value(hasItem(DEFAULT_ENTITY_TYPE_ID))) .andExpect(jsonPath("$.[*].entityTypeId").value(hasItem(DEFAULT_ENTITY_TYPE_ID)))
.andExpect(jsonPath("$.[*].entityObjectId").value(hasItem(DEFAULT_ENTITY_OBJECT_ID.intValue()))) .andExpect(jsonPath("$.[*].entityObjectId").value(hasItem(DEFAULT_ENTITY_OBJECT_ID.intValue())))
.andExpect(jsonPath("$.[*].assignedRole").value(hasItem(DEFAULT_ASSIGNED_ROLE.toString()))); .andExpect(jsonPath("$.[*].assignedRole").value(hasItem(DEFAULT_ASSIGNED_ROLE.name())));
// Check, that the count call also returns 1 // Check, that the count call also returns 1
restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments/count?sort=id,desc&" + filter)) restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments/count?sort=id,desc&" + filter))
@ -469,7 +470,7 @@ public class UserRoleAssignmentResourceIntTest {
int databaseSizeBeforeUpdate = userRoleAssignmentRepository.findAll().size(); int databaseSizeBeforeUpdate = userRoleAssignmentRepository.findAll().size();
// Update the userRoleAssignment // Update the userRoleAssignment
SecurityContextFake.havingAuthenticatedUser().withAuthority(AuthoritiesConstants.ADMIN); SecurityContextFake.havingAuthenticatedUser().withAuthority(Admin.ROLE.authority());
UserRoleAssignment updatedUserRoleAssignment = userRoleAssignmentRepository.findById(userRoleAssignment.getId()).get(); UserRoleAssignment updatedUserRoleAssignment = userRoleAssignmentRepository.findById(userRoleAssignment.getId()).get();
// Disconnect from session so that the updates on updatedUserRoleAssignment are not directly saved in db // Disconnect from session so that the updates on updatedUserRoleAssignment are not directly saved in db
em.detach(updatedUserRoleAssignment); em.detach(updatedUserRoleAssignment);
@ -490,6 +491,7 @@ public class UserRoleAssignmentResourceIntTest {
UserRoleAssignment testUserRoleAssignment = userRoleAssignmentList.get(userRoleAssignmentList.size() - 1); UserRoleAssignment testUserRoleAssignment = userRoleAssignmentList.get(userRoleAssignmentList.size() - 1);
assertThat(testUserRoleAssignment.getEntityTypeId()).isEqualTo(UPDATED_ENTITY_TYPE_ID); assertThat(testUserRoleAssignment.getEntityTypeId()).isEqualTo(UPDATED_ENTITY_TYPE_ID);
assertThat(testUserRoleAssignment.getEntityObjectId()).isEqualTo(UPDATED_ENTITY_OBJECT_ID); assertThat(testUserRoleAssignment.getEntityObjectId()).isEqualTo(UPDATED_ENTITY_OBJECT_ID);
assertThat(testUserRoleAssignment.getAssignedRole().name()).isEqualTo(UPDATED_ASSIGNED_ROLE.name());
assertThat(testUserRoleAssignment.getAssignedRole()).isEqualTo(UPDATED_ASSIGNED_ROLE); assertThat(testUserRoleAssignment.getAssignedRole()).isEqualTo(UPDATED_ASSIGNED_ROLE);
} }