2

我想检索所有具有特定角色的用户,例如“ROLE_USER”。

下面是用户、角色和用户角色的域类。

用户.groovy

class User {

    transient springSecurityService

    String username
    String password
        String email
    boolean enabled
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired

    static constraints = {
        username blank: false, unique: true
        password blank: false
    }

    static mapping = {
        password column: '`password`'
    }

    Set<Role> getAuthorities() {
        UserRole.findAllByUser(this).collect { it.role } as Set
    }

    def beforeInsert() {
        encodePassword()
    }

    def beforeUpdate() {
        if (isDirty('password')) {
            encodePassword()
        }
    }

    protected void encodePassword() {
        password = springSecurityService.encodePassword(password)
    }
}

角色.groovy

class Role {

    String authority

    static mapping = {
        cache true
    }

    static constraints = {
        authority blank: false, unique: true
    }
}

用户角色.groovy

class UserRole implements Serializable {

    User user
    Role role

    boolean equals(other) {
        if (!(other instanceof UserRole)) {
            return false
        }

        other.user?.id == user?.id &&
            other.role?.id == role?.id
    }

    int hashCode() {
        def builder = new HashCodeBuilder()
        if (user) builder.append(user.id)
        if (role) builder.append(role.id)
        builder.toHashCode()
    }

    static UserRole get(long userId, long roleId) {
        find 'from UserRole where user.id=:userId and role.id=:roleId',
            [userId: userId, roleId: roleId]
    }

    static UserRole create(User user, Role role, boolean flush = false) {
        new UserRole(user: user, role: role).save(flush: flush, insert: true)
    }

    static boolean remove(User user, Role role, boolean flush = false) {
        UserRole instance = UserRole.findByUserAndRole(user, role)
        if (!instance) {
            return false
        }

        instance.delete(flush: flush)
        true
    }

    static void removeAll(User user) {
        executeUpdate 'DELETE FROM UserRole WHERE user=:user', [user: user]
    }

    static void removeAll(Role role) {
        executeUpdate 'DELETE FROM UserRole WHERE role=:role', [role: role]
    }

    static mapping = {
        id composite: ['role', 'user']
        version false
    }
}

这些域类是由Spring Security插件生成的。
我只为用户类添加了电子邮件字段。

这是我的UserController.groovy

class UserController {

    def index = {
       }


    def list = {

        def role = Role.findByAuthority("ROLE_USER")
        println "role id "+role.id

        def users = User.findAll()         //Its giving me all Users regardless of Role
        println "total users "+users.size()
        for(user in users)
        {
            println "User "+user.username+" "+user.email
        }
        render (view: "listUsers", model:[users:users])

    }
}

在我使用的列表操作中,User.findAll()但它给了我所有角色的所有用户。
我只想要某个角色的用户列表..

编辑

将角色分配给新创建的用户的代码

def username = params.username
def emailID = params.emailID
def password = params.password

def testUser = new User(username: username, enabled: true, password: password,email:emailID)
testUser.save(flush: true)
def userRole = new Role(authority: 'ROLE_USER').save(flush: true)
UserRole.create testUser, userRole, true

谢谢..

4

1 回答 1

4

代替

def users = User.findAll()

def users = UserRole.findAllByRole(role).user

并且您应该获得具有所需角色的所有用户。

编辑

在您的代码示例中,您尝试为用户创建一个新角色。由于具有 ROLE_USER 权限的角色已经存在并且权限必须是唯一的(请参阅角色类中的“约束”部分),因此无法将这个新角色保存到数据库中。因为您分配的角色UserRole.create在数据库中不存在,所以也没有保存 UserRole。您必须将现有角色分配给新用户(例如,使用“Role.findByAuthority”)。

根据 Spring Source,在 Bootstrap.groovy 中创建角色是一个好主意,因为角色“通常在应用程序生命周期的早期定义并对应于不变的参考数据。这使得 BootStrap 成为创建它们的理想场所。” ( Spring源码博客)

于 2013-01-25T11:19:30.813 回答