grails - 如何获取在grails中具有特定角色的所有用户

标签 grails find

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

下面是 User、Role 和 UserRole 的域类。

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

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

谢谢..

最佳答案

替换

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)

关于grails - 如何获取在grails中具有特定角色的所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14520592/

相关文章:

ruby-on-rails - 我如何find()在某些字段中唯一的所有记录?

c++ - std::find 中的 Lambda 问题

regex - sed mass 通过终端替换 CSS 样式

ruby-on-rails - 在Rails中为所有事件记录模型添加查找条件

grails - Griffon Gsql-如何在Config.properties文件中配置数据源?

grails - 我在输入类型的文本中输入了一个值,但在params.descrption中使用空值。为什么?

grails - gradle测试未运行Geb测试

hibernate - Grails 2.5和SpringAcl:无法访问aclCacheManager bean

grails - 如何在 grails Controller 中使用路径变量?

c++ - 使用 map::find 查找键并返回值