cn.zhxu.bp.auth.Scope Maven / Gradle / Ivy
The newest version!
package cn.zhxu.bp.auth;
import cn.zhxu.data.Mapper;
import cn.zhxu.bp.enums.ScopeType;
import cn.zhxu.bp.utils.StringUtils;
import lombok.Getter;
import lombok.ToString;
import java.util.*;
import java.util.stream.Collectors;
/**
* 数据权限
* @author Troy.Zhou @ 2022/8/23
*/
@Getter
@ToString
public class Scope {
/** 类型 */
private final ScopeType type;
/** 组 ID 列表 */
private final String groupIds;
public Scope(ScopeType type) {
this(type, "-1");
}
public Scope(ScopeType type, List groupIds) {
this(type, StringUtils.join(groupIds.toArray(), ","));
}
public Scope(ScopeType type, String groupIds) {
this.type = type;
if (StringUtils.isBlank(groupIds)) {
this.groupIds = "-1";
} else {
this.groupIds = groupIds;
}
}
public List groupIdList() {
if (groupIds == null) {
return Collections.emptyList();
}
return Arrays.stream(groupIds.split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
}
public boolean isEmptyGroup() {
return StringUtils.isBlank(groupIds) || groupIds.trim().equals("-1");
}
/**
* 是否包含某个组的数据权限
* @param groupId 指定的组
*/
public boolean scoped(int groupId) {
if (type == ScopeType.ALL) {
return true;
}
if (type == ScopeType.ONLY_SELF) {
return false;
}
return groupIdList().contains(groupId);
}
static final String TYPE = "t";
static final String GROUP_IDS = "g";
public static Scope parse(Mapper mapper) {
if (mapper == null) {
return null;
}
ScopeType type = ScopeType.from(mapper.getInt(TYPE));
if (type == null) {
return null;
}
String groupIds = mapper.getString(GROUP_IDS);
return new Scope(type, groupIds);
}
public Map toMap() {
Map map = new HashMap<>();
map.put(TYPE, type.value());
map.put(GROUP_IDS, groupIds);
return map;
}
}