com.github.houbb.privilege.proxy.bs.PrivilegeProxyBs Maven / Gradle / Ivy
package com.github.houbb.privilege.proxy.bs;
import com.github.houbb.heaven.support.handler.IHandler;
import com.github.houbb.heaven.util.common.ArgUtil;
import com.github.houbb.heaven.util.lang.ObjectUtil;
import com.github.houbb.heaven.util.util.CollectionUtil;
import com.github.houbb.privilege.api.annotation.PrivilegeAcquire;
import com.github.houbb.privilege.api.api.IPrivilegeAcquire;
import com.github.houbb.privilege.api.api.IPrivilegeInfo;
import com.github.houbb.privilege.api.api.IPrivilegeOwn;
import com.github.houbb.privilege.api.exception.PrivilegeRuntimeException;
import com.github.houbb.privilege.core.bs.PrivilegeBs;
import com.github.houbb.privilege.proxy.support.acquire.PrivilegeAcquireAnnotation;
import com.github.houbb.privilege.proxy.support.context.IPrivilegeProxyContext;
import com.github.houbb.privilege.proxy.support.own.PrivilegeOwnSubject;
import java.util.List;
/**
* 代理引导类
* @author binbin.hou
* @since 0.0.4
*/
public final class PrivilegeProxyBs {
private PrivilegeProxyBs(){}
/**
* 上下文
* @since 0.0.4
*/
private IPrivilegeProxyContext context;
/**
* 新建对象实例
* @return 实例
* @since 0.0.4
*/
public static PrivilegeProxyBs newInstance() {
return new PrivilegeProxyBs();
}
public PrivilegeProxyBs context(IPrivilegeProxyContext context) {
ArgUtil.notNull(context, "context");
this.context = context;
return this;
}
/**
* 权限 check
*
* 1. 没有注解,直接返回
* 2. 有注解才进行校验
*
* @return 结果
* @since 0.0.4
*/
public Object privilege() throws Throwable {
//1. 注解
PrivilegeAcquire privilege = context.acquire();
if(ObjectUtil.isNull(privilege)) {
return context.process();
}
//2. 处理
IPrivilegeAcquire acquire = new PrivilegeAcquireAnnotation(privilege);
IPrivilegeOwn own = new PrivilegeOwnSubject();
//2.1 校验是否拥有权限
boolean hasPrivilege = PrivilegeBs.newInstance()
.acquire(acquire)
.own(own)
.hasPrivilege();
//2.2 抛出异常,后期考虑添加 message 等信息
if(!hasPrivilege) {
List acquireCodes = CollectionUtil.toList(acquire.acquirePrivilege(),
new IHandler() {
@Override
public String handle(IPrivilegeInfo iPrivilegeInfo) {
return iPrivilegeInfo.code();
}
});
List ownCodes = CollectionUtil.toList(own.ownPrivilege(),
new IHandler() {
@Override
public String handle(IPrivilegeInfo iPrivilegeInfo) {
return iPrivilegeInfo.code();
}
});
String tips = String.format("Has no privilege! Acquire: <%s>, Own: <%s>",
acquireCodes, ownCodes);
throw new PrivilegeRuntimeException(tips);
}
//3. 正常执行
return context.process();
}
}