Skip to content

Commit

Permalink
Issue #79: Refactor UserController as demonstrated in PR 13
Browse files Browse the repository at this point in the history
This is step one of the refactoring which:
1. pulls the existing code used to build the `roleMap` out into its own, testable method
2. implements a test to verify existing functionality
  • Loading branch information
ddelponte authored and sdelamo committed Oct 19, 2017
1 parent 687c322 commit d35939f
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,19 +77,26 @@ class UserController extends AbstractS2UiDomainController {
protected Map buildUserModel(user) {

Set userRoleNames = user[authoritiesPropertyName].collect { it[authorityNameField] }
def granted = [:]
def notGranted = [:]
Map roleMap = buildRoleMap(userRoleNames)

[roleMap: roleMap, tabData: tabData, user: user]
}

protected Map buildRoleMap(Set userRoleNames) {
if (!userRoleNames) {
return [:]
}
Map granted = [:]
Map notGranted = [:]
for (role in sortedRoles()) {
String authority = role[authorityNameField]
if (userRoleNames.contains(authority)) {
granted[(role)] = userRoleNames.contains(authority)
}
else {
} else {
notGranted[(role)] = userRoleNames.contains(authority)
}
}

[roleMap: granted + notGranted, tabData: tabData, user: user]
return granted + notGranted
}

protected List sortedRoles() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package grails.plugin.springsecurity.ui

import grails.testing.web.controllers.ControllerUnitTest
import spock.lang.Specification
import spock.lang.Unroll

@Unroll
class UserControllerSpec extends Specification implements ControllerUnitTest<UserController> {
static final Map ADMIN_ROLE = [authority: "ROLE_ADMIN"]
static final Map SUPER_ADMIN_ROLE = [authority: "ROLE_SUPER_ADMIN"]
static final Map USER_ROLE = [authority: "ROLE_USER"]

void "verify proper construction of roleMap for user with roles #rolesAssignedToUser"() {
given: "the authority name field has been set to the default name of 'authority'"
controller.authorityNameField = "authority"

and: "we mock the returning of all Role instances within the database"
controller.metaClass.sortedRoles = {
[
ADMIN_ROLE,
SUPER_ADMIN_ROLE,
USER_ROLE
]
}

when: "we call buildRoleMap with the role names associated to the user"
Map results = controller.buildRoleMap(rolesAssignedToUser)

then: "the user is only granted access to roles with which they are associated"
results == expectedResults

where:
rolesAssignedToUser | expectedResults
[ADMIN_ROLE.authority, USER_ROLE.authority] as Set | [(ADMIN_ROLE): true, (SUPER_ADMIN_ROLE): false, (USER_ROLE): true]
[] as Set | [:]
null | [:]
}
}

0 comments on commit d35939f

Please sign in to comment.