【问题标题】:How to get All users which have a certain Role in grails如何获取所有在grails中具有特定角色的用户
【发布时间】:2013-01-25 20:37:32
【问题描述】:

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

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

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)
    }
}

Role.groovy

class Role {

    String authority

    static mapping = {
        cache true
    }

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

UserRole.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

谢谢..

【问题讨论】:

    标签: grails find


    【解决方案1】:

    替换

    def users = User.findAll()
    

    def users = UserRole.findAllByRole(role).user
    

    你应该让所有用户都拥有所需的角色。

    编辑

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

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

    【讨论】:

    • 不!我仍然没有得到任何东西
    • 您确定角色已正确分配给用户吗? println UserRole.list().role.authority 的输出是什么?
    • 我只得到这个 [ROLE_ADMIN]...检查我现在更新的代码,以便为新用户分配角色
    • 在您创建测试用户时是否已经存在具有 ROLE_USER 权限的角色(Role.list().authority 查看现有角色)?您必须使用现有角色:UserRole.create testUser, Role.findByAuthority('ROLE_USER'), true
    • 我是 grails 的新手。你能告诉我我需要在哪里创建这个 ROLE_USER,因为我是为 ROLE_ADMIN 做的并且它有效,所以认为这是创建 ROLE_USER 的方法
    猜你喜欢
    • 2021-02-24
    • 2016-06-18
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    相关资源
    最近更新 更多