Grails Spring Security 查询没有特定角色的用户

Posted

技术标签:

【中文标题】Grails Spring Security 查询没有特定角色的用户【英文标题】:Grails Spring Security querying users which don't have a certain role 【发布时间】:2015-11-01 10:28:42 【问题描述】:

使用Grails spring security REST(它本身使用Grails Spring Security Core)我生成了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
    

用户角色:

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 不在前一个列表中的用户。

这可行并且是可分页的,但是它困扰我有两个原因:

    用户上的joinTable 对我来说似乎“恶心”。为什么要使用joinTable 当我已经有一个特定的类用于该目的UserRole,但是该类更难查询,我担心为每个找到的Role 映射Role 可能的开销@ 987654341@ 即使我只需要User。 两个查询,只能分页第二个。

所以我的问题是: 是否有更优化的方法来构造查询以获取不包含某些角色的用户(无需将数据库重组为每个用户只有一个角色的金字塔角色系统)?

两个查询是绝对必要的吗?我试图构建一个纯 SQL 查询,但如果没有子查询,我就无法做到。

【问题讨论】:

【参考方案1】:

你可以这样做:

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

【讨论】:

【参考方案2】:

如果你的 UserRoleuser 和角色 properties 而不是 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');

【讨论】:

以上是关于Grails Spring Security 查询没有特定角色的用户的主要内容,如果未能解决你的问题,请参考以下文章

Grails - grails-spring-security-rest - 无法从 application.yml 加载 jwt 机密

grails-spring-security-rest 插件和悲观锁定

Grails + spring-security-core:用户登录后如何分配角色?

Grails Spring Security注释问题

Grails spring-security-oauth-google:如何设置

Grails Spring Security 插件网址