使用Grails spring security REST(本身使用Grails Spring Security Core)我已经生成了User
,Role
,UserRole
类。
用户:
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_USER
个角色,因此不具备ROLE_ADMIN
角色。
从上面的代码中可以看出,我已经修改了默认生成的代码并将joinTable
添加到User
类而不是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
似乎&#34; icky&#34;对我来说。为什么在我已经为此目的使用特定类joinTable
时使用UserRole
,但是该类更难以查询,并且我担心映射Role
可能带来的开销每个人都找到了User
,即使我只需要User
。所以我的问题是: 是否有更优化的方法来构建查询以获取不包含某些角色的用户(不将数据库重组为金字塔角色系统,其中每个用户只有一个角色)?
绝对需要两个查询吗?我试图构建一个纯SQL查询,如果没有子查询,我就无法做到这一点。
答案 0 :(得分:0)
如果您的 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');
答案 1 :(得分:0)
你可以做类似的事情:
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