#112 [RightsModule] use UserRoleAssignments from database

This commit is contained in:
Michael Hoennig 2019-05-10 11:18:15 +02:00
parent 01d28a85d4
commit 72e79e2134
36 changed files with 680 additions and 289 deletions

View File

@ -3,8 +3,6 @@ package org.hostsharing.hsadminng;
import org.hostsharing.hsadminng.config.ApplicationProperties; import org.hostsharing.hsadminng.config.ApplicationProperties;
import org.hostsharing.hsadminng.config.DefaultProfileUtil; import org.hostsharing.hsadminng.config.DefaultProfileUtil;
import org.hostsharing.hsadminng.security.SecurityUtils;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterConstants;
@ -60,14 +58,6 @@ public class HsadminNgApp {
"You have misconfigured your application! It should not " + "You have misconfigured your application! It should not " +
"run with both the 'dev' and 'cloud' profiles at the same time."); "run with both the 'dev' and 'cloud' profiles at the same time.");
} }
// TODO: remove this hack once proper user roles are implemented
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
// For some strange reasons, HsadminNgApp is created in locally running tests,
// but not on Jenkins, therefore the login user had no rights and many tests
// failed.
SecurityUtils.addUserRole(null, null, Role.HOSTMASTER);
}
} }
/** /**

View File

@ -36,6 +36,10 @@ public class CacheConfiguration {
cm.createCache(org.hostsharing.hsadminng.repository.UserRepository.USERS_BY_LOGIN_CACHE, jcacheConfiguration); cm.createCache(org.hostsharing.hsadminng.repository.UserRepository.USERS_BY_LOGIN_CACHE, jcacheConfiguration);
cm.createCache(org.hostsharing.hsadminng.repository.UserRepository.USERS_BY_EMAIL_CACHE, jcacheConfiguration); cm.createCache(org.hostsharing.hsadminng.repository.UserRepository.USERS_BY_EMAIL_CACHE, jcacheConfiguration);
// jhipster-needle-ehcache-add-entry // jhipster-needle-ehcache-add-entry
cm.createCache(
org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository.CURRENT_USER_ROLE_ASSIGNMENTS_CACHE,
jcacheConfiguration);
}; };
} }
} }

View File

@ -1,7 +1,7 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.domain; package org.hostsharing.hsadminng.domain;
import org.hostsharing.hsadminng.domain.enumeration.UserRole; import org.hostsharing.hsadminng.service.accessfilter.Role;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@ -37,13 +37,14 @@ public class UserRoleAssignment implements Serializable {
@NotNull @NotNull
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
@Column(name = "assigned_role", nullable = false) @Column(name = "assigned_role", nullable = false)
private UserRole assignedRole; private Role assignedRole;
@ManyToOne @ManyToOne
@JsonIgnoreProperties("requireds") @JsonIgnoreProperties("requireds")
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
public Long getId() { public Long getId() {
return id; return id;
} }
@ -78,16 +79,16 @@ public class UserRoleAssignment implements Serializable {
this.entityObjectId = entityObjectId; this.entityObjectId = entityObjectId;
} }
public UserRole getAssignedRole() { public Role getAssignedRole() {
return assignedRole; return assignedRole;
} }
public UserRoleAssignment assignedRole(UserRole assignedRole) { public UserRoleAssignment assignedRole(Role assignedRole) {
this.assignedRole = assignedRole; this.assignedRole = assignedRole;
return this; return this;
} }
public void setAssignedRole(UserRole assignedRole) { public void setAssignedRole(Role assignedRole) {
this.assignedRole = assignedRole; this.assignedRole = assignedRole;
} }
@ -103,6 +104,7 @@ public class UserRoleAssignment implements Serializable {
public void setUser(User user) { public void setUser(User user) {
this.user = user; this.user = user;
} }
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override @Override

View File

@ -1,15 +0,0 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.domain.enumeration;
/**
* The UserRole enumeration.
*/
public enum UserRole {
HOSTMASTER,
ADMIN,
SUPPORTER,
CONTRACTUAL_CONTACT,
FINANCIAL_CONTACT,
TECHNICAL_CONTACT,
CUSTOMER_USER
}

View File

@ -3,7 +3,10 @@ package org.hostsharing.hsadminng.repository;
import org.hostsharing.hsadminng.domain.UserRoleAssignment; import org.hostsharing.hsadminng.domain.UserRoleAssignment;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.*; import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List; import java.util.List;
@ -16,7 +19,14 @@ import java.util.List;
public interface UserRoleAssignmentRepository public interface UserRoleAssignmentRepository
extends JpaRepository<UserRoleAssignment, Long>, JpaSpecificationExecutor<UserRoleAssignment> { extends JpaRepository<UserRoleAssignment, Long>, JpaSpecificationExecutor<UserRoleAssignment> {
@Query("select user_role_assignment from UserRoleAssignment user_role_assignment where user_role_assignment.user.login = ?#{principal.username}") String CURRENT_USER_ROLE_ASSIGNMENTS_CACHE = "currentUserRoleAssignments";
List<UserRoleAssignment> findByUserIsCurrentUser();
// TODO mhoennig: optimize with query by id
@Cacheable(CURRENT_USER_ROLE_ASSIGNMENTS_CACHE)
@Query("select user_role_assignment from UserRoleAssignment user_role_assignment where user_role_assignment.user.login = :login")
List<UserRoleAssignment> findByLogin(@Param("login") final String login);
@CacheEvict(value = CURRENT_USER_ROLE_ASSIGNMENTS_CACHE, allEntries = true)
default void evictCache() {
}
} }

View File

@ -1,16 +1,12 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.security; package org.hostsharing.hsadminng.security;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional; import java.util.Optional;
/** /**
@ -20,8 +16,6 @@ public final class SecurityUtils {
private static final Logger log = LoggerFactory.getLogger(SecurityUtils.class); private static final Logger log = LoggerFactory.getLogger(SecurityUtils.class);
private static List<UserRoleAssignment> userRoleAssignments = new ArrayList<>();
private SecurityUtils() { private SecurityUtils() {
} }
@ -83,52 +77,12 @@ public final class SecurityUtils {
*/ */
public static boolean isCurrentUserInRole(String authority) { public static boolean isCurrentUserInRole(String authority) {
SecurityContext securityContext = SecurityContextHolder.getContext(); SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication()) final Boolean isCurrentUserInRole = Optional.ofNullable(securityContext.getAuthentication())
.map( .map(
authentication -> authentication.getAuthorities() authentication -> authentication.getAuthorities()
.stream() .stream()
.anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority))) .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority)))
.orElse(false); .orElse(false);
} return isCurrentUserInRole;
public static Role getLoginUserRoleFor(final Class<?> onDtoClass, final Long onId) {
final Role highestRole = userRoleAssignments.stream()
.map(
ura -> matches(onDtoClass, onId, ura)
? ura.role
: Role.ANYBODY)
.reduce(Role.ANYBODY, (r1, r2) -> r1.covers(r2) ? r1 : r2);
log.debug("getLoginUserRoleFor({}, {}) returned {}", onDtoClass, onId, highestRole);
return highestRole;
}
private static boolean matches(Class<?> onDtoClass, Long onId, UserRoleAssignment ura) {
final boolean matches = (ura.onClass == null || onDtoClass == ura.onClass)
&& (ura.onId == null || ura.onId.equals(onId));
return matches;
}
// TODO: depends on https://plan.hostsharing.net/project/hsadmin/us/67?milestone=34
public static void addUserRole(final Class<?> onClass, final Long onId, final Role role) {
log.info("addUserRole({}, {}, {})", onClass, onId, role);
userRoleAssignments.add(new UserRoleAssignment(onClass, onId, role));
}
public static void clearUserRoles() {
userRoleAssignments.clear();
}
private static class UserRoleAssignment {
final Class<?> onClass;
final Long onId;
final Role role;
UserRoleAssignment(Class<?> onClass, Long onId, Role role) {
this.onClass = onClass;
this.onId = onId;
this.role = role;
}
} }
} }

View File

@ -1,8 +1,13 @@
// Licensed under Apache-2.0 // Licensed under Apache-2.0
package org.hostsharing.hsadminng.service; package org.hostsharing.hsadminng.service;
import static com.google.common.base.Verify.verify;
import org.hostsharing.hsadminng.domain.UserRoleAssignment; import org.hostsharing.hsadminng.domain.UserRoleAssignment;
import org.hostsharing.hsadminng.repository.UserRepository;
import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository; import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository;
import org.hostsharing.hsadminng.security.SecurityUtils;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -11,7 +16,10 @@ import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.Optional; import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/** /**
* Service Implementation for managing UserRoleAssignment. * Service Implementation for managing UserRoleAssignment.
@ -24,7 +32,9 @@ public class UserRoleAssignmentService {
private final UserRoleAssignmentRepository userRoleAssignmentRepository; private final UserRoleAssignmentRepository userRoleAssignmentRepository;
public UserRoleAssignmentService(UserRoleAssignmentRepository userRoleAssignmentRepository) { public UserRoleAssignmentService(
final UserRepository userRepository,
final UserRoleAssignmentRepository userRoleAssignmentRepository) {
this.userRoleAssignmentRepository = userRoleAssignmentRepository; this.userRoleAssignmentRepository = userRoleAssignmentRepository;
} }
@ -72,4 +82,30 @@ public class UserRoleAssignmentService {
log.debug("Request to delete UserRoleAssignment : {}", id); log.debug("Request to delete UserRoleAssignment : {}", id);
userRoleAssignmentRepository.deleteById(id); userRoleAssignmentRepository.deleteById(id);
} }
/**
* Collects all roles assigned to the current login user for the specified entity.
*
* @param entityTypeId the type id of the entity, e.g. "customer.Customer", not null
* @param entityObjectId id of entity instance in given entity type
* @return a set of all roles assigned to the current login user
*/
public Set<Role> getEffectiveRoleOfCurrentUser(final String entityTypeId, final long entityObjectId) {
verify(entityTypeId != null);
// findByLogin is cached, thus I presume this is faster more specific query which would result in many DB roundtrips
final Set<Role> roles = SecurityUtils.getCurrentUserLogin()
.map(
login -> userRoleAssignmentRepository.findByLogin(login)
.stream()
.filter(ura -> matches(entityTypeId, entityObjectId, ura))
.map(UserRoleAssignment::getAssignedRole)
.collect(Collectors.toSet()))
.orElse(Collections.emptySet());
return roles;
}
private static boolean matches(final String entityTypeId, final long entityObjectId, final UserRoleAssignment ura) {
return ura.getEntityTypeId().equals(entityTypeId) && ura.getEntityObjectId().equals(entityObjectId);
}
} }

View File

@ -2,9 +2,13 @@
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.base.Verify.verify;
import static com.google.common.collect.Sets.union;
import static java.util.Collections.EMPTY_SET;
import static org.thymeleaf.util.SetUtils.singletonSet;
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.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;
@ -14,16 +18,22 @@ import org.springframework.context.ApplicationContext;
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.stream.Collectors;
abstract class JSonAccessFilter<T> { abstract class JSonAccessFilter<T> {
private final ApplicationContext ctx; private final ApplicationContext ctx;
private final UserRoleAssignmentService userRoleAssignmentService;
final T dto; final T dto;
final Field selfIdField; final Field selfIdField;
final Field parentIdField; final Field parentIdField;
JSonAccessFilter(final ApplicationContext ctx, final T dto) { JSonAccessFilter(final ApplicationContext ctx, final UserRoleAssignmentService userRoleAssignmentService, final T dto) {
this.ctx = ctx; this.ctx = ctx;
this.userRoleAssignmentService = userRoleAssignmentService;
this.dto = dto; this.dto = dto;
this.selfIdField = determineFieldWithAnnotation(dto.getClass(), SelfId.class); this.selfIdField = determineFieldWithAnnotation(dto.getClass(), SelfId.class);
this.parentIdField = determineFieldWithAnnotation(dto.getClass(), ParentId.class); this.parentIdField = determineFieldWithAnnotation(dto.getClass(), ParentId.class);
@ -45,25 +55,23 @@ abstract class JSonAccessFilter<T> {
} }
/** /**
* @return the role of the login user in relation to the dto, this filter is created for. * @return all roles of the login user in relation to the dto, for which this filter is created.
*/ */
Role getLoginUserRole() { Set<Role> getLoginUserRoles() {
final Role roleOnSelf = getLoginUserRoleOnSelf(); final Set<Role> independentRoles = Arrays.stream(Role.values())
if (roleOnSelf.isIndependent()) { // TODO mhoennig: ugly and risky filter condition => refactor!
return roleOnSelf; .filter(role -> role.isIndependent() && SecurityUtils.isCurrentUserInRole(role.asAuthority()))
} .collect(Collectors.toSet());
return getLoginUserRoleOnAncestorOfDtoClassIfHigher(roleOnSelf, dto);
final Set<Role> rolesOnThis = getId() != null ? getLoginUserDirectRolesFor(dto.getClass(), getId()) : EMPTY_SET;
return union(independentRoles, union(rolesOnThis, getLoginUserRoleOnAncestorIfHigher(dto)));
} }
private Role getLoginUserRoleOnSelf() { private Set<Role> getLoginUserRoleOnAncestorIfHigher(final Object dto) {
return SecurityUtils.getLoginUserRoleFor(dto.getClass(), getId());
}
private Role getLoginUserRoleOnAncestorOfDtoClassIfHigher(final Role baseRole, final Object dto) {
final Field parentIdField = determineFieldWithAnnotation(dto.getClass(), ParentId.class); final Field parentIdField = determineFieldWithAnnotation(dto.getClass(), ParentId.class);
if (parentIdField == null) { if (parentIdField == null) {
return baseRole; return singletonSet(Role.ANYBODY);
} }
final ParentId parentIdAnnot = parentIdField.getAnnotation(ParentId.class); final ParentId parentIdAnnot = parentIdField.getAnnotation(ParentId.class);
@ -72,10 +80,23 @@ abstract class JSonAccessFilter<T> {
final Class<?> parentDtoClass = ReflectionUtil.<T> determineGenericInterfaceParameter(parentDtoLoader, rawType, 0); final Class<?> parentDtoClass = ReflectionUtil.<T> determineGenericInterfaceParameter(parentDtoLoader, rawType, 0);
final Long parentId = ReflectionUtil.getValue(dto, parentIdField); final Long parentId = ReflectionUtil.getValue(dto, parentIdField);
final Role roleOnParent = SecurityUtils.getLoginUserRoleFor(parentDtoClass, parentId); final Set<Role> rolesOnParent = getLoginUserDirectRolesFor(parentDtoClass, parentId);
final Object parentEntity = loadDto(parentDtoLoader, parentId); final Object parentEntity = loadDto(parentDtoLoader, parentId);
return Role.broadest(baseRole, getLoginUserRoleOnAncestorOfDtoClassIfHigher(roleOnParent, parentEntity)); return union(rolesOnParent, getLoginUserRoleOnAncestorIfHigher(parentEntity));
}
private Set<Role> getLoginUserDirectRolesFor(final Class<?> dtoClass, final Long id) {
if (!SecurityUtils.isAuthenticated()) {
return singletonSet(Role.ANYBODY);
}
final EntityTypeId entityTypeId = dtoClass.getAnnotation(EntityTypeId.class);
if (entityTypeId == null) {
return singletonSet(Role.ANYBODY); // TODO mhoennig: all of such singletonSets -> emptySet
}
return userRoleAssignmentService.getEffectiveRoleOfCurrentUser(entityTypeId.value(), id);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View File

@ -3,6 +3,7 @@ package org.hostsharing.hsadminng.service.accessfilter;
import static org.hostsharing.hsadminng.service.util.ReflectionUtil.unchecked; 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.service.util.ReflectionUtil;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
@ -10,6 +11,7 @@ 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;
import com.fasterxml.jackson.databind.node.*; import com.fasterxml.jackson.databind.node.*;
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;
@ -35,10 +37,11 @@ public class JSonDeserializationWithAccessFilter<T> extends JSonAccessFilter<T>
public JSonDeserializationWithAccessFilter( public JSonDeserializationWithAccessFilter(
final ApplicationContext ctx, final ApplicationContext ctx,
final UserRoleAssignmentService userRoleAssignmentService,
final JsonParser jsonParser, final JsonParser jsonParser,
final DeserializationContext deserializationContext, final DeserializationContext deserializationContext,
Class<T> dtoClass) { Class<T> dtoClass) {
super(ctx, unchecked(dtoClass::newInstance)); super(ctx, userRoleAssignmentService, unchecked(dtoClass::newInstance));
this.treeNode = unchecked(() -> jsonParser.getCodec().readTree(jsonParser)); this.treeNode = unchecked(() -> jsonParser.getCodec().readTree(jsonParser));
} }
@ -151,26 +154,28 @@ public class JSonDeserializationWithAccessFilter<T> extends JSonAccessFilter<T>
field -> { field -> {
// TODO this ugly code needs cleanup // TODO this ugly code needs cleanup
if (!field.equals(selfIdField)) { if (!field.equals(selfIdField)) {
final Role role = getLoginUserRole(); final Set<Role> roles = getLoginUserRoles();
if (isInitAccess()) { if (isInitAccess()) {
if (!role.isAllowedToInit(field)) { if (!isAllowedToInit(roles, field)) {
if (!field.equals(parentIdField)) { if (!field.equals(parentIdField)) {
throw new BadRequestAlertException( throw new BadRequestAlertException(
"Initialization of field " + toDisplay(field) + " prohibited for current user role " "Initialization of field " + toDisplay(field)
+ role, + " prohibited for current user roles "
+ Joiner.on("+").join(roles),
toDisplay(field), toDisplay(field),
"initializationProhibited"); "initializationProhibited");
} else { } else {
throw new BadRequestAlertException( throw new BadRequestAlertException(
"Referencing field " + toDisplay(field) + " prohibited for current user role " "Referencing field " + toDisplay(field) + " prohibited for current user roles "
+ role, + Joiner.on("+").join(roles),
toDisplay(field), toDisplay(field),
"referencingProhibited"); "referencingProhibited");
} }
} }
} else if (!Role.toBeIgnoredForUpdates(field) && !getLoginUserRole().isAllowedToUpdate(field)) { } else if (!Role.toBeIgnoredForUpdates(field) && !isAllowedToUpdate(getLoginUserRoles(), field)) {
throw new BadRequestAlertException( throw new BadRequestAlertException(
"Update of field " + toDisplay(field) + " prohibited for current user role " + role, "Update of field " + toDisplay(field) + " prohibited for current user roles "
+ Joiner.on("+").join(roles),
toDisplay(field), toDisplay(field),
"updateProhibited"); "updateProhibited");
} }
@ -178,6 +183,24 @@ public class JSonDeserializationWithAccessFilter<T> extends JSonAccessFilter<T>
}); });
} }
private boolean isAllowedToInit(final Set<Role> roles, final Field field) {
for (Role role : roles) {
if (role.isAllowedToInit(field)) {
return true;
}
}
return false;
}
private boolean isAllowedToUpdate(final Set<Role> roles, final Field field) {
for (Role role : roles) {
if (role.isAllowedToUpdate(field)) {
return true;
}
}
return false;
}
private boolean isInitAccess() { private boolean isInitAccess() {
return getId() == null; return getId() == null;
} }

View File

@ -1,6 +1,7 @@
// 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 org.hostsharing.hsadminng.service.util.ReflectionUtil;
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator;
@ -13,6 +14,7 @@ import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.Set;
/** /**
* Actual implementation of JSON serialization, where {link JsonSerializerWithAccessFilter} * Actual implementation of JSON serialization, where {link JsonSerializerWithAccessFilter}
@ -28,10 +30,11 @@ public class JSonSerializationWithAccessFilter<T> extends JSonAccessFilter<T> {
public JSonSerializationWithAccessFilter( public JSonSerializationWithAccessFilter(
final ApplicationContext ctx, final ApplicationContext ctx,
final UserRoleAssignmentService userRoleAssignmentService,
final JsonGenerator jsonGenerator, final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider, final SerializerProvider serializerProvider,
final T dto) { final T dto) {
super(ctx, dto); super(ctx, userRoleAssignmentService, dto);
this.jsonGenerator = jsonGenerator; this.jsonGenerator = jsonGenerator;
this.serializerProvider = serializerProvider; this.serializerProvider = serializerProvider;
} }
@ -47,7 +50,7 @@ public class JSonSerializationWithAccessFilter<T> extends JSonAccessFilter<T> {
} }
private void toJSon(final Object dto, final JsonGenerator jsonGenerator, final Field field) throws IOException { private void toJSon(final Object dto, final JsonGenerator jsonGenerator, final Field field) throws IOException {
if (getLoginUserRole().isAllowedToRead(field)) { if (isAllowedToRead(getLoginUserRoles(), field)) {
final String fieldName = field.getName(); final String fieldName = field.getName();
// TODO: maybe replace by serializerProvider.defaultSerialize...()? // TODO: maybe replace by serializerProvider.defaultSerialize...()?
// But that makes it difficult for parallel structure with the deserializer (clumsy API). // But that makes it difficult for parallel structure with the deserializer (clumsy API).
@ -77,4 +80,13 @@ public class JSonSerializationWithAccessFilter<T> extends JSonAccessFilter<T> {
} }
} }
private boolean isAllowedToRead(final Set<Role> roles, final Field field) {
for (Role role : roles) {
if (role.isAllowedToRead(field)) {
return true;
}
}
return false;
}
} }

View File

@ -1,6 +1,7 @@
// 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 org.hostsharing.hsadminng.service.util.ReflectionUtil;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
@ -12,9 +13,13 @@ import org.springframework.context.ApplicationContext;
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;
private final UserRoleAssignmentService userRoleAssignmentService;
public JsonDeserializerWithAccessFilter(final ApplicationContext ctx) { public JsonDeserializerWithAccessFilter(
final ApplicationContext ctx,
final UserRoleAssignmentService userRoleAssignmentService) {
this.ctx = ctx; this.ctx = ctx;
this.userRoleAssignmentService = userRoleAssignmentService;
} }
@Override @Override
@ -24,6 +29,11 @@ public abstract class JsonDeserializerWithAccessFilter<T extends AccessMappings>
final Class<T> dtoClass = ReflectionUtil final Class<T> dtoClass = ReflectionUtil
.determineGenericClassParameter(this.getClass(), JsonDeserializerWithAccessFilter.class, 0); .determineGenericClassParameter(this.getClass(), JsonDeserializerWithAccessFilter.class, 0);
return new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, deserializationContext, dtoClass).deserialize(); return new JSonDeserializationWithAccessFilter<T>(
ctx,
userRoleAssignmentService,
jsonParser,
deserializationContext,
dtoClass).deserialize();
} }
} }

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.UserRoleAssignmentService;
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;
@ -20,9 +22,13 @@ import java.io.IOException;
public abstract class JsonSerializerWithAccessFilter<T extends AccessMappings> extends JsonSerializer<T> { public abstract class JsonSerializerWithAccessFilter<T extends AccessMappings> extends JsonSerializer<T> {
protected final ApplicationContext ctx; protected final ApplicationContext ctx;
protected final UserRoleAssignmentService userRoleAssignmentService;
public JsonSerializerWithAccessFilter(final ApplicationContext ctx) { public JsonSerializerWithAccessFilter(
final ApplicationContext ctx,
final UserRoleAssignmentService userRoleAssignmentService) {
this.ctx = ctx; this.ctx = ctx;
this.userRoleAssignmentService = userRoleAssignmentService;
} }
@Override @Override
@ -31,6 +37,7 @@ public abstract class JsonSerializerWithAccessFilter<T extends AccessMappings> e
final JsonGenerator jsonGenerator, final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider) throws IOException { final SerializerProvider serializerProvider) throws IOException {
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, serializerProvider, dto).serialize(); new JSonSerializationWithAccessFilter<T>(ctx, userRoleAssignmentService, jsonGenerator, serializerProvider, dto)
.serialize();
} }
} }

View File

@ -3,6 +3,8 @@ package org.hostsharing.hsadminng.service.accessfilter;
import static com.google.common.base.Verify.verify; import static com.google.common.base.Verify.verify;
import org.hostsharing.hsadminng.security.AuthoritiesConstants;
import java.lang.reflect.Field; import java.lang.reflect.Field;
/** /**
@ -24,17 +26,17 @@ public enum Role {
/** /**
* 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.
*/ */
HOSTMASTER(1), HOSTMASTER(1, AuthoritiesConstants.HOSTMASTER),
/** /**
* This role is for administrators, e.g. to create memberships and book shared and assets. * This role is for administrators, e.g. to create memberships and book shared and assets.
*/ */
ADMIN(2), ADMIN(2, AuthoritiesConstants.ADMIN),
/** /**
* This role is for members of the support team. * This role is for members of the support team.
*/ */
SUPPORTER(3), SUPPORTER(3, AuthoritiesConstants.SUPPORTER),
/** /**
* 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.
@ -82,7 +84,7 @@ public enum Role {
* 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.
* It's currently only used for technical purposes. * It's currently only used for technical purposes.
*/ */
ANYBODY(99), ANYBODY(99, 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.
@ -92,13 +94,21 @@ public enum Role {
IGNORED; IGNORED;
private final Integer level; private final Integer level;
private final String authority;
Role() { Role(final int level, final String authority) {
this.level = null; this.level = level;
this.authority = authority;
} }
Role(final int level) { Role(final int level) {
this.level = level; this.level = level;
this.authority = AuthoritiesConstants.USER;
}
Role() {
this.level = null;
this.authority = null;
} }
/** /**
@ -114,6 +124,10 @@ public enum Role {
return updateAccessFor.length == 1 && updateAccessFor[0].isIgnored(); return updateAccessFor.length == 1 && updateAccessFor[0].isIgnored();
} }
public String asAuthority() {
return authority;
}
/** /**
* @return true if the role is the IGNORED role * @return true if the role is the IGNORED role
*/ */
@ -125,7 +139,7 @@ public enum Role {
* @return true if this role is independent of a target object, false otherwise. * @return true if this role is independent of a target object, false otherwise.
*/ */
public boolean isIndependent() { public boolean isIndependent() {
return covers(Role.SUPPORTER); return this != NOBODY && covers(Role.SUPPORTER);
} }
/** /**

View File

@ -5,6 +5,7 @@ import org.hostsharing.hsadminng.domain.Asset;
import org.hostsharing.hsadminng.domain.enumeration.AssetAction; import org.hostsharing.hsadminng.domain.enumeration.AssetAction;
import org.hostsharing.hsadminng.service.AssetService; 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.accessfilter.*; import org.hostsharing.hsadminng.service.accessfilter.*;
import org.springframework.boot.jackson.JsonComponent; import org.springframework.boot.jackson.JsonComponent;
@ -157,16 +158,16 @@ public class AssetDTO implements Serializable, AccessMappings {
@JsonComponent @JsonComponent
public static class JsonSerializer extends JsonSerializerWithAccessFilter<AssetDTO> { public static class JsonSerializer extends JsonSerializerWithAccessFilter<AssetDTO> {
public JsonSerializer(final ApplicationContext ctx) { public JsonSerializer(final ApplicationContext ctx, final UserRoleAssignmentService userRoleAssignmentService) {
super(ctx); super(ctx, userRoleAssignmentService);
} }
} }
@JsonComponent @JsonComponent
public static class JsonDeserializer extends JsonDeserializerWithAccessFilter<AssetDTO> { public static class JsonDeserializer extends JsonDeserializerWithAccessFilter<AssetDTO> {
public JsonDeserializer(final ApplicationContext ctx) { public JsonDeserializer(final ApplicationContext ctx, final UserRoleAssignmentService userRoleAssignmentService) {
super(ctx); super(ctx, userRoleAssignmentService);
} }
} }
} }

View File

@ -5,6 +5,7 @@ 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;
import org.hostsharing.hsadminng.service.CustomerService; import org.hostsharing.hsadminng.service.CustomerService;
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;
@ -22,24 +23,24 @@ 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 = Role.ACTUAL_CUSTOMER_USER)
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 = Role.ADMIN, read = Role.ACTUAL_CUSTOMER_USER)
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 = Role.ADMIN, read = Role.ACTUAL_CUSTOMER_USER)
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 = Role.ADMIN, update = Role.ADMIN, read = Role.ACTUAL_CUSTOMER_USER)
private String name; private String name;
@NotNull @NotNull
@ -93,7 +94,7 @@ public class CustomerDTO implements AccessMappings, FluentBuilder<CustomerDTO> {
@AccessFor(init = Role.ADMIN, update = Role.SUPPORTER, read = Role.SUPPORTER) @AccessFor(init = Role.ADMIN, update = Role.SUPPORTER, read = Role.SUPPORTER)
private String remark; private String remark;
@AccessFor(init = Role.ANYBODY, update = Role.ANYBODY, read = Role.ANY_CUSTOMER_USER) @AccessFor(init = Role.ANYBODY, update = Role.ANYBODY, read = Role.ACTUAL_CUSTOMER_USER)
private String displayLabel; private String displayLabel;
public Long getId() { public Long getId() {
@ -278,16 +279,18 @@ public class CustomerDTO implements AccessMappings, FluentBuilder<CustomerDTO> {
@JsonComponent @JsonComponent
public static class CustomerJsonSerializer extends JsonSerializerWithAccessFilter<CustomerDTO> { public static class CustomerJsonSerializer extends JsonSerializerWithAccessFilter<CustomerDTO> {
public CustomerJsonSerializer(final ApplicationContext ctx) { public CustomerJsonSerializer(final ApplicationContext ctx, final UserRoleAssignmentService userRoleAssignmentService) {
super(ctx); super(ctx, userRoleAssignmentService);
} }
} }
@JsonComponent @JsonComponent
public static class CustomerJsonDeserializer extends JsonDeserializerWithAccessFilter<CustomerDTO> { public static class CustomerJsonDeserializer extends JsonDeserializerWithAccessFilter<CustomerDTO> {
public CustomerJsonDeserializer(final ApplicationContext ctx) { public CustomerJsonDeserializer(
super(ctx); final ApplicationContext ctx,
final UserRoleAssignmentService userRoleAssignmentService) {
super(ctx, userRoleAssignmentService);
} }
} }
} }

View File

@ -4,6 +4,7 @@ package org.hostsharing.hsadminng.service.dto;
import org.hostsharing.hsadminng.domain.Membership; import org.hostsharing.hsadminng.domain.Membership;
import org.hostsharing.hsadminng.service.CustomerService; 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.accessfilter.*; import org.hostsharing.hsadminng.service.accessfilter.*;
import org.springframework.boot.jackson.JsonComponent; import org.springframework.boot.jackson.JsonComponent;
@ -174,16 +175,20 @@ public class MembershipDTO implements AccessMappings, FluentBuilder<MembershipDT
@JsonComponent @JsonComponent
public static class MembershipJsonSerializer extends JsonSerializerWithAccessFilter<MembershipDTO> { public static class MembershipJsonSerializer extends JsonSerializerWithAccessFilter<MembershipDTO> {
public MembershipJsonSerializer(final ApplicationContext ctx) { public MembershipJsonSerializer(
super(ctx); final ApplicationContext ctx,
final UserRoleAssignmentService userRoleAssignmentService) {
super(ctx, userRoleAssignmentService);
} }
} }
@JsonComponent @JsonComponent
public static class MembershipJsonDeserializer extends JsonDeserializerWithAccessFilter<MembershipDTO> { public static class MembershipJsonDeserializer extends JsonDeserializerWithAccessFilter<MembershipDTO> {
public MembershipJsonDeserializer(final ApplicationContext ctx) { public MembershipJsonDeserializer(
super(ctx); final ApplicationContext ctx,
final UserRoleAssignmentService userRoleAssignmentService) {
super(ctx, userRoleAssignmentService);
} }
} }
} }

View File

@ -4,6 +4,7 @@ package org.hostsharing.hsadminng.service.dto;
import org.hostsharing.hsadminng.domain.SepaMandate; import org.hostsharing.hsadminng.domain.SepaMandate;
import org.hostsharing.hsadminng.service.CustomerService; 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.accessfilter.*; import org.hostsharing.hsadminng.service.accessfilter.*;
import org.springframework.boot.jackson.JsonComponent; import org.springframework.boot.jackson.JsonComponent;
@ -222,16 +223,16 @@ public class SepaMandateDTO implements AccessMappings, FluentBuilder<SepaMandate
@JsonComponent @JsonComponent
public static class JsonSerializer extends JsonSerializerWithAccessFilter<SepaMandateDTO> { public static class JsonSerializer extends JsonSerializerWithAccessFilter<SepaMandateDTO> {
public JsonSerializer(final ApplicationContext ctx) { public JsonSerializer(final ApplicationContext ctx, final UserRoleAssignmentService userRoleAssignmentService) {
super(ctx); super(ctx, userRoleAssignmentService);
} }
} }
@JsonComponent @JsonComponent
public static class JsonDeserializer extends JsonDeserializerWithAccessFilter<SepaMandateDTO> { public static class JsonDeserializer extends JsonDeserializerWithAccessFilter<SepaMandateDTO> {
public JsonDeserializer(final ApplicationContext ctx) { public JsonDeserializer(final ApplicationContext ctx, final UserRoleAssignmentService userRoleAssignmentService) {
super(ctx); super(ctx, userRoleAssignmentService);
} }
} }
} }

View File

@ -5,6 +5,7 @@ import org.hostsharing.hsadminng.domain.Share;
import org.hostsharing.hsadminng.domain.enumeration.ShareAction; import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
import org.hostsharing.hsadminng.service.MembershipService; 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.accessfilter.*; import org.hostsharing.hsadminng.service.accessfilter.*;
import org.springframework.boot.jackson.JsonComponent; import org.springframework.boot.jackson.JsonComponent;
@ -156,16 +157,16 @@ public class ShareDTO implements Serializable, AccessMappings {
@JsonComponent @JsonComponent
public static class JsonSerializer extends JsonSerializerWithAccessFilter<ShareDTO> { public static class JsonSerializer extends JsonSerializerWithAccessFilter<ShareDTO> {
public JsonSerializer(final ApplicationContext ctx) { public JsonSerializer(final ApplicationContext ctx, final UserRoleAssignmentService userRoleAssignmentService) {
super(ctx); super(ctx, userRoleAssignmentService);
} }
} }
@JsonComponent @JsonComponent
public static class JsonDeserializer extends JsonDeserializerWithAccessFilter<ShareDTO> { public static class JsonDeserializer extends JsonDeserializerWithAccessFilter<ShareDTO> {
public JsonDeserializer(final ApplicationContext ctx) { public JsonDeserializer(final ApplicationContext ctx, final UserRoleAssignmentService userRoleAssignmentService) {
super(ctx); super(ctx, userRoleAssignmentService);
} }
} }
} }

View File

@ -1,7 +1,7 @@
// 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.UserRole; 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;
@ -23,7 +23,7 @@ public class UserRoleAssignmentCriteria implements Serializable {
/** /**
* Class for filtering UserRole * Class for filtering UserRole
*/ */
public static class UserRoleFilter extends Filter<UserRole> { public static class UserRoleFilter extends Filter<Role> {
} }
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;

View File

@ -0,0 +1,95 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.domain.UserRoleAssignment;
import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository;
import org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext;
import org.hostsharing.hsadminng.service.accessfilter.Role;
import com.google.common.base.VerifyException;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.util.Arrays;
import java.util.Set;
public class UserRoleAssignmentServiceUnitTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private UserRoleAssignmentRepository userRoleAssignmentRepository;
@InjectMocks
private UserRoleAssignmentService userRoleAssignmentService;
@Test
public void getEffectiveRoleOfCurrentUserReturnsEmptySetIfUserNotAuthenticated() {
// when
final Set<Role> actual = userRoleAssignmentService.getEffectiveRoleOfCurrentUser("test.Something", 1L);
// then
assertThat(actual).isEmpty();
}
@Test
public void getEffectiveRoleOfCurrentUserReturnsEmptySetIfUserAuthenticatedButNoRolesAssigned() {
// given
new MockSecurityContext().havingAuthenticatedUser();
// when
final Set<Role> actual = userRoleAssignmentService.getEffectiveRoleOfCurrentUser("test.Something", 1L);
// then
assertThat(actual).isEmpty();
}
@Test
public void getEffectiveRoleOfCurrentUserReturnsExactlyAssignedRoles() {
// given
final String givenUserLogin = "someUser";
new MockSecurityContext().havingAuthenticatedUser(givenUserLogin);
final long givenEntityObjectId = 2L;
final String givenEntityTypeId = "test.Something";
given(userRoleAssignmentRepository.findByLogin(givenUserLogin)).willReturn(
Arrays.asList(
new UserRoleAssignment().entityTypeId("test.SomethingElse")
.entityObjectId(givenEntityObjectId)
.assignedRole(Role.CONTRACTUAL_CONTACT),
new UserRoleAssignment().entityTypeId(givenEntityTypeId)
.entityObjectId(givenEntityObjectId)
.assignedRole(Role.FINANCIAL_CONTACT),
new UserRoleAssignment().entityTypeId(givenEntityTypeId)
.entityObjectId(givenEntityObjectId)
.assignedRole(Role.TECHNICAL_CONTACT),
new UserRoleAssignment().entityTypeId(givenEntityTypeId)
.entityObjectId(3L)
.assignedRole(Role.CONTRACTUAL_CONTACT)));
// when
final Set<Role> actual = userRoleAssignmentService
.getEffectiveRoleOfCurrentUser(givenEntityTypeId, givenEntityObjectId);
// then
assertThat(actual).containsExactlyInAnyOrder(Role.FINANCIAL_CONTACT, Role.TECHNICAL_CONTACT);
}
@Test
public void getEffectiveRoleOfCurrentUserThrowsExceptionIfEntityTypeIdIsMissing() {
// when
final Throwable actual = catchThrowable(() -> userRoleAssignmentService.getEffectiveRoleOfCurrentUser(null, 1L));
// then
assertThat(actual).isInstanceOf(VerifyException.class);
}
}

View File

@ -33,6 +33,7 @@ public class JSonAccessFilterTestFixture {
return dto; return dto;
} }
@EntityTypeId("test.GivenCustomer")
static class GivenCustomerDto implements FluentBuilder<GivenCustomerDto> { static class GivenCustomerDto implements FluentBuilder<GivenCustomerDto> {
@SelfId(resolver = GivenService.class) @SelfId(resolver = GivenService.class)
@ -47,6 +48,7 @@ public class JSonAccessFilterTestFixture {
static abstract class GivenCustomerService implements IdToDtoResolver<GivenCustomerDto> { static abstract class GivenCustomerService implements IdToDtoResolver<GivenCustomerDto> {
} }
@EntityTypeId("test.Given")
static class GivenDto implements FluentBuilder<GivenDto> { static class GivenDto implements FluentBuilder<GivenDto> {
@SelfId(resolver = GivenService.class) @SelfId(resolver = GivenService.class)

View File

@ -6,10 +6,9 @@ import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.Assumptions.assumeThat; import static org.assertj.core.api.Assumptions.assumeThat;
import static org.hostsharing.hsadminng.service.accessfilter.JSonAccessFilterTestFixture.*; import static org.hostsharing.hsadminng.service.accessfilter.JSonAccessFilterTestFixture.*;
import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon; import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser;
@ -61,6 +60,9 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Mock @Mock
private TreeNode treeNode; private TreeNode treeNode;
@Mock
private UserRoleAssignmentService userRoleAssignmentService;
@Mock @Mock
private GivenService givenService; private GivenService givenService;
@ -70,10 +72,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Mock @Mock
private GivenCustomerService givenCustomerService; private GivenCustomerService givenCustomerService;
private MockSecurityContext givenSecurityContext;
@Before @Before
public void init() { public void init() {
givenAuthenticatedUser(); givenSecurityContext = new MockSecurityContext(userRoleAssignmentService);
givenUserHavingRole(GivenDto.class, 1234L, Role.ACTUAL_CUSTOMER_USER); givenSecurityContext.havingAuthenticatedUser().withRole(GivenDto.class, 1234L, Role.ACTUAL_CUSTOMER_USER);
given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory); given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory);
given(autowireCapableBeanFactory.createBean(GivenService.class)).willReturn(givenService); given(autowireCapableBeanFactory.createBean(GivenService.class)).willReturn(givenService);
@ -113,7 +117,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
ImmutablePair.of("openStringField", null))); ImmutablePair.of("openStringField", null)));
// when // when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDto.class).deserialize();
// then // then
assertThat(actualDto.openStringField).isNull(); assertThat(actualDto.openStringField).isNull();
@ -129,7 +138,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
ImmutablePair.of("openStringField", "String Value"))); ImmutablePair.of("openStringField", "String Value")));
// when // when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDto.class).deserialize();
// then // then
assertThat(actualDto.openStringField).isEqualTo("String Value"); assertThat(actualDto.openStringField).isEqualTo("String Value");
@ -145,7 +159,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
ImmutablePair.of("openIntegerField", 1234))); ImmutablePair.of("openIntegerField", 1234)));
// when // when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDto.class).deserialize();
// then // then
assertThat(actualDto.openIntegerField).isEqualTo(1234); assertThat(actualDto.openIntegerField).isEqualTo(1234);
@ -162,7 +181,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
ImmutablePair.of("restrictedBigDecimalField", SOME_BIG_DECIMAL_WITH_ANOTHER_SCALE))); ImmutablePair.of("restrictedBigDecimalField", SOME_BIG_DECIMAL_WITH_ANOTHER_SCALE)));
// when // when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDto.class).deserialize();
// then // then
assertThat(actualDto.restrictedBigDecimalField).isEqualByComparingTo(SOME_BIG_DECIMAL); assertThat(actualDto.restrictedBigDecimalField).isEqualByComparingTo(SOME_BIG_DECIMAL);
@ -192,7 +216,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
ImmutablePair.of("openEnumField", TestEnum.GREEN))); ImmutablePair.of("openEnumField", TestEnum.GREEN)));
// when // when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDto.class).deserialize();
// then // then
assertThat(actualDto.openIntegerField).isEqualTo(11); assertThat(actualDto.openIntegerField).isEqualTo(11);
@ -218,7 +247,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
// when // when
Throwable exception = catchThrowable( Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize()); () -> new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDto.class).deserialize());
// then // then
assertThat(exception).isInstanceOf(NotImplementedException.class); assertThat(exception).isInstanceOf(NotImplementedException.class);
@ -227,8 +261,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Test @Test
public void shouldDeserializeStringFieldIfRequiredRoleIsCoveredByUser() throws IOException { public void shouldDeserializeStringFieldIfRequiredRoleIsCoveredByUser() throws IOException {
// given // given
givenAuthenticatedUser(); givenSecurityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 888L, Role.FINANCIAL_CONTACT);
givenUserHavingRole(GivenCustomerDto.class, 888L, Role.FINANCIAL_CONTACT);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("id", 1234L), ImmutablePair.of("id", 1234L),
@ -236,7 +269,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
ImmutablePair.of("restrictedField", "update value of restricted field"))); ImmutablePair.of("restrictedField", "update value of restricted field")));
// when // when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDto.class).deserialize();
// then // then
assertThat(actualDto.restrictedField).isEqualTo("update value of restricted field"); assertThat(actualDto.restrictedField).isEqualTo("update value of restricted field");
@ -245,8 +283,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Test @Test
public void shouldDeserializeUnchangedStringFieldIfRequiredRoleIsNotCoveredByUser() throws IOException { public void shouldDeserializeUnchangedStringFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given // given
givenAuthenticatedUser(); givenSecurityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER);
givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("id", 1234L), ImmutablePair.of("id", 1234L),
@ -254,7 +291,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
ImmutablePair.of("restrictedField", "initial value of restricted field"))); ImmutablePair.of("restrictedField", "initial value of restricted field")));
// when // when
GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDto.class).deserialize();
// then // then
assertThat(actualDto.restrictedField).isEqualTo("initial value of restricted field"); assertThat(actualDto.restrictedField).isEqualTo("initial value of restricted field");
@ -263,8 +305,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Test @Test
public void shouldNotDeserializeUpatedStringFieldIfRequiredRoleIsNotCoveredByUser() throws IOException { public void shouldNotDeserializeUpatedStringFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given // given
givenAuthenticatedUser(); givenSecurityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER);
givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("customerId", 888L), ImmutablePair.of("customerId", 888L),
@ -272,7 +313,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
// when // when
Throwable exception = catchThrowable( Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize()); () -> new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDto.class).deserialize());
// then // then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> { assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {
@ -284,8 +330,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Test @Test
public void shouldInitializeFieldIfRequiredRoleIsNotCoveredByUser() throws IOException { public void shouldInitializeFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given // given
givenAuthenticatedUser(); givenSecurityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER);
givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("customerId", 888L), ImmutablePair.of("customerId", 888L),
@ -293,7 +338,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
// when // when
Throwable exception = catchThrowable( Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize()); () -> new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDto.class).deserialize());
// then // then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> { assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {
@ -305,15 +355,19 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Test @Test
public void shouldNotCreateIfRoleRequiredByParentEntityIsNotCoveredByUser() throws IOException { public void shouldNotCreateIfRoleRequiredByParentEntityIsNotCoveredByUser() throws IOException {
// given // given
givenAuthenticatedUser(); givenSecurityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 9999L, Role.CONTRACTUAL_CONTACT);
givenUserHavingRole(GivenDto.class, 9999L, Role.CONTRACTUAL_CONTACT);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("parentId", 1234L))); ImmutablePair.of("parentId", 1234L)));
// when // when
Throwable exception = catchThrowable( Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenChildDto.class).deserialize()); () -> new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenChildDto.class).deserialize());
// then // then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> { assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {
@ -325,14 +379,18 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Test @Test
public void shouldCreateIfRoleRequiredByReferencedEntityIsCoveredByUser() throws IOException { public void shouldCreateIfRoleRequiredByReferencedEntityIsCoveredByUser() throws IOException {
// given // given
givenAuthenticatedUser(); givenSecurityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 888L, Role.CONTRACTUAL_CONTACT);
givenUserHavingRole(GivenDto.class, 1234L, Role.CONTRACTUAL_CONTACT);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("parentId", 1234L))); ImmutablePair.of("parentId", 1234L)));
// when // when
final GivenChildDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenChildDto.class) final GivenChildDto actualDto = new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenChildDto.class)
.deserialize(); .deserialize();
// then // then
@ -342,8 +400,7 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Test @Test
public void shouldNotUpdateFieldIfRequiredRoleIsNotCoveredByUser() throws IOException { public void shouldNotUpdateFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given // given
givenAuthenticatedUser(); givenSecurityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER);
givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER);
givenJSonTree( givenJSonTree(
asJSon( asJSon(
ImmutablePair.of("id", 1234L), ImmutablePair.of("id", 1234L),
@ -352,7 +409,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
// when // when
Throwable exception = catchThrowable( Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize()); () -> new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDto.class).deserialize());
// then // then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> { assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {
@ -368,7 +430,12 @@ public class JSonDeserializationWithAccessFilterUnitTest {
// when // when
Throwable exception = catchThrowable( Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDtoWithMultipleSelfId.class) () -> new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDtoWithMultipleSelfId.class)
.deserialize()); .deserialize());
// then // then
@ -379,13 +446,17 @@ public class JSonDeserializationWithAccessFilterUnitTest {
@Test @Test
public void shouldDetectUnknownFieldType() throws IOException { public void shouldDetectUnknownFieldType() throws IOException {
// given // given
givenAuthenticatedUser(); givenSecurityContext.havingAuthenticatedUser().withRole(Role.ADMIN);
givenUserHavingRole(Role.ADMIN);
givenJSonTree(asJSon(ImmutablePair.of("unknown", new Arbitrary()))); givenJSonTree(asJSon(ImmutablePair.of("unknown", new Arbitrary())));
// when // when
Throwable exception = catchThrowable( Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDtoWithUnknownFieldType.class) () -> new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
GivenDtoWithUnknownFieldType.class)
.deserialize()); .deserialize());
// then // then

View File

@ -8,6 +8,8 @@ import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; 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;
@ -37,15 +39,20 @@ public class JSonSerializationWithAccessFilterUnitTest {
@Mock @Mock
private JsonGenerator jsonGenerator; private JsonGenerator jsonGenerator;
@Mock
private UserRoleAssignmentService userRoleAssignmentService;
@Mock @Mock
private GivenCustomerService givenCustomerService; private GivenCustomerService givenCustomerService;
private MockSecurityContext securityContext;
private final GivenDto givenDTO = createSampleDto(); private final GivenDto givenDTO = createSampleDto();
@Before @Before
public void init() { public void init() {
MockSecurityContext.givenAuthenticatedUser(); securityContext = new MockSecurityContext(userRoleAssignmentService).havingAuthenticatedUser()
MockSecurityContext.givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ANY_CUSTOMER_USER); .withRole(GivenCustomerDto.class, 888L, Role.ANY_CUSTOMER_USER);
given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory); given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory);
given(autowireCapableBeanFactory.createBean(GivenCustomerService.class)).willReturn(givenCustomerService); given(autowireCapableBeanFactory.createBean(GivenCustomerService.class)).willReturn(givenCustomerService);
@ -58,7 +65,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
@Test @Test
public void shouldSerializeStringField() throws IOException { public void shouldSerializeStringField() throws IOException {
// when // when
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDTO).serialize(); new JSonSerializationWithAccessFilter<>(ctx, userRoleAssignmentService, jsonGenerator, null, givenDTO).serialize();
// then // then
verify(jsonGenerator).writeStringField("openStringField", givenDTO.openStringField); verify(jsonGenerator).writeStringField("openStringField", givenDTO.openStringField);
@ -67,7 +74,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
@Test @Test
public void shouldSerializeIntegerField() throws IOException { public void shouldSerializeIntegerField() throws IOException {
// when // when
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDTO).serialize(); new JSonSerializationWithAccessFilter<>(ctx, userRoleAssignmentService, jsonGenerator, null, givenDTO).serialize();
// then // then
verify(jsonGenerator).writeNumberField("openIntegerField", givenDTO.openIntegerField); verify(jsonGenerator).writeNumberField("openIntegerField", givenDTO.openIntegerField);
@ -76,7 +83,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
@Test @Test
public void shouldSerializePrimitiveIntField() throws IOException { public void shouldSerializePrimitiveIntField() throws IOException {
// when // when
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDTO).serialize(); new JSonSerializationWithAccessFilter<>(ctx, userRoleAssignmentService, jsonGenerator, null, givenDTO).serialize();
// then // then
verify(jsonGenerator).writeNumberField("openPrimitiveIntField", givenDTO.openPrimitiveIntField); verify(jsonGenerator).writeNumberField("openPrimitiveIntField", givenDTO.openPrimitiveIntField);
@ -85,7 +92,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
@Test @Test
public void shouldSerializeLongField() throws IOException { public void shouldSerializeLongField() throws IOException {
// when // when
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDTO).serialize(); new JSonSerializationWithAccessFilter<>(ctx, userRoleAssignmentService, jsonGenerator, null, givenDTO).serialize();
// then // then
verify(jsonGenerator).writeNumberField("openLongField", givenDTO.openLongField); verify(jsonGenerator).writeNumberField("openLongField", givenDTO.openLongField);
@ -94,7 +101,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
@Test @Test
public void shouldSerializePrimitiveLongField() throws IOException { public void shouldSerializePrimitiveLongField() throws IOException {
// when // when
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDTO).serialize(); new JSonSerializationWithAccessFilter<>(ctx, userRoleAssignmentService, jsonGenerator, null, givenDTO).serialize();
// then // then
verify(jsonGenerator).writeNumberField("openPrimitiveLongField", givenDTO.openPrimitiveLongField); verify(jsonGenerator).writeNumberField("openPrimitiveLongField", givenDTO.openPrimitiveLongField);
@ -103,7 +110,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
@Test @Test
public void shouldSerializeBooleanField() throws IOException { public void shouldSerializeBooleanField() throws IOException {
// when // when
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDTO).serialize(); new JSonSerializationWithAccessFilter<>(ctx, userRoleAssignmentService, jsonGenerator, null, givenDTO).serialize();
// then // then
verify(jsonGenerator).writeBooleanField("openBooleanField", givenDTO.openBooleanField); verify(jsonGenerator).writeBooleanField("openBooleanField", givenDTO.openBooleanField);
@ -112,7 +119,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
@Test @Test
public void shouldSerializePrimitiveBooleanField() throws IOException { public void shouldSerializePrimitiveBooleanField() throws IOException {
// when // when
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDTO).serialize(); new JSonSerializationWithAccessFilter<>(ctx, userRoleAssignmentService, jsonGenerator, null, givenDTO).serialize();
// then // then
verify(jsonGenerator).writeBooleanField("openPrimitiveBooleanField", givenDTO.openPrimitiveBooleanField); verify(jsonGenerator).writeBooleanField("openPrimitiveBooleanField", givenDTO.openPrimitiveBooleanField);
@ -121,7 +128,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
@Test @Test
public void shouldSerializeBigDecimalField() throws IOException { public void shouldSerializeBigDecimalField() throws IOException {
// when // when
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDTO).serialize(); new JSonSerializationWithAccessFilter<>(ctx, userRoleAssignmentService, jsonGenerator, null, givenDTO).serialize();
// then // then
verify(jsonGenerator).writeNumberField("openBigDecimalField", givenDTO.openBigDecimalField); verify(jsonGenerator).writeNumberField("openBigDecimalField", givenDTO.openBigDecimalField);
@ -130,7 +137,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
@Test @Test
public void shouldSerializeLocalDateField() throws IOException { public void shouldSerializeLocalDateField() throws IOException {
// when // when
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDTO).serialize(); new JSonSerializationWithAccessFilter<>(ctx, userRoleAssignmentService, jsonGenerator, null, givenDTO).serialize();
// then // then
verify(jsonGenerator).writeStringField("openLocalDateField", givenDTO.openLocalDateFieldAsString); verify(jsonGenerator).writeStringField("openLocalDateField", givenDTO.openLocalDateFieldAsString);
@ -139,7 +146,7 @@ public class JSonSerializationWithAccessFilterUnitTest {
@Test @Test
public void shouldSerializeEnumField() throws IOException { public void shouldSerializeEnumField() throws IOException {
// when // when
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDTO).serialize(); new JSonSerializationWithAccessFilter<>(ctx, userRoleAssignmentService, jsonGenerator, null, givenDTO).serialize();
// then // then
verify(jsonGenerator).writeStringField("openEnumField", givenDTO.openEnumFieldAsString); verify(jsonGenerator).writeStringField("openEnumField", givenDTO.openEnumFieldAsString);
@ -149,11 +156,10 @@ public class JSonSerializationWithAccessFilterUnitTest {
public void shouldSerializeRestrictedFieldIfRequiredRoleIsCoveredByUser() throws IOException { public void shouldSerializeRestrictedFieldIfRequiredRoleIsCoveredByUser() throws IOException {
// given // given
MockSecurityContext.givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 888L, Role.FINANCIAL_CONTACT);
MockSecurityContext.givenUserHavingRole(GivenCustomerDto.class, 888L, Role.FINANCIAL_CONTACT);
// when // when
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDTO).serialize(); new JSonSerializationWithAccessFilter<>(ctx, userRoleAssignmentService, jsonGenerator, null, givenDTO).serialize();
// then // then
verify(jsonGenerator).writeStringField("restrictedField", givenDTO.restrictedField); verify(jsonGenerator).writeStringField("restrictedField", givenDTO.restrictedField);
@ -163,11 +169,10 @@ public class JSonSerializationWithAccessFilterUnitTest {
public void shouldNotSerializeRestrictedFieldIfRequiredRoleIsNotCoveredByUser() throws IOException { public void shouldNotSerializeRestrictedFieldIfRequiredRoleIsNotCoveredByUser() throws IOException {
// given // given
MockSecurityContext.givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(GivenCustomerDto.class, 888L, Role.ANY_CUSTOMER_USER);
MockSecurityContext.givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ANY_CUSTOMER_USER);
// when // when
new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDTO).serialize(); new JSonSerializationWithAccessFilter<>(ctx, userRoleAssignmentService, jsonGenerator, null, givenDTO).serialize();
// then // then
verify(jsonGenerator, never()).writeStringField("restrictedField", givenDTO.restrictedField); verify(jsonGenerator, never()).writeStringField("restrictedField", givenDTO.restrictedField);
@ -188,7 +193,12 @@ public class JSonSerializationWithAccessFilterUnitTest {
// when // when
final Throwable actual = catchThrowable( final Throwable actual = catchThrowable(
() -> new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDtoWithUnimplementedFieldType) () -> new JSonSerializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonGenerator,
null,
givenDtoWithUnimplementedFieldType)
.serialize()); .serialize());
// then // then

View File

@ -2,33 +2,95 @@
package org.hostsharing.hsadminng.service.accessfilter; package org.hostsharing.hsadminng.service.accessfilter;
import static org.assertj.core.api.Assumptions.assumeThat; import static org.assertj.core.api.Assumptions.assumeThat;
import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.security.SecurityUtils; import org.hostsharing.hsadminng.security.SecurityUtils;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.mockito.Mockito;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
public class MockSecurityContext { public class MockSecurityContext {
public static void givenAuthenticatedUser() { private final UserRoleAssignmentService userRoleAssignmentService;
private final Collection<GrantedAuthority> authorities;
// TODO mhoennig: refactor this ctor to method withMock(...) returning a subclass to avoid null checks
public MockSecurityContext(final UserRoleAssignmentService userRoleAssignmentService) {
this.userRoleAssignmentService = userRoleAssignmentService;
this.authorities = new ArrayList<>();
}
public MockSecurityContext() {
this(null);
}
public MockSecurityContext havingAuthenticatedUser() {
return havingAuthenticatedUser("dummyUser");
}
public MockSecurityContext havingAuthenticatedUser(final String login) {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("dummyUser", "dummyPassword"));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken(login, "dummyPassword") {
@Override
public Collection<GrantedAuthority> getAuthorities() {
return authorities;
}
});
SecurityContextHolder.setContext(securityContext); SecurityContextHolder.setContext(securityContext);
SecurityUtils.clearUserRoles();
assumeThat(SecurityUtils.getCurrentUserLogin()).hasValue("dummyUser"); assumeThat(SecurityUtils.getCurrentUserLogin()).hasValue(login);
if (userRoleAssignmentService != null) {
Mockito.reset(userRoleAssignmentService);
}
authorities.clear();
return this;
} }
public static void givenUserHavingRole(final Class<?> onClass, final Long onId, final Role role) { public MockSecurityContext withRole(final Class<?> onClass, final Long onId, final Role... roles) {
if ((onClass == null || onId == null) && !role.isIndependent()) { if (userRoleAssignmentService == null) {
throw new IllegalArgumentException("dependent role " + role + " needs DtoClass and ID"); throw new IllegalStateException("mock not registered for: " + UserRoleAssignmentService.class.getSimpleName());
} }
SecurityUtils.addUserRole(onClass, onId, role); final EntityTypeId entityTypeId = onClass.getAnnotation(EntityTypeId.class);
assumeThat(entityTypeId).as("@" + EntityTypeId.class.getSimpleName() + " missing on class " + onClass.toString())
.isNotNull();
given(userRoleAssignmentService.getEffectiveRoleOfCurrentUser(entityTypeId.value(), onId))
.willReturn(new HashSet(Arrays.asList(roles)));
return this;
} }
public static void givenUserHavingRole(final Role role) { public MockSecurityContext withRole(final Role role) {
givenUserHavingRole(null, null, role); authorities.add(new GrantedAuthority() {
@Override
public String getAuthority() {
return role.asAuthority();
}
});
return this;
} }
private static class FakePrincipal {
private final String username;
public FakePrincipal(final String username) {
this.username = username;
}
@Override
public String toString() {
return username;
}
}
} }

View File

@ -123,6 +123,14 @@ public class RoleUnitTest {
assertThat(Role.ANY_CUSTOMER_USER.isIndependent()).isFalse(); assertThat(Role.ANY_CUSTOMER_USER.isIndependent()).isFalse();
} }
@Test
public void asAuthority() {
assertThat(Role.HOSTMASTER.asAuthority()).isEqualTo("ROLE_HOSTMASTER");
assertThat(Role.ADMIN.asAuthority()).isEqualTo("ROLE_ADMIN");
assertThat(Role.SUPPORTER.asAuthority()).isEqualTo("ROLE_SUPPORTER");
assertThat(Role.CONTRACTUAL_CONTACT.asAuthority()).isEqualTo("ROLE_USER");
}
@Test @Test
public void isBroadest() { public void isBroadest() {
assertThat(Role.broadest(Role.HOSTMASTER, Role.CONTRACTUAL_CONTACT)).isEqualTo(Role.HOSTMASTER); assertThat(Role.broadest(Role.HOSTMASTER, Role.CONTRACTUAL_CONTACT)).isEqualTo(Role.HOSTMASTER);

View File

@ -3,8 +3,6 @@ package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -18,7 +16,9 @@ import org.hostsharing.hsadminng.repository.MembershipRepository;
import org.hostsharing.hsadminng.service.AssetService; import org.hostsharing.hsadminng.service.AssetService;
import org.hostsharing.hsadminng.service.AssetValidator; import org.hostsharing.hsadminng.service.AssetValidator;
import org.hostsharing.hsadminng.service.MembershipValidator; import org.hostsharing.hsadminng.service.MembershipValidator;
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.MockSecurityContext;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
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;
@ -110,19 +110,25 @@ public class AssetDTOIntTest {
@MockBean @MockBean
private EntityManager em; private EntityManager em;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private MockSecurityContext securityContext;
@Before @Before
public void init() { public void init() {
given(customerRepository.findById(SOME_CUSTOMER_ID)).willReturn(Optional.of(SOME_CUSTOMER)); given(customerRepository.findById(SOME_CUSTOMER_ID)).willReturn(Optional.of(SOME_CUSTOMER));
given(membershipRepository.findById(SOME_MEMBERSHIP_ID)).willReturn(Optional.of(SOME_MEMBERSHIP)); given(membershipRepository.findById(SOME_MEMBERSHIP_ID)).willReturn(Optional.of(SOME_MEMBERSHIP));
given(assetRepository.findById(SOME_ASSET_ID)).willReturn((Optional.of(SOME_ASSET))); given(assetRepository.findById(SOME_ASSET_ID)).willReturn((Optional.of(SOME_ASSET)));
securityContext = new MockSecurityContext(userRoleAssignmentService);
} }
@Test @Test
public void shouldSerializePartiallyForFinancialCustomerContact() throws JsonProcessingException { public void shouldSerializePartiallyForFinancialCustomerContact() throws JsonProcessingException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.FINANCIAL_CONTACT);
givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.FINANCIAL_CONTACT);
final AssetDTO given = createSomeAssetDTO(SOME_ASSET_ID); final AssetDTO given = createSomeAssetDTO(SOME_ASSET_ID);
// when // when
@ -137,8 +143,7 @@ public class AssetDTOIntTest {
public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException { public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(Role.SUPPORTER);
givenUserHavingRole(Role.SUPPORTER);
final AssetDTO given = createSomeAssetDTO(SOME_ASSET_ID); final AssetDTO given = createSomeAssetDTO(SOME_ASSET_ID);
// when // when
@ -151,8 +156,7 @@ public class AssetDTOIntTest {
@Test @Test
public void shouldNotDeserializeForContractualCustomerContact() { public void shouldNotDeserializeForContractualCustomerContact() {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CONTRACTUAL_CONTACT);
givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CONTRACTUAL_CONTACT);
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")
@ -165,14 +169,14 @@ public class AssetDTOIntTest {
assertThat(actual).isInstanceOfSatisfying( assertThat(actual).isInstanceOfSatisfying(
BadRequestAlertException.class, BadRequestAlertException.class,
bre -> assertThat(bre.getMessage()) bre -> assertThat(bre.getMessage())
.isEqualTo("Update of field AssetDTO.remark prohibited for current user role CONTRACTUAL_CONTACT")); .isEqualTo(
"Update of field AssetDTO.remark prohibited for current user roles CONTRACTUAL_CONTACT+ANYBODY"));
} }
@Test @Test
public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException { public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(Role.ADMIN);
givenUserHavingRole(Role.ADMIN);
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")

View File

@ -2,8 +2,6 @@
package org.hostsharing.hsadminng.service.dto; package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -12,7 +10,9 @@ import org.hostsharing.hsadminng.domain.enumeration.CustomerKind;
import org.hostsharing.hsadminng.domain.enumeration.VatRegion; import org.hostsharing.hsadminng.domain.enumeration.VatRegion;
import org.hostsharing.hsadminng.repository.CustomerRepository; import org.hostsharing.hsadminng.repository.CustomerRepository;
import org.hostsharing.hsadminng.service.CustomerService; import org.hostsharing.hsadminng.service.CustomerService;
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.MockSecurityContext;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
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;
@ -20,6 +20,7 @@ import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -60,12 +61,21 @@ public class CustomerDTOUnitTest {
@MockBean @MockBean
private CustomerService customerService; private CustomerService customerService;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private MockSecurityContext securityContext;
@Before
public void init() {
securityContext = new MockSecurityContext(userRoleAssignmentService);
}
@Test @Test
public void testSerializationAsContractualCustomerContact() throws JsonProcessingException { public void testSerializationAsContractualCustomerContact() throws JsonProcessingException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.CONTRACTUAL_CONTACT);
givenUserHavingRole(CustomerDTO.class, 1234L, Role.CONTRACTUAL_CONTACT);
CustomerDTO given = createSomeCustomerDTO(1234L); CustomerDTO given = createSomeCustomerDTO(1234L);
// when // when
@ -80,8 +90,7 @@ public class CustomerDTOUnitTest {
public void testSerializationAsTechnicalCustomerUser() throws JsonProcessingException { public void testSerializationAsTechnicalCustomerUser() throws JsonProcessingException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.TECHNICAL_CONTACT);
givenUserHavingRole(CustomerDTO.class, 1234L, Role.TECHNICAL_CONTACT);
CustomerDTO given = createSomeCustomerDTO(1234L); CustomerDTO given = createSomeCustomerDTO(1234L);
// when // when
@ -102,8 +111,7 @@ public class CustomerDTOUnitTest {
public void testSerializationAsSupporter() throws JsonProcessingException { public void testSerializationAsSupporter() throws JsonProcessingException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(Role.SUPPORTER);
givenUserHavingRole(CustomerDTO.class, null, Role.SUPPORTER);
CustomerDTO given = createSomeCustomerDTO(1234L); CustomerDTO given = createSomeCustomerDTO(1234L);
// when // when
@ -116,8 +124,7 @@ public class CustomerDTOUnitTest {
@Test @Test
public void testDeserializeAsContractualCustomerContact() throws IOException { public void testDeserializeAsContractualCustomerContact() throws IOException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.CONTRACTUAL_CONTACT);
givenUserHavingRole(CustomerDTO.class, 1234L, Role.CONTRACTUAL_CONTACT);
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

@ -4,13 +4,13 @@ package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon; import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import org.hostsharing.hsadminng.service.CustomerService; 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.accessfilter.JSonDeserializationWithAccessFilter; import org.hostsharing.hsadminng.service.accessfilter.JSonDeserializationWithAccessFilter;
import org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
@ -52,12 +52,17 @@ public class MembershipDTOUnitTest {
@Mock @Mock
private TreeNode treeNode; private TreeNode treeNode;
@Mock
private UserRoleAssignmentService userRoleAssignmentService;
@Mock @Mock
private MembershipService membershipService; private MembershipService membershipService;
@Mock @Mock
private CustomerService customerService; private CustomerService customerService;
private MockSecurityContext securityContext;
@Before @Before
public void init() { public void init() {
given(jsonParser.getCodec()).willReturn(codec); given(jsonParser.getCodec()).willReturn(codec);
@ -69,16 +74,22 @@ public class MembershipDTOUnitTest {
Optional.of( Optional.of(
new CustomerDTO() new CustomerDTO()
.with(dto -> dto.setId(1234L)))); .with(dto -> dto.setId(1234L))));
securityContext = new MockSecurityContext(userRoleAssignmentService);
} }
@Test @Test
public void adminShouldHaveRightToCreate() throws IOException { public void adminShouldHaveRightToCreate() throws IOException {
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(Role.ADMIN);
givenUserHavingRole(null, null, Role.ADMIN);
givenJSonTree(asJSon(ImmutablePair.of("customerId", 1234L))); givenJSonTree(asJSon(ImmutablePair.of("customerId", 1234L)));
// when // when
final MembershipDTO actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, MembershipDTO.class) final MembershipDTO actualDto = new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
MembershipDTO.class)
.deserialize(); .deserialize();
// then // then
@ -87,13 +98,17 @@ public class MembershipDTOUnitTest {
@Test @Test
public void contractualContactShouldNotHaveRightToCreate() throws IOException { public void contractualContactShouldNotHaveRightToCreate() throws IOException {
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, 1234L, Role.CONTRACTUAL_CONTACT);
givenUserHavingRole(CustomerDTO.class, 1234L, Role.CONTRACTUAL_CONTACT);
givenJSonTree(asJSon(ImmutablePair.of("customerId", 1234L))); givenJSonTree(asJSon(ImmutablePair.of("customerId", 1234L)));
// when // when
Throwable exception = catchThrowable( Throwable exception = catchThrowable(
() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, MembershipDTO.class).deserialize()); () -> new JSonDeserializationWithAccessFilter<>(
ctx,
userRoleAssignmentService,
jsonParser,
null,
MembershipDTO.class).deserialize());
// then // then
assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> { assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> {

View File

@ -3,8 +3,6 @@ package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.hostsharing.hsadminng.service.dto.SepaMandateDTOUnitTest.createSampleDTO; import static org.hostsharing.hsadminng.service.dto.SepaMandateDTOUnitTest.createSampleDTO;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -16,7 +14,9 @@ import org.hostsharing.hsadminng.repository.MembershipRepository;
import org.hostsharing.hsadminng.repository.SepaMandateRepository; import org.hostsharing.hsadminng.repository.SepaMandateRepository;
import org.hostsharing.hsadminng.service.MembershipValidator; import org.hostsharing.hsadminng.service.MembershipValidator;
import org.hostsharing.hsadminng.service.SepaMandateService; import org.hostsharing.hsadminng.service.SepaMandateService;
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.MockSecurityContext;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
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;
@ -98,18 +98,24 @@ public class SepaMandateDTOIntTest {
@MockBean @MockBean
private EntityManager em; private EntityManager em;
@MockBean
public UserRoleAssignmentService userRoleAssignmentService;
private MockSecurityContext securityContext;
@Before @Before
public void init() { public void init() {
given(customerRepository.findById(SOME_CUSTOMER_ID)).willReturn(Optional.of(SOME_CUSTOMER)); given(customerRepository.findById(SOME_CUSTOMER_ID)).willReturn(Optional.of(SOME_CUSTOMER));
given(sepaMandateRepository.findById(SOME_SEPA_MANDATE_ID)).willReturn((Optional.of(SOME_SEPA_MANDATE))); given(sepaMandateRepository.findById(SOME_SEPA_MANDATE_ID)).willReturn((Optional.of(SOME_SEPA_MANDATE)));
securityContext = new MockSecurityContext(userRoleAssignmentService);
} }
@Test @Test
public void shouldSerializePartiallyForFinancialCustomerContact() throws JsonProcessingException { public void shouldSerializePartiallyForFinancialCustomerContact() throws JsonProcessingException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.FINANCIAL_CONTACT);
givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.FINANCIAL_CONTACT);
final SepaMandateDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID); final SepaMandateDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID);
// when // when
@ -124,8 +130,7 @@ public class SepaMandateDTOIntTest {
public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException { public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(Role.SUPPORTER);
givenUserHavingRole(Role.SUPPORTER);
final SepaMandateDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID); final SepaMandateDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID);
// when // when
@ -138,8 +143,7 @@ public class SepaMandateDTOIntTest {
@Test @Test
public void shouldNotDeserializeForContractualCustomerContact() { public void shouldNotDeserializeForContractualCustomerContact() {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CONTRACTUAL_CONTACT);
givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CONTRACTUAL_CONTACT);
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")
@ -152,14 +156,13 @@ 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 CONTRACTUAL_CONTACT")); "Update of field SepaMandateDTO.remark prohibited for current user roles CONTRACTUAL_CONTACT+ANYBODY"));
} }
@Test @Test
public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException { public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(Role.ADMIN);
givenUserHavingRole(Role.ADMIN);
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")

View File

@ -3,8 +3,6 @@ package org.hostsharing.hsadminng.service.dto;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.catchThrowable;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -18,7 +16,9 @@ import org.hostsharing.hsadminng.repository.ShareRepository;
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.accessfilter.JSonBuilder; import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
import org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
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;
@ -109,19 +109,25 @@ public class ShareDTOIntTest {
@MockBean @MockBean
private EntityManager em; private EntityManager em;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private MockSecurityContext securityContext;
@Before @Before
public void init() { public void init() {
given(customerRepository.findById(SOME_CUSTOMER_ID)).willReturn(Optional.of(SOME_CUSTOMER)); given(customerRepository.findById(SOME_CUSTOMER_ID)).willReturn(Optional.of(SOME_CUSTOMER));
given(membershipRepository.findById(SOME_MEMBERSHIP_ID)).willReturn(Optional.of(SOME_MEMBERSHIP)); given(membershipRepository.findById(SOME_MEMBERSHIP_ID)).willReturn(Optional.of(SOME_MEMBERSHIP));
given(shareRepository.findById(SOME_SHARE_ID)).willReturn((Optional.of(SOME_SHARE))); given(shareRepository.findById(SOME_SHARE_ID)).willReturn((Optional.of(SOME_SHARE)));
securityContext = new MockSecurityContext(userRoleAssignmentService);
} }
@Test @Test
public void shouldSerializePartiallyForFinancialCustomerContact() throws JsonProcessingException { public void shouldSerializePartiallyForFinancialCustomerContact() throws JsonProcessingException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.FINANCIAL_CONTACT);
givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.FINANCIAL_CONTACT);
final ShareDTO given = createSomeShareDTO(SOME_SHARE_ID); final ShareDTO given = createSomeShareDTO(SOME_SHARE_ID);
// when // when
@ -136,8 +142,7 @@ public class ShareDTOIntTest {
public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException { public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(Role.SUPPORTER);
givenUserHavingRole(Role.SUPPORTER);
final ShareDTO given = createSomeShareDTO(SOME_SHARE_ID); final ShareDTO given = createSomeShareDTO(SOME_SHARE_ID);
// when // when
@ -150,8 +155,7 @@ public class ShareDTOIntTest {
@Test @Test
public void shouldNotDeserializeForContractualCustomerContact() { public void shouldNotDeserializeForContractualCustomerContact() {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CONTRACTUAL_CONTACT);
givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CONTRACTUAL_CONTACT);
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")
@ -164,14 +168,14 @@ public class ShareDTOIntTest {
assertThat(actual).isInstanceOfSatisfying( assertThat(actual).isInstanceOfSatisfying(
BadRequestAlertException.class, BadRequestAlertException.class,
bre -> assertThat(bre.getMessage()) bre -> assertThat(bre.getMessage())
.isEqualTo("Update of field ShareDTO.remark prohibited for current user role CONTRACTUAL_CONTACT")); .isEqualTo(
"Update of field ShareDTO.remark prohibited for current user roles CONTRACTUAL_CONTACT+ANYBODY"));
} }
@Test @Test
public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException { public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException {
// given // given
givenAuthenticatedUser(); securityContext.havingAuthenticatedUser().withRole(Role.ADMIN);
givenUserHavingRole(Role.ADMIN);
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

@ -14,6 +14,7 @@ import org.hostsharing.hsadminng.domain.enumeration.AssetAction;
import org.hostsharing.hsadminng.repository.AssetRepository; import org.hostsharing.hsadminng.repository.AssetRepository;
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.accessfilter.MockSecurityContext; import org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.dto.AssetDTO; import org.hostsharing.hsadminng.service.dto.AssetDTO;
@ -26,6 +27,7 @@ import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
@ -94,14 +96,18 @@ public class AssetResourceIntTest {
@Autowired @Autowired
private Validator validator; private Validator validator;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private MockSecurityContext securityContext;
private MockMvc restAssetMockMvc; private MockMvc restAssetMockMvc;
private Asset asset; private Asset asset;
@Before @Before
public void setup() { public void setup() {
MockSecurityContext.givenAuthenticatedUser(); securityContext = new MockSecurityContext(userRoleAssignmentService).havingAuthenticatedUser().withRole(Role.ADMIN);
MockSecurityContext.givenUserHavingRole(Role.ADMIN);
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
final AssetResource assetResource = new AssetResource(assetService, assetQueryService); final AssetResource assetResource = new AssetResource(assetService, assetQueryService);

View File

@ -3,8 +3,6 @@ package org.hostsharing.hsadminng.web.rest;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasItem;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService; 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.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@ -18,6 +16,7 @@ import org.hostsharing.hsadminng.domain.enumeration.VatRegion;
import org.hostsharing.hsadminng.repository.CustomerRepository; import org.hostsharing.hsadminng.repository.CustomerRepository;
import org.hostsharing.hsadminng.service.CustomerQueryService; import org.hostsharing.hsadminng.service.CustomerQueryService;
import org.hostsharing.hsadminng.service.CustomerService; import org.hostsharing.hsadminng.service.CustomerService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext; import org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.dto.CustomerDTO; import org.hostsharing.hsadminng.service.dto.CustomerDTO;
@ -30,9 +29,12 @@ import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@ -107,6 +109,11 @@ public class CustomerResourceIntTest {
private static int otherCounter = 0; private static int otherCounter = 0;
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
@Autowired @Autowired
private CustomerRepository customerRepository; private CustomerRepository customerRepository;
@ -134,19 +141,19 @@ public class CustomerResourceIntTest {
@Autowired @Autowired
private Validator validator; private Validator validator;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private MockSecurityContext securityContext;
private MockMvc restCustomerMockMvc; private MockMvc restCustomerMockMvc;
private Customer customer; private Customer customer;
@Before @Before
public void setup() { public void setup() {
MockSecurityContext.givenAuthenticatedUser();
MockSecurityContext.givenUserHavingRole(Role.ADMIN);
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
securityContext = new MockSecurityContext(userRoleAssignmentService).havingAuthenticatedUser().withRole(Role.ADMIN);
givenAuthenticatedUser();
givenUserHavingRole(Role.ADMIN);
final CustomerResource customerResource = new CustomerResource(customerService, customerQueryService); final CustomerResource customerResource = new CustomerResource(customerService, customerQueryService);
this.restCustomerMockMvc = MockMvcBuilders.standaloneSetup(customerResource) this.restCustomerMockMvc = MockMvcBuilders.standaloneSetup(customerResource)

View File

@ -15,6 +15,7 @@ import org.hostsharing.hsadminng.domain.Share;
import org.hostsharing.hsadminng.repository.MembershipRepository; import org.hostsharing.hsadminng.repository.MembershipRepository;
import org.hostsharing.hsadminng.service.MembershipQueryService; import org.hostsharing.hsadminng.service.MembershipQueryService;
import org.hostsharing.hsadminng.service.MembershipService; import org.hostsharing.hsadminng.service.MembershipService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext; import org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.dto.MembershipDTO; import org.hostsharing.hsadminng.service.dto.MembershipDTO;
@ -27,6 +28,7 @@ import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
@ -100,14 +102,18 @@ public class MembershipResourceIntTest {
@Autowired @Autowired
private Validator validator; private Validator validator;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private MockSecurityContext securityContext;
private MockMvc restMembershipMockMvc; private MockMvc restMembershipMockMvc;
private Membership membership; private Membership membership;
@Before @Before
public void setup() { public void setup() {
MockSecurityContext.givenAuthenticatedUser(); securityContext = new MockSecurityContext(userRoleAssignmentService).havingAuthenticatedUser().withRole(Role.ADMIN);
MockSecurityContext.givenUserHavingRole(Role.ADMIN);
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
final MembershipResource membershipResource = new MembershipResource(membershipService, membershipQueryService); final MembershipResource membershipResource = new MembershipResource(membershipService, membershipQueryService);

View File

@ -13,6 +13,7 @@ import org.hostsharing.hsadminng.domain.SepaMandate;
import org.hostsharing.hsadminng.repository.SepaMandateRepository; import org.hostsharing.hsadminng.repository.SepaMandateRepository;
import org.hostsharing.hsadminng.service.SepaMandateQueryService; import org.hostsharing.hsadminng.service.SepaMandateQueryService;
import org.hostsharing.hsadminng.service.SepaMandateService; import org.hostsharing.hsadminng.service.SepaMandateService;
import org.hostsharing.hsadminng.service.UserRoleAssignmentService;
import org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext; import org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.dto.CustomerDTO; import org.hostsharing.hsadminng.service.dto.CustomerDTO;
@ -26,6 +27,7 @@ import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
@ -104,14 +106,18 @@ public class SepaMandateResourceIntTest {
@Autowired @Autowired
private Validator validator; private Validator validator;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private MockSecurityContext securityContext;
private MockMvc restSepaMandateMockMvc; private MockMvc restSepaMandateMockMvc;
private SepaMandate sepaMandate; private SepaMandate sepaMandate;
@Before @Before
public void setup() { public void setup() {
MockSecurityContext.givenAuthenticatedUser(); securityContext = new MockSecurityContext(userRoleAssignmentService).havingAuthenticatedUser().withRole(Role.ADMIN);
MockSecurityContext.givenUserHavingRole(Role.ADMIN);
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
final SepaMandateResource sepaMandateResource = new SepaMandateResource(sepaMandateService, sepaMandateQueryService); final SepaMandateResource sepaMandateResource = new SepaMandateResource(sepaMandateService, sepaMandateQueryService);
@ -187,8 +193,8 @@ public class SepaMandateResourceIntTest {
sepaMandateDTO.setRemark(null); sepaMandateDTO.setRemark(null);
sepaMandateDTO.setRevokationDocumentDate(null); sepaMandateDTO.setRevokationDocumentDate(null);
sepaMandateDTO.setLastUsedDate(null); sepaMandateDTO.setLastUsedDate(null);
MockSecurityContext.givenAuthenticatedUser(); securityContext.havingAuthenticatedUser()
MockSecurityContext.givenUserHavingRole(CustomerDTO.class, sepaMandateDTO.getCustomerId(), Role.FINANCIAL_CONTACT); .withRole(CustomerDTO.class, sepaMandateDTO.getCustomerId(), Role.FINANCIAL_CONTACT);
restSepaMandateMockMvc.perform( restSepaMandateMockMvc.perform(
post("/api/sepa-mandates") post("/api/sepa-mandates")

View File

@ -14,6 +14,7 @@ import org.hostsharing.hsadminng.domain.enumeration.ShareAction;
import org.hostsharing.hsadminng.repository.ShareRepository; import org.hostsharing.hsadminng.repository.ShareRepository;
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.accessfilter.MockSecurityContext; import org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext;
import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.accessfilter.Role;
import org.hostsharing.hsadminng.service.dto.ShareDTO; import org.hostsharing.hsadminng.service.dto.ShareDTO;
@ -26,6 +27,7 @@ import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
@ -92,14 +94,18 @@ public class ShareResourceIntTest {
@Autowired @Autowired
private Validator validator; private Validator validator;
@MockBean
private UserRoleAssignmentService userRoleAssignmentService;
private MockSecurityContext securityContext;
private MockMvc restShareMockMvc; private MockMvc restShareMockMvc;
private Share share; private Share share;
@Before @Before
public void setup() { public void setup() {
MockSecurityContext.givenAuthenticatedUser(); securityContext = new MockSecurityContext(userRoleAssignmentService).havingAuthenticatedUser().withRole(Role.ADMIN);
MockSecurityContext.givenUserHavingRole(Role.ADMIN);
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
final ShareResource shareResource = new ShareResource(shareService, shareQueryService); final ShareResource shareResource = new ShareResource(shareService, shareQueryService);

View File

@ -10,10 +10,10 @@ 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.domain.enumeration.UserRole;
import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository; import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository;
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.web.rest.errors.ExceptionTranslator; import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
import org.junit.Before; import org.junit.Before;
@ -50,8 +50,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 UserRole DEFAULT_ASSIGNED_ROLE = UserRole.HOSTMASTER; private static final Role DEFAULT_ASSIGNED_ROLE = Role.HOSTMASTER;
private static final UserRole UPDATED_ASSIGNED_ROLE = UserRole.ADMIN; private static final Role UPDATED_ASSIGNED_ROLE = Role.ADMIN;
@Autowired @Autowired
private UserRoleAssignmentRepository userRoleAssignmentRepository; private UserRoleAssignmentRepository userRoleAssignmentRepository;