2

「ROLE_USER」のような特定のロールを持つすべてのユーザーを取得したい。

以下は、User、Role、および UserRole のドメイン クラスです。

ユーザー.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プラグインによって生成されます。
User クラスの email フィールドのみを追加しました。

ここに私の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 Source ブログ)

于 2013-01-25T11:19:30.813 に答える