UserRoleActivationStrategy implements ActivationStrategy { @Override public boolean isActive(FeatureState state, FeatureUser user) { if (user != null) { Collection<String> userRoles = (Collection<String>) user.getAttribute(USER_ATTRIBUTE_ROLES); if (userRoles != null) { String rolesAsString = state.getParameter(PARAM_ROLES_NAME); if (Strings.isNotBlank(rolesAsString)) { List<String> roles = Strings.splitAndTrim(rolesAsString, ","); for (String authority : roles) { if (userRoles.contains(authority)) { return true; } } } } } return false; }  @Override String getId(); @Override String getName(); @Override boolean isActive(FeatureState state, FeatureUser user); @Override Parameter[] getParameters(); static final String ID; static final String NAME; static final String PARAM_ROLES_NAME; static final String PARAM_ROLES_LABEL; static final String PARAM_ROLES_DESC; static final String USER_ATTRIBUTE_ROLES; }
@Test void isActiveWillReturnFalseWhenThereIsNoUser() { boolean result = activationStrategy.isActive(state, null); assertFalse(result); }
@Test void isActiveWillReturnFalseWhenThereIsNoRolesAttribute() { when(user.getAttribute(USER_ATTRIBUTE_ROLES)).thenReturn(null); boolean result = activationStrategy.isActive(state, user); assertFalse(result); }
@Test void isActiveWillReturnFalseWhenThereIsNoRolesParam() { when(user.getAttribute(USER_ATTRIBUTE_ROLES)).thenReturn(userRoles); when(state.getParameter(PARAM_ROLES_NAME)).thenReturn(null); boolean result = activationStrategy.isActive(state, user); assertFalse(result); }
@Test void isActiveWillReturnFalseWhenRolesParamIsBlank() { when(user.getAttribute(USER_ATTRIBUTE_ROLES)).thenReturn(userRoles); when(state.getParameter(PARAM_ROLES_NAME)).thenReturn(" "); boolean result = activationStrategy.isActive(state, user); assertFalse(result); }
@Test void isActiveWillReturnFalseWhenUserHasNoneOfSelectedRoles() { when(user.getAttribute(USER_ATTRIBUTE_ROLES)).thenReturn(userRoles); when(state.getParameter(PARAM_ROLES_NAME)).thenReturn("ROLE_1, ROLE_2, ROLE_3"); boolean result = activationStrategy.isActive(state, user); assertFalse(result); }
@Test void isActiveWillReturnTrueWhenUserHasAnyOfSelectedRoles() { userRoles.add("ROLE_2"); when(user.getAttribute(USER_ATTRIBUTE_ROLES)).thenReturn(userRoles); when(state.getParameter(PARAM_ROLES_NAME)).thenReturn("ROLE_1, ROLE_2, ROLE_3"); boolean result = activationStrategy.isActive(state, user); assertTrue(result); }
@Test void doesntFailForOtherCollectionTypes() { Collection<String> userRoles = new ArrayList<String>(); userRoles.add("SOME_ROLE"); when(user.getAttribute(USER_ATTRIBUTE_ROLES)).thenReturn(userRoles); when(state.getParameter(PARAM_ROLES_NAME)).thenReturn("SOME_ROLE"); boolean result = activationStrategy.isActive(state, user); assertTrue(result); }