繁体   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