簡體   English   中英

Grails Spring Security查詢沒有特定角色的用戶

[英]Grails Spring Security querying users which don't have a certain role

使用Grails春季安全性REST (本身使用Grails春季安全性核心 ),我生成了UserRoleUserRole類。

用戶:

class User extends DomainBase{

    transient springSecurityService

    String username
    String password
    String firstName
    String lastNameOrTitle
    String email
    boolean showEmail
    String phoneNumber
    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired

    static transients = ['springSecurityService']

    static hasMany = [
            roles: Role,
            ratings: Rating,
            favorites: Favorite
    ]

    static constraints = {
        username blank: false, unique: true
        password blank: false
        firstName nullable: true, blank: false
        lastNameOrTitle nullable: false, blank: false
        email nullable: false, blank: false
        phoneNumber nullable: true
    }

    static mapping = {
        DomainUtil.inheritDomainMappingFrom(DomainBase, delegate)
        id column: 'user_id', generator: 'sequence', params: [sequence: 'user_seq']
        username column: 'username'
        password column: 'password'
        enabled column: 'enabled'
        accountExpired column: 'account_expired'
        accountLocked column: 'account_locked'
        passwordExpired column: 'password_expired'
        roles joinTable: [
                name: 'user_role',
                column: 'role_id',
                key: 'user_id']
    }

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

    def beforeInsert() {
        encodePassword()
    }

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

    protected void encodePassword() {
        password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
    }
}

角色:

class Role {

    String authority

    static mapping = {
        cache true
        id column: 'role_id', generator: 'sequence', params: [sequence: 'role_seq']
        authority column: 'authority'
    }

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

UserRole的:

class UserRole implements Serializable {

    private static final long serialVersionUID = 1

    static belongsTo = [
            user: User,
            role: Role
    ]
//    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) {
        UserRole.where {
            user == User.load(userId) &&
                    role == Role.load(roleId)
        }.get()
    }

    static boolean exists(long userId, long roleId) {
        UserRole.where {
            user == User.load(userId) &&
                    role == Role.load(roleId)
        }.count() > 0
    }

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

    static boolean remove(User u, Role r, boolean flush = false) {
        if (u == null || r == null) return false

        int rowCount = UserRole.where {
            user == User.load(u.id) &&
                    role == Role.load(r.id)
        }.deleteAll()

        if (flush) {
            UserRole.withSession { it.flush() }
        }

        rowCount > 0
    }

    static void removeAll(User u, boolean flush = false) {
        if (u == null) return

        UserRole.where {
            user == User.load(u.id)
        }.deleteAll()

        if (flush) {
            UserRole.withSession { it.flush() }
        }
    }

    static void removeAll(Role r, boolean flush = false) {
        if (r == null) return

        UserRole.where {
            role == Role.load(r.id)
        }.deleteAll()

        if (flush) {
            UserRole.withSession { it.flush() }
        }
    }

    static constraints = {
        role validator: { Role r, UserRole ur ->
            if (ur.user == null) return
            boolean existing = false
            UserRole.withNewSession {
                existing = UserRole.exists(ur.user.id, r.id)
            }
            if (existing) {
                return 'userRole.exists'
            }
        }
    }

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

現在,我希望創建一個管理員區域,管理員可以在其中修改/啟用用戶帳戶,但不能接觸其他管理員,因此,我決定創建一個可分頁查詢,該查詢將僅選擇沒有ROLE_ADMIN的用戶角色,因為管理員同時具有ROLE_USERROLE_ADMIN角色。

從上面的代碼可以看出,我已經稍微修改了默認生成的代碼,並向User類中添加了joinTable而不是hasMany: [roles:UserRole]或將其保持為默認值而不引用任何角色。 進行此更改的原因是因為查詢UserRole時,偶爾會出現重復,這會使分頁變得困難。

因此,在當前的設置下,我設法創建了兩個查詢,這些查詢使我能夠僅提取沒有管理員角色的用戶。

def rolesToIgnore = ["ROLE_ADMIN"]
def userIdsWithGivenRoles = User.createCriteria().list() {
    projections {
        property "id"
    }
    roles {
        'in' "authority", rolesToIgnore
    }
}

def usersWithoutGivenRoles = User.createCriteria().list(max: 10, offset: 0) {
    not {
        'in' "id", userIdsWithGivenRoles
    }
}

第一個查詢獲取具有ROLE_ADMIN角色的所有用戶ID的列表,然后第二個查詢獲取其ID不在上一個列表中的所有用戶。

這有效且可分頁,但是由於兩個原因而困擾我:

  1. 對我來說, joinTable on User似乎“很討厭”。 當我已經有一個特定的類UserRole ,為什么要使用joinTable ,但是該類更難以查詢,並且即使我只需要User ,我也擔心為每個找到的User映射Role開銷。
  2. 有兩個查詢,只有第二個可以分頁。

因此,我的問題是:是否有一種更好的方式來構造一個查詢來獲取不包含某些角色的用戶(而不將數據庫重組為金字塔式角色系統,其中每個用戶只有一個角色)?

兩個查詢絕對必要嗎? 我試圖構造一個純SQL查詢,沒有子查詢我就做不到。

如果您的UserRole具有用戶和角色屬性,而不是belongsTo ,則如下所示:

class UserRole implements Serializable {

    private static final long serialVersionUID = 1

    User user
    Role role
    ...
}

然后,您可以執行以下操作:

def rolesToIgnore = ["ROLE_ADMIN"]

def userIdsWithGivenRoles = UserRole.where {
    role.authority in rolesToIgnore
}.list().collect { it.user.id }.unique()

def userIdsWithoutGivenRoles = UserRole.where {
    !(role.authority in rolesToIgnore)
}.list().collect { it.user.id }.unique()

我很討厭投影,所以我用unique()刪除了重復項。

SQL等效項是:

SELECT DISTINCT ur.user_id
FROM    user_role AS ur INNER JOIN role AS r
        ON ur.authority_id = r.id
WHERE   r.authority IN ('ROLE_ADMIN');

SELECT DISTINCT ur.user_id
FROM    user_role AS ur INNER JOIN role AS r
        ON ur.authority_id = r.id
WHERE   r.authority NOT IN ('ROLE_ADMIN');

您可以執行類似的操作:

return UserRole.createCriteria().list {
    distinct('user')
    user {
        ne("enabled", false)
    }
    or {
        user {
            eq('id', springSecurityService.currentUser.id)
        }
        role {
            not {
                'in'('authority', ['ADMIN', 'EXECUTIVE'])
            }
        }
    }
}

使用distinct('user')您只會獲得Users

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM