提交 c0024bd4 编写于 作者: sq3536's avatar sq3536

合并dev2开发分支

上级 7fe90329
......@@ -31,9 +31,11 @@ TARGET=PSSYSAPP
</#if>
</dependencies>
<#if pub.getPSDeployCenter()?? && pub.getPSDeployCenter().getPSRegistryRepo()??>
<properties>
<docker.image.prefix>registry.cn-shanghai.aliyuncs.com/ibizsys</docker.image.prefix>
<docker.image.prefix>${pub.getPSDeployCenter().getPSRegistryRepo().getConnStr()}</docker.image.prefix>
</properties>
</#if>
<profiles>
......@@ -107,7 +109,8 @@ TARGET=PSSYSAPP
</execution>
</executions>
</plugin>
<#if pub.getPSDeployCenter()?? && pub.getPSDeployCenter().getPSRegistryRepo()??>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
......@@ -125,6 +128,7 @@ TARGET=PSSYSAPP
</resources>
</configuration>
</plugin>
</#if>
</plugins>
</build>
</profile>
......
......@@ -17,6 +17,10 @@ services:
- "${httpPort}:${httpPort}"
networks:
- agent_network
<#if sysrun?? && sysrun.getPSDevSlnMSDepApp()?? && sysrun.getPSDevSlnMSDepApp().getPSDCMSPlatformNode()?? && sysrun.getPSDevSlnMSDepApp().getPSDCMSPlatformNode().getSSHIPAddr()??>
environment:
SPRING_CLOUD_NACOS_DISCOVERY_IP: ${sysrun.getPSDevSlnMSDepApp().getPSDCMSPlatformNode().getSSHIPAddr()}
</#if>
deploy:
mode: replicated
replicas: 1
......
......@@ -14,6 +14,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
@Slf4j
@Import({
......@@ -28,9 +31,15 @@ import org.springframework.boot.SpringApplication;
@SpringBootApplication(exclude = {
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class,
})
public class ${app.getPKGCodeName()}Application{
public class ${app.getPKGCodeName()}Application extends WebMvcConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(${app.getPKGCodeName()}Application.class,args);
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
super.addArgumentResolvers(argumentResolvers);
argumentResolvers.add(new ${pub.getPKGCodeName()}.util.web.SearchContextHandlerMethodArgumentResolver());
}
}
......@@ -44,6 +44,15 @@ public class ${app.getPKGCodeName()}SecurityConfig extends WebSecurityConfigurer
@Value("${r'${ibiz.auth.path:v7/login}"'})
private String loginPath;
@Value("${r'${ibiz.file.uploadpath:ibizutil/upload}"'})
private String uploadpath;
@Value("${r'${ibiz.file.downloadpath:ibizutil/download}"'})
private String downloadpath;
@Value("${r'${ibiz.file.previewpath:ibizutil/preview}"'})
private String previewpath;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
......@@ -100,6 +109,10 @@ public class ${app.getPKGCodeName()}SecurityConfig extends WebSecurityConfigurer
).permitAll()
//放行登录请求
.antMatchers( HttpMethod.POST,"/"+loginPath).permitAll()
// 文件操作
.antMatchers("/"+downloadpath+"/**").permitAll()
.antMatchers("/"+uploadpath).permitAll()
.antMatchers("/"+previewpath+"/**").permitAll()
// 所有请求都需要认证
.anyRequest().authenticated()
// 防止iframe 造成跨域
......
......@@ -16,12 +16,16 @@ server:
#zuul网关路由设置
zuul:
routes:
<#assign haswfentity=false>
<#list item.getAllPSAppDataEntities() as appDataEntity>
<#assign serviceId="">
<#assign serviceUrl=srfpluralize(appDataEntity.codeName?lower_case)>
<#assign appEntity=appDataEntity.name?lower_case>
<#assign psDataEntity=appDataEntity.getPSDataEntity()>
<#assign systemName=sys.getCodeName()?lower_case>
<#if psDataEntity.hasPSDEWF()??>
<#assign haswfentity=true>
</#if>
<#if psDataEntity.getStorageMode()==4>
<#comment>serviceApi模式</#comment>
<#assign serviceId=(psDataEntity.getPSSubSysServiceAPI().getServiceCodeName())!''>
......@@ -36,6 +40,12 @@ zuul:
serviceId: ${serviceId}
stripPrefix: false
</#list>
<#if haswfentity==true>
wfcore:
path: /wfcore/**
serviceId: ibzwf-api
stripPrefix: false
</#if>
<#comment>通过设置该参数,避免Zuul转发请求时丢失Authorization请求头信息</#comment>
sensitive-headers:
- Cookie,Set-Cookie,Authorization
......
......@@ -10,6 +10,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
@Slf4j
@EnableDiscoveryClient
......@@ -17,9 +20,15 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableTransactionManagement
@SpringBootApplication
@EnableFeignClients(basePackages = {"${pub.getPKGCodeName()}" })
public class DevBootApplication{
public class DevBootApplication extends WebMvcConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(DevBootApplication.class,args);
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
super.addArgumentResolvers(argumentResolvers);
argumentResolvers.add(new ${pub.getPKGCodeName()}.util.web.SearchContextHandlerMethodArgumentResolver());
}
}
......@@ -43,6 +43,15 @@ public class DevBootSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${r'${ibiz.auth.path:v7/login}"'})
private String loginPath;
@Value("${r'${ibiz.file.uploadpath:ibizutil/upload}"'})
private String uploadpath;
@Value("${r'${ibiz.file.downloadpath:ibizutil/download}"'})
private String downloadpath;
@Value("${r'${ibiz.file.previewpath:ibizutil/preview}"'})
private String previewpath;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
......@@ -95,6 +104,10 @@ public class DevBootSecurityConfig extends WebSecurityConfigurerAdapter {
).permitAll()
//放行登录请求
.antMatchers( HttpMethod.POST,"/"+loginPath).permitAll()
// 文件操作
.antMatchers("/"+downloadpath+"/**").permitAll()
.antMatchers("/"+uploadpath).permitAll()
.antMatchers("/"+previewpath+"/**").permitAll()
.anyRequest().authenticated()
// 防止iframe 造成跨域
.and().headers().frameOptions().disable();
......
......@@ -10,4 +10,39 @@ TARGET=PSSYSTEM
</#if>
</#if>
server:
port: ${httpPort}
\ No newline at end of file
port: ${httpPort}
<#if item.getAllPSAppDataEntities?? && app.getAllPSAppDataEntities()??>
#zuul网关路由设置
zuul:
routes:
<#assign haswfentity=false>
<#list item.getAllPSAppDataEntities() as appDataEntity>
<#assign serviceId="">
<#assign serviceUrl=srfpluralize(appDataEntity.codeName?lower_case)>
<#assign appEntity=appDataEntity.name?lower_case>
<#assign psDataEntity=appDataEntity.getPSDataEntity()>
<#assign systemName=sys.getCodeName()?lower_case>
<#if psDataEntity.hasPSDEWF()??>
<#assign haswfentity=true>
</#if>
<#if psDataEntity.getStorageMode()==4>
<#comment>serviceApi模式</#comment>
<#assign serviceId=(psDataEntity.getPSSubSysServiceAPI().getServiceCodeName())!''>
<#assign serviceUrl=srfpluralize(appDataEntity.name?lower_case)>
${appEntity}:
path: /${serviceUrl}/**
serviceId: ${serviceId}
stripPrefix: false
</#if>
</#list>
<#if haswfentity==true>
wfcore:
path: /wfcore/**
serviceId: ibzwf-api
stripPrefix: false
</#if>
<#comment>通过设置该参数,避免Zuul转发请求时丢失Authorization请求头信息</#comment>
sensitive-headers:
- Cookie,Set-Cookie,Authorization
</#if>
\ No newline at end of file
......@@ -50,7 +50,7 @@ import com.alibaba.fastjson.JSONObject;
* 实体[${item.getLogicName()}] 服务对象接口实现
*/
@Slf4j
@Service
@Service("${item.getCodeName()}ServiceImpl")
public class ${item.getCodeName()}ServiceImpl extends ServiceImpl<${de.getCodeName()}Mapper, ${de.getCodeName()}> implements I${de.getCodeName()}Service {
<#assign keyfield=de.getKeyPSDEField()>
......
......@@ -2,8 +2,10 @@
TARGET=PSSYSTEM
</#ibiztemplate>
<#if sys.getAllPSApps()??>
{
"predefineddatarange":[{"id":"ALL","name":"全部数据"},{"id":"CURORG","name":"当前单位"},{"id":"PORG","name":"上级单位"},{"id":"SORG","name":"下级单位"},{"id":"CURORGDEPT","name":"当前部门"},{"id":"PORGDEPT","name":"上级部门"},{"id":"SORGDEPT","name":"下级部门"}],
<#assign ct=0>
[
"entities":[
<#list sys.getAllPSApps() as app>
<#if app.getAllPSAppDataEntities?? && app.getAllPSAppDataEntities()??>
<#list app.getAllPSAppDataEntities() as appde><#comment>由于平台暂未开放获取实体操作标识的方法,所以暂时写死</#comment>
......@@ -11,18 +13,51 @@ TARGET=PSSYSTEM
<#if !P.exists(de.getCodeName(),"")>
<#if (ct>0)>
,</#if><#assign ct=ct+1>
<#assign dataSetResult=getDataSet()>
<#assign deActionResult=getDEAction()>
{
"dename":"${de.codeName}",
"delogicname":"${de.logicName}",
"sysmoudle":{"id":"${de.getPSSystemModule().codeName?upper_case}","name":"${de.getPSSystemModule().name}"},
"dedataset":[{"id":"Default","name":"默认数据集"}],
"dedatarange":[{"id":"ALL","name":"全部数据"},{"id":"CURORG","name":"当前单位"},{"id":"PORG","name":"上级单位"},{"id":"SORG","name":"下级单位"},{"id":"CURORGDEPT","name":"当前部门"},{"id":"PORGDEPT","name":"上级部门"},{"id":"SORGDEPT","name":"下级部门"}],
"deprivs":[{"id":"READ","name":"READ"},{"id":"CREATE","name":"CREATE"},{"id":"UPDATE","name":"UPDATE"},{"id":"DELETE","name":"DELETE"}]
"dedataset":${dataSetResult},
"deaction":${deActionResult}
}
</#if>
</#list>
</#if>
</#list>
]
}
</#if>
<#comment>获取实体数据集</#comment>
<#function getDataSet>
<#assign result="[" >
<#if de.getAllPSDEDataSets()??>
<#list de.getAllPSDEDataSets() as dataSet>
<#if dataSet_index gt 0><#assign result=result+","></#if>
<#assign dataSetLogicName="">
<#if dataSet.getLogicName()?? && dataSet.getLogicName()!=''><#assign dataSetLogicName=dataSet.getLogicName()><#else><#assign dataSetLogicName=dataSet.codeName></#if>
<#assign result=result+"{\"id\":\""+dataSet.codeName+"\" , \"name\":\""+dataSetLogicName+"\"}">
</#list>
</#if>
<#assign result=result+"]" >
<#return result>
</#function>
<#comment>获取实体行为</#comment>
<#function getDEAction>
<#assign result="[" >
<#if de.getAllPSDEActions()??>
<#list de.getAllPSDEActions() as deAction>
<#if deAction_index gt 0><#assign result=result+","></#if>
<#assign deActionLogicName="">
<#if deAction.getLogicName()?? && deAction.getLogicName()!=''><#assign deActionLogicName=deAction.getLogicName()><#else><#assign deActionLogicName=deAction.codeName></#if>
<#assign result=result+"{\"id\":\""+deAction.codeName+"\" , \"name\":\""+deActionLogicName+"\" , \"type\":\""+deAction.getActionType()+"\" }">
</#list>
</#if>
<#assign result=result+"]" >
<#return result>
</#function>
......@@ -185,11 +185,13 @@ TARGET=PSDATAENTITY
</mapper>
</#if>
<#comment>上下文参数转换</#comment>
<#comment>上下文参数转换 原字符串:${srfdatacontext('field','{"defname":"PORGNAME","dename":"IBZORG"}')})</#comment>
<#comment>第一次替换:#{srf.datacontext.field','{"defname":"PORGNAME","dename":"IBZORG"}')})</#comment>
<#comment>第二次替换:#{srf.datacontext.field}</#comment>
<#function contextParamConvert contextParam>
<#assign resultParam="">
<#assign resultParam=contextParam?replace('$\{srfdatacontext(\'','#\{srf.datacontext.')?replace("','\\{[\\S]*","\\}","r")><#comment>数据上下文</#comment>
<#assign resultParam=resultParam?replace('$\{srfsessioncontext(\'','#\{srf.sessioncontext.')?replace("','\\{[\\S]*","\\}","r")><#comment>用户上下文</#comment>
<#assign resultParam=resultParam?replace('$\{srfwebcontext(\'','#\{srf.webcontext.')?replace("','\\{[\\S]*","\\}","r")><#comment>网页请求上下文</#comment>
<#assign resultParam=contextParam?replace('$\{srfdatacontext(\'','#\{srf.datacontext.')?replace("','\\{[\\S]*}'\\)}","\\}","r")><#comment>数据上下文</#comment>
<#assign resultParam=resultParam?replace('$\{srfsessioncontext(\'','#\{srf.sessioncontext.')?replace("','\\{[\\S]*}'\\)}","\\}","r")><#comment>用户上下文</#comment>
<#assign resultParam=resultParam?replace('$\{srfwebcontext(\'','#\{srf.webcontext.')?replace("','\\{[\\S]*}'\\)}","\\}","r")><#comment>网页请求上下文</#comment>
<#return resultParam>
</#function>
......@@ -34,9 +34,11 @@ TARGET=PSSYSSERVICEAPI
</dependency>
</dependencies>
<#if pub.getPSDeployCenter()?? && pub.getPSDeployCenter().getPSRegistryRepo()??>
<properties>
<docker.image.prefix>registry.cn-shanghai.aliyuncs.com/ibizsys</docker.image.prefix>
<docker.image.prefix>${pub.getPSDeployCenter().getPSRegistryRepo().getConnStr()}</docker.image.prefix>
</properties>
</#if>
<profiles>
<profile>
......@@ -69,6 +71,8 @@ TARGET=PSSYSSERVICEAPI
</execution>
</executions>
</plugin>
<#if pub.getPSDeployCenter()?? && pub.getPSDeployCenter().getPSRegistryRepo()??>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
......@@ -86,6 +90,7 @@ TARGET=PSSYSSERVICEAPI
</resources>
</configuration>
</plugin>
</#if>
</plugins>
</build>
</profile>
......
......@@ -17,6 +17,10 @@ services:
- "${httpPort}:${httpPort}"
networks:
- agent_network
<#if sysrun?? && sysrun.getPSDevSlnMSDepAPI()?? && sysrun.getPSDevSlnMSDepAPI().getPSDCMSPlatformNode()?? && sysrun.getPSDevSlnMSDepAPI().getPSDCMSPlatformNode().getSSHIPAddr()??>
environment:
SPRING_CLOUD_NACOS_DISCOVERY_IP: ${sysrun.getPSDevSlnMSDepAPI().getPSDCMSPlatformNode().getSSHIPAddr()}
</#if>
deploy:
mode: replicated
replicas: 1
......
......@@ -12,6 +12,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
@Slf4j
@EnableDiscoveryClient
......@@ -23,9 +26,15 @@ import org.mybatis.spring.annotation.MapperScan;
@SpringBootApplication(exclude = {
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class,
})
public class ${sys.codeName}${item.codeName}Application{
public class ${sys.codeName}${item.codeName}Application extends WebMvcConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(${sys.codeName}${item.codeName}Application.class, args);
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
super.addArgumentResolvers(argumentResolvers);
argumentResolvers.add(new ${pub.getPKGCodeName()}.util.web.SearchContextHandlerMethodArgumentResolver());
}
}
......@@ -17,6 +17,8 @@ TARGET=PSDESERVICEAPI
<#assign itemSysApiCodeName = item.getPSSysServiceAPI().getCodeName()>
<#assign itemSysApiCodeNameLC = item.getPSSysServiceAPI().getCodeName()?lower_case>
<#assign keyCNLC = "_id">
<#assign deStorageMode="None">
<#if de.getStorageMode()==1><#assign deStorageMode="Sql"><#elseif de.getStorageMode()==2><#assign deStorageMode="NoSQL"><#elseif de.getStorageMode()==4><#assign deStorageMode="ServiceApi"></#if>
package ${pubPkgCodeName}.${itemSysApiCodeNameLC}.rest;
import java.sql.Timestamp;
......@@ -147,7 +149,7 @@ public class ${itemCodeName}Resource {
<#if deaction.codeName?lower_case == 'create'>
@PreAuthorize("hasPermission('','CREATE',this.getEntity())")
@PreAuthorize("hasPermission('','Create',{this.getEntity(),'${deStorageMode}'})")
@ApiOperation(value = "${deaction.getLogicName()}", tags = {"${itemCodeName}" }, notes = "${deaction.getLogicName()}")
@RequestMapping(method = RequestMethod.POST, value = "${fullPath}")
<#if de.getStorageMode()==4><#else> @Transactional</#if>
......@@ -158,7 +160,7 @@ public class ${itemCodeName}Resource {
return ResponseEntity.status(HttpStatus.OK).body(dto);
}
@PreAuthorize("hasPermission('','CREATE',this.getEntity())")
@PreAuthorize("hasPermission('','Create',{this.getEntity(),'${deStorageMode}'})")
@ApiOperation(value = "createBatch", tags = {"createBatch" }, notes = "createBatch")
@RequestMapping(method = RequestMethod.POST, value = "${fullPath}/createbatch")
public ResponseEntity<Boolean> createBatch(${etParamsList}) {
......@@ -167,7 +169,7 @@ public class ${itemCodeName}Resource {
}
<#elseif deaction.codeName?lower_case == 'update'>
@PreAuthorize("hasPermission(#${itemCodeNameLC + keyCNLC},'UPDATE',this.getEntity())")
@PreAuthorize("hasPermission(#${itemCodeNameLC + keyCNLC},'Update',{this.getEntity(),'${deStorageMode}'})")
@ApiOperation(value = "${deaction.getLogicName()}", tags = {"${itemCodeName}" }, notes = "${deaction.getLogicName()}")
@RequestMapping(method = RequestMethod.PUT, value = "${fullPath}/{${itemCodeNameLC + keyCNLC}}")
<#if de.getStorageMode()==4><#else> @Transactional</#if>
......@@ -179,7 +181,7 @@ public class ${itemCodeName}Resource {
return ResponseEntity.status(HttpStatus.OK).body(dto);
}
@PreAuthorize("hasPermission(#${itemCodeNameLC + keyCNLC},'UPDATE',this.getEntity())")
@PreAuthorize("hasPermission(#${itemCodeNameLC + keyCNLC},'Update',{this.getEntity(),'${deStorageMode}'})")
@ApiOperation(value = "UpdateBatch", tags = {"UpdateBatch" }, notes = "UpdateBatch")
@RequestMapping(method = RequestMethod.POST, value = "${fullPath}/updatebatch")
public ResponseEntity<Boolean> updateBatch(${etParamsList}) {
......@@ -202,7 +204,7 @@ public class ${itemCodeName}Resource {
}
<#elseif deaction.codeName?lower_case == 'remove'>
@PreAuthorize("hasPermission('DELETE',{#${itemCodeNameLC + keyCNLC},this.getEntity()})")
@PreAuthorize("hasPermission('Remove',{#${itemCodeNameLC + keyCNLC},{this.getEntity(),'${deStorageMode}'}})")
@ApiOperation(value = "${deaction.getLogicName()}", tags = {"${itemCodeName}" }, notes = "${deaction.getLogicName()}")
@RequestMapping(method = RequestMethod.DELETE, value = "${fullPath}/{${itemCodeNameLC + keyCNLC}}")
<#if de.getStorageMode()==4><#else> @Transactional</#if>
......@@ -218,7 +220,7 @@ public class ${itemCodeName}Resource {
}
<#elseif deaction.codeName?lower_case == 'get'>
@PreAuthorize("hasPermission(#${itemCodeNameLC + keyCNLC},'READ',this.getEntity())")
@PreAuthorize("hasPermission(#${itemCodeNameLC + keyCNLC},'Get',{this.getEntity(),'${deStorageMode}'})")
@ApiOperation(value = "${deaction.getLogicName()}", tags = {"${itemCodeName}" }, notes = "${deaction.getLogicName()}")
@RequestMapping(method = RequestMethod.GET, value = "${fullPath}/{${itemCodeNameLC + keyCNLC}}")
public ResponseEntity<${itemCodeName}DTO> get(${idParams}) {
......@@ -261,7 +263,7 @@ public class ${itemCodeName}Resource {
</#if>
<#elseif apiMethod.getActionType()=='FETCH'>
<#assign deds = apiMethod.getPSDEDataSet()>
@PreAuthorize("hasPermission('READ',{#context,'${deds.getCodeName()}',this.getEntity()})")
@PreAuthorize("hasPermission('Get',{#context,'${deds.getCodeName()}',this.getEntity(),'${deStorageMode}'})")
@ApiOperation(value = "fetch${deds.getLogicName()}", tags = {"${itemCodeName}" } ,notes = "fetch${deds.getLogicName()}")
@RequestMapping(method= RequestMethod.${reqMtd} , value="${fullPath}/fetch<#if (deds.getName()=='DEFAULT')>${deds.getCodeName()?lower_case}<#else>${deds.getCodeName()?lower_case}</#if>")
public ResponseEntity<List<${itemCodeName}DTO>> fetch<#if (deds.getName()=='DEFAULT')>${deds.getCodeName()}<#else>${deds.getCodeName()}</#if>(${deCodeName}SearchContext context) {
......@@ -275,7 +277,7 @@ public class ${itemCodeName}Resource {
.body(list);
}
@PreAuthorize("hasPermission('READ',{#context,'${deds.getCodeName()}',this.getEntity()})")
@PreAuthorize("hasPermission('Get',{#context,'${deds.getCodeName()}',this.getEntity(),'${deStorageMode}'})")
@ApiOperation(value = "search${deds.getLogicName()}", tags = {"${itemCodeName}" } ,notes = "search${deds.getLogicName()}")
@RequestMapping(method= RequestMethod.${reqMtd} , value="${fullPath}/search<#if (deds.getName()=='DEFAULT')>${deds.getCodeName()?lower_case}<#else>${deds.getCodeName()?lower_case}</#if>")
public ResponseEntity<Page<${itemCodeName}DTO>> search<#if (deds.getName()=='DEFAULT')>${deds.getCodeName()}<#else>${deds.getCodeName()}</#if>(${deCodeName}SearchContext context) {
......
......@@ -17,6 +17,8 @@ public class FileItem
{
private String id;
private String name;
private String fileid;
private String filename;
private long size;
private String ext;
}
......@@ -3,6 +3,7 @@ TARGET=PSSYSTEM
</#ibiztemplate>
package ${pub.getPKGCodeName()}.util.filter;
import ${pub.getPKGCodeName()}.util.security.AuthenticationUser;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonProperty;
......@@ -109,16 +110,11 @@ public class SearchContextBase implements ISearchContext{
}
/**
* 用户上下文参数
*/
Map<String,Object> sessionparams = new HashMap<String,Object>() ;
/**
* 获取用户上下文
* @return
*/
* 获取用户上下文
* @return
*/
public Map<String,Object> getSessioncontext() {
return sessionparams;
return AuthenticationUser.getAuthenticationUser().getSessionParams();
}
@JsonAnyGetter
......
......@@ -44,14 +44,13 @@ public class PermissionSyncJob implements ApplicationRunner {
private String systemId;
@Override
public void run(ApplicationArguments args) throws Exception {
public void run(ApplicationArguments args) {
if(enablePermissionValid){
try {
InputStream permission= this.getClass().getResourceAsStream("/deprivs/DEPrivs.json"); //获取当前系统所有实体资源能力
String permissionResult = IOUtils.toString(permission,"UTF-8");
JSONArray jsonNodePermission = JSONArray.parseArray(permissionResult);
Map<String,Object> map=new HashMap<String,Object>();
map.put("menu",new JSONArray());
JSONObject jsonNodePermission = JSONObject.parseObject(permissionResult);
Map<String,Object> map=new HashMap<>();
map.put("permission",jsonNodePermission);
client.pushSystemPermissionData(map,systemId);
}
......
......@@ -17,21 +17,20 @@ import java.io.*;
@Slf4j
@RestController
@RequestMapping("/")
public class FileController
{
@Autowired
private FileService fileService;
@PostMapping(value = "${r'${ibiz.uploadpath.path:ibizutil/upload}'}")
@PostMapping(value = "${r'${ibiz.file.uploadpath:ibizutil/upload}'}")
public ResponseEntity<FileItem> upload(@RequestParam("file") MultipartFile multipartFile){
return ResponseEntity.ok().body(fileService.saveFile(multipartFile));
}
private final String defaultdownloadpath="ibizutil/download/{id}";
protected String getDefaultdownloadpath(){
return defaultdownloadpath;
}
@GetMapping(value = "${r'${ibiz.file.downloadpath:"+defaultdownloadpath+"}'}")
@ResponseStatus(HttpStatus.OK)
......
......@@ -7,14 +7,30 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.QueryBuilder;
import ${pub.getPKGCodeName()}.util.annotation.DEField;
import ${pub.getPKGCodeName()}.util.domain.EntityBase;
import ${pub.getPKGCodeName()}.util.enums.DEPredefinedFieldType;
import ${pub.getPKGCodeName()}.util.filter.QueryBuildContext;
import ${pub.getPKGCodeName()}.util.filter.QueryWrapperContext;
import ${pub.getPKGCodeName()}.util.helper.DEFieldCacheMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import javax.swing.text.html.parser.Entity;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
......@@ -29,273 +45,455 @@ public class AuthPermissionEvaluator implements PermissionEvaluator {
@Value("${r'${ibiz.enablePermissionValid:false}'}")
boolean enablePermissionValid; //是否开启权限校验
/**
* 实体行为操作标识
*/
private String DEActionType="DEACTION";
/**
* 实体数据集操作标识
*/
private String DataSetTag="DATASET";
/**
*实体主键标识
*/
private String keyFieldTag="keyfield";
@Resource
private MongoTemplate mongoTemplate;
/**
* 表格权限检查 :用于检查当前用户是否拥有表格数据的读取、删除权限
*
* @param authentication
* @param obj_action 表格行为,如:[READ,DELETE]
* @param grid_param 表格参数,如:当前表格所处实体(EntityName)、表格删除的数据主键(srfkeys)
* @param deAction 表格行为,如:[READ,DELETE]
* @param gridParam 表格参数,如:当前表格所处实体(EntityName)、表格删除的数据主键(srfkeys)
* @return true/false true则允许当前行为,false拒绝行为
*/
@Override
public boolean hasPermission(Authentication authentication, Object obj_action, Object grid_param) {
public boolean hasPermission(Authentication authentication, Object deAction, Object gridParam) {
//未开启权限校验、超级管理员则不进行权限检查
if(AuthenticationUser.getAuthenticationUser().getSuperuser()==1 || !enablePermissionValid)
return true; //系统没开启权限、超级管理员 两种情况不进行权限检查
return true;
try{
String action = "";
String action = "";
String deStorageMode;
if (deAction instanceof String)
action = (String) deAction;
if (obj_action instanceof String)
action = (String) obj_action;
if (StringUtils.isEmpty(action))
return false;
if (StringUtils.isEmpty(action))
return false;
//获取当前用户权限列表
JSONObject userPermission= AuthenticationUser.getAuthenticationUser().getPermisionList();
JSONObject permissionList= AuthenticationUser.getAuthenticationUser().getPermisionList();//获取权限列表
if(userPermission==null)
return false;
if(permissionList==null)
return false;
List gridParamList = (ArrayList) gridParam;
if(action.equalsIgnoreCase("remove")){
//准备参数
Object srfKey =gridParamList.get(0);
EntityBase entity = (EntityBase) gridParamList.get(1);
deStorageMode= (String) gridParamList.get(2);
String entityName = entity.getClass().getSimpleName();
//获取实体行为权限信息
JSONObject permissionList=userPermission.getJSONObject("userPermissionList");
List param_list = (ArrayList) grid_param;
if(obj_action.equals("DELETE")){ //表格删除权限校验
Object srfkey =param_list.get(0);
EntityBase cur_entity = (EntityBase) param_list.get(1);
String entityName = cur_entity.getClass().getSimpleName();
ServiceImpl service= SpringContextHolder.getBean(String.format("%s%s",getBeanName(entityName),"ServiceImpl"));//获取当前实体service
JSONObject formDataAbility=permissionList.getJSONObject("dataAbility-form");//由于表格删除是不跟着dataSet走,所以此处走form获取权限
Map<String,String> permissionField=getPermissionField(cur_entity);//获取系统预置属性列表
String selectCond=generatePermissionSQLForm(formDataAbility,entityName,action,srfkey,permissionField);//拼接权限条件
if(StringUtils.isEmpty(selectCond))
return false;
QueryWrapper permissionCond=getPermissionCond(selectCond,permissionField);
return testDataAccess(service,permissionCond);//执行权限检查
//检查是否有操作权限[create.update.delete.read]
if(!validDEActionHasPermission(permissionList,entityName,action)){
return false;
}
else{ //表格查询权限校验
Object searchContext=param_list.get(0);
String dataSet=String.valueOf(param_list.get(1));
EntityBase cur_entity = (EntityBase) param_list.get(2);
String entityName = cur_entity.getClass().getSimpleName();
if(StringUtils.isEmpty(entityName)|| StringUtils.isEmpty(dataSet)|| StringUtils.isEmpty(action))
return false;
JSONObject gridDataAbility=permissionList.getJSONObject("dataAbility-grid");//获取表格的权限数据
Map<String,String> permissionField=getPermissionField(cur_entity);//获取系统预置属性列表
String selectCond=generatePermissionSQLGrid(gridDataAbility,entityName,action,dataSet,permissionField,null);//拼接权限条件
if(StringUtils.isEmpty(selectCond))
return false;
filterDataAccess(searchContext,selectCond);//过滤出权限内的数据
//检查是否有数据权限
return deActionPermissionValidRouter(deStorageMode, entity , action , srfKey, permissionList);
}
else{
//准备参数
Object searchContext=gridParamList.get(0);
String dataSetName=String.valueOf(gridParamList.get(1));
EntityBase entity = (EntityBase) gridParamList.get(2);
deStorageMode= (String) gridParamList.get(3);
String entityName = entity.getClass().getSimpleName();
//获取数据集权限信息
JSONObject permissionList=userPermission.getJSONObject("userPermissionList");
if(StringUtils.isEmpty(entityName)|| StringUtils.isEmpty(dataSetName))
return false;
//检查是否有访问数据集的权限
if(!validDataSetHasPermission(permissionList,entityName,dataSetName)){
return false;
}
return true;
}catch (Exception e){
throw new RuntimeException("系统在进行权限检查时出现异常,原因为:"+e);
//拼接权限条件
deDataSetFillPermissionSQLRouter(deStorageMode, searchContext, entity , dataSetName , permissionList);
}
return true;
}
/**
* 表单权限检查 :用于检查当前用户是否拥有表单的新建、编辑、删除权限
*
* @param authentication
* @param srfkey 当前操作数据的主键
* @param srfKey 当前操作数据的主键
* @param action 当前操作行为:如:[READUPDATEDELETE]
* @param cur_entity 当前操作的实体对象
* @param formParam 表单参数对象
* @return true/false true则允许当前行为,false拒绝行为
*/
@Override
public boolean hasPermission(Authentication authentication, Serializable srfkey, String action, Object cur_entity) {
public boolean hasPermission(Authentication authentication, Serializable srfKey, String action, Object formParam) {
//未开启权限校验、超级管理员则不进行权限检查
if(AuthenticationUser.getAuthenticationUser().getSuperuser()==1 || !enablePermissionValid)
return true; //系统没开启权限、超级管理员 两种情况不进行权限检查
boolean isPermission;
EntityBase entity = null;
return true;
if (cur_entity instanceof EntityBase)
entity = (EntityBase) cur_entity;
List formParamList = (ArrayList) formParam;
EntityBase entity = (EntityBase) formParamList.get(0);
String deStorageMode= (String) formParamList.get(1);
if (StringUtils.isEmpty(entity))
return false;
try {
String entityName = entity.getClass().getSimpleName(); //实体名
if(action.equals("CREATE")){ //表单新建权限校验
JSONObject permissionList= AuthenticationUser.getAuthenticationUser().getPermisionList();//获取权限列表
JSONObject formDataAbility=permissionList.getJSONObject("dataAbility-form");//获取表单的权限数据
return isFormCreatePermission(formDataAbility,entityName,action);//拼接权限条件
JSONObject userPermission= AuthenticationUser.getAuthenticationUser().getPermisionList();
JSONObject permissionList=userPermission.getJSONObject("userPermissionList");
String entityName = entity.getClass().getSimpleName();
if(action.equalsIgnoreCase("create")){
return validDEActionHasPermission(permissionList,entityName,action);
}
else{
//拥有全部数据访问权限时,则跳过权限检查
if(isAllData(permissionList,entityName,action)){
return true;
}
else{
//表单编辑、查询权限校验
ServiceImpl service= SpringContextHolder.getBean(String.format("%s%s",getBeanName(entityName),"ServiceImpl"));//获取当前实体service
JSONObject permissionList= AuthenticationUser.getAuthenticationUser().getPermisionList();//获取权限列表
JSONObject formDataAbility=permissionList.getJSONObject("dataAbility-form");//获取表单的权限数据
if(isAllData(formDataAbility,entityName,action)){//若为全部数据则直接返回,不再进行校验
return true;
}
Map<String,String> permissionField=getPermissionField(entity);//获取系统预置属性
String selectCond=generatePermissionSQLForm(formDataAbility,entityName,action,srfkey,permissionField);//根据uaa中分配的权限拼接where条件
if(StringUtils.isEmpty(selectCond))
return false;
QueryWrapper permissionCond=getPermissionCond(selectCond,permissionField);
isPermission=testDataAccess(service,permissionCond);//执行权限检查
//检查是否有操作权限[create.update.delete.read]
if(!validDEActionHasPermission(permissionList,entityName,action)){
return false;
}
}catch (Exception e){
throw new RuntimeException("系统在进行权限检查时出现异常,原因为:"+e);
//检查是否有数据权限
return deActionPermissionValidRouter(deStorageMode, entity , action , srfKey, permissionList);
}
return isPermission;
}
/**
* 判断是否包含全部数据
* @param formDataAbility
* 是否为全部数据
* @param permissionList
* @param entityName
* @param action
* @return
*/
private boolean isAllData(JSONObject formDataAbility, String entityName, String action) {
private boolean isAllData(JSONObject permissionList, String entityName, String action) {
if(formDataAbility==null)
if(permissionList==null)
return false;
if(!formDataAbility.containsKey(entityName))
if(!permissionList.containsKey(entityName))
return false;
JSONObject entityObj=formDataAbility.getJSONObject(entityName);//获取实体
if(!entityObj.containsKey(action))
return false;
JSONArray entityOperation=entityObj.getJSONArray(action);//行为:readinsert...
if(entityOperation.size()==0)
return false;
if(entityOperation.contains("ALL")){ //全部数据
JSONObject entity=permissionList.getJSONObject(entityName);
if(entity.containsKey(action) && entity.getJSONArray(action).contains("ALL"))
return true;
}
return false;
}
/**
* 拼接表格查询条件
* @param gridDataAbility
* 实体行为权限校验
* @param userPermission
* @param entityName
* @param action
* @param dataSet
* @param permissionField
* @param srfkey
* userPermission:{"ENTITY":{"DEACTION":{"READ":["CURORG"]},"DATASET":{"Default":["CURORG"]}}}
* @return
*/
private String generatePermissionSQLGrid(JSONObject gridDataAbility, String entityName, String action, String dataSet, Map<String,String> permissionField,Object srfkey){
if(gridDataAbility==null)
return null;
if(!gridDataAbility.containsKey(entityName))
return null;
JSONObject entityObj=gridDataAbility.getJSONObject(entityName);//获取实体
if(!entityObj.containsKey(dataSet))
return null;
JSONObject dedatasetObject=entityObj.getJSONObject(dataSet);//获取实体数据集
if(!dedatasetObject.containsKey(action))
return null;
JSONArray entityOperation=dedatasetObject.getJSONArray(action);//行为:readinsert...
if(entityOperation.size()==0)
return null;
if(StringUtils.isEmpty(srfkey))
return getPermissionCond(entityOperation,permissionField); //拼接权限条件-查询
else
return String.format(" (%s) AND (%sid='%s')",getPermissionCond(entityOperation,permissionField),srfkey); //拼接权限条件-删除
}
private boolean validDEActionHasPermission(JSONObject userPermission,String entityName , String action ){
boolean hasPermission=false;
if(userPermission==null)
return false;
if(!userPermission.containsKey(entityName))
return false;
JSONObject entity=userPermission.getJSONObject(entityName);//获取实体
if(!entity.containsKey(DEActionType))
return false;
JSONObject dataRange=entity.getJSONObject(DEActionType);//获取实体行为对应的数据范围
if(dataRange.containsKey(action)){
hasPermission=true;
}
return hasPermission;
}
/**
* 表格拼接权限条件,过滤出权限数据
* @param targetDomainObject
* @param permissionCond
* @throws Exception
* 数据集合权限校验
* @param userPermission
* @param entityName
* @param dataSetName
* userPermission:{"ENTITY":{"DEACTION":{"READ":["CURORG"]},"DATASET":{"Default":["CURORG"]}}}
* @return
*/
private void filterDataAccess(Object targetDomainObject, String permissionCond) throws Exception{
if(targetDomainObject instanceof QueryWrapperContext){
QueryWrapperContext queryWrapperContext = (QueryWrapperContext) targetDomainObject;
QueryWrapper queryWrapper = queryWrapperContext.getSelectCond();
queryWrapper.apply(permissionCond);
private boolean validDataSetHasPermission(JSONObject userPermission,String entityName ,String dataSetName){
boolean hasPermission=false;
if(userPermission==null)
return false;
if(!userPermission.containsKey(entityName))
return false;
JSONObject entity=userPermission.getJSONObject(entityName);//获取实体
if(!entity.containsKey(DataSetTag))
return false;
JSONObject dataSetList=entity.getJSONObject(DataSetTag);//获取数据集
if(!dataSetList.containsKey(dataSetName))
return false;
JSONArray dataRange=dataSetList.getJSONArray(dataSetName);//获取数据范围
if(dataRange!=null && dataRange.size()>0){
hasPermission=true;
}
return hasPermission;
}
/**
* 拼接表单数据查询条件
* @param formDataAbility
* @param entityName
* 根据实体存储模式,进行鉴权
* @param deStorageMode
* @param entity
* @param action
* @param srfkey
* @param permissionField
* @param srfKey
* @param permissionList
* @return
*/
private String generatePermissionSQLForm(JSONObject formDataAbility, String entityName, String action, Object srfkey, Map<String,String> permissionField){
if(formDataAbility==null)
return null;
if(!formDataAbility.containsKey(entityName))
return null;
JSONObject entityObj=formDataAbility.getJSONObject(entityName);//获取实体
if(!entityObj.containsKey(action))
return null;
JSONArray entityOperation=entityObj.getJSONArray(action);//行为:readinsert...
if(entityOperation.size()==0)
return null;
String resultCond=getPermissionCond(entityOperation,permissionField);
if(StringUtils.isEmpty(srfkey))
return String.format(" (%s)",resultCond,entityName.toLowerCase()); //拼接权限条件-新建
else
return String.format(" (%s) AND (%sid='%s')",resultCond,entityName.toLowerCase(),srfkey); //拼接权限条件-编辑
}
private boolean deActionPermissionValidRouter(String deStorageMode, EntityBase entity , String action , Object srfKey , JSONObject permissionList){
if(deStorageMode.equalsIgnoreCase("sql")){
return sqlPermissionValid(entity , action , srfKey, permissionList);
}
else if(deStorageMode.equalsIgnoreCase("nosql")){
return noSqlPermissionValid(entity , action , srfKey, permissionList);
}
else if(deStorageMode.equalsIgnoreCase("serviceapi")){
return true;
}
else {
throw new RuntimeException(String.format("未能识别[%s]实体对应存储模式[%s]",entity.getClass().getSimpleName(),deStorageMode));
}
}
/**
* 判断当前用户是否拥有建立表单数据权限
* @param formDataAbility
* @param entityName
* @param targetType
* sql存储模式实体行为鉴权
* @param entity
* @param action
* @param srfKey
* @param permissionList
* @return
*/
private boolean isFormCreatePermission(JSONObject formDataAbility, String entityName, String targetType){
if(formDataAbility==null)
return false;
if(!formDataAbility.containsKey(entityName))
private boolean sqlPermissionValid(EntityBase entity , String action , Object srfKey, JSONObject permissionList){
String entityName=entity.getClass().getSimpleName();
ServiceImpl service= SpringContextHolder.getBean(String.format("%s%s",entityName,"ServiceImpl"));//获取实体service对象
Map<String,String> permissionField=getPermissionField(entity);//获取组织、部门预置属性
String keyField=permissionField.get(keyFieldTag);
if(StringUtils.isEmpty(keyField)){
throw new RuntimeException("权限校验失败,请检查当前实体中是否已经配置主键属性!");
}
//获取权限表达式[全部数据、本单位、本部门等]
JSONObject entityObj=permissionList.getJSONObject(entity.getClass().getSimpleName());//获取实体
JSONObject permissionType= entityObj.getJSONObject(DEActionType);
JSONArray opprivList=permissionType.getJSONArray(action);//行为:readinsert...
if(opprivList.size()==0)
return false;
JSONObject entityObj=formDataAbility.getJSONObject(entityName);//获取实体
if(!entityObj.containsKey(targetType))
//通过权限表达式来获取sql
String tempPermissionSQL=getPermissionSQL(entity,opprivList);
String permissionSQL= String.format(" (%s) AND (%s='%s')",tempPermissionSQL,keyField,srfKey); //拼接权限条件-编辑
//执行sql进行权限检查
QueryWrapper permissionWrapper=getPermissionWrapper(permissionSQL);//构造权限条件
List list=service.list(permissionWrapper);
if(list.size()>0){
return true;
}else{
return false;
return true;
}
}
/**
* 表单权限检查
* @param service
* @param permissionCond
* NoSQL实体行为鉴权
* @param entity
* @param action
* @param srfKey
* @param permissionList
* @return
*/
private boolean testDataAccess(ServiceImpl service, QueryWrapper permissionCond){
boolean isPermission=false;
List list=service.list(permissionCond);
if(list.size()>0)
isPermission=true;
return isPermission;
private boolean noSqlPermissionValid(EntityBase entity, String action, Object srfKey, JSONObject permissionList) {
Map<String,String> permissionField=getPermissionField(entity);//获取组织、部门预置属性
String keyField=permissionField.get(keyFieldTag);
if(StringUtils.isEmpty(keyField)){
throw new RuntimeException("权限校验失败,请检查当前实体中是否已经配置主键属性!");
}
//获取权限表达式[全部数据、本单位、本部门等]
JSONObject entityObj=permissionList.getJSONObject(entity.getClass().getSimpleName());//获取实体
JSONObject permissionType= entityObj.getJSONObject(DEActionType);
JSONArray dataRange=permissionType.getJSONArray(action);//行为:readinsert...
if(dataRange.size()==0)
return false;
//根据权限表达式填充权限条件
QueryBuilder permissionCond=new QueryBuilder();
fillNoSqlPermissionCond(dataRange,entity,permissionCond);
//权限条件拼接主键
permissionCond.and(keyField).is(srfKey);
//执行权限检查
Query query = new BasicQuery(permissionCond.get().toString());
List list=mongoTemplate.find(query,entity.getClass());
if(list.size()>0){
return true;
}
else{
return false;
}
}
/**
* 根据实体存储类型,拼接权限条件
* @param deStorageMode
* @param searchContext
* @param entity
* @param dataSetName
* @param permissionList
*/
private void deDataSetFillPermissionSQLRouter(String deStorageMode , Object searchContext, EntityBase entity ,String dataSetName ,JSONObject permissionList){
//检查是否有数据权限[单行删除]
if(deStorageMode.equalsIgnoreCase("sql")){
sqlPermissionBuilder(searchContext, entity , dataSetName, permissionList);
}
else if(deStorageMode.equalsIgnoreCase("nosql")){
noSqlPermissionBuilder(searchContext, entity , dataSetName, permissionList);
}
else if(deStorageMode.equalsIgnoreCase("serviceapi")){
}
else {
throw new RuntimeException(String.format("未能识别[%s]实体对应存储模式[%s]",entity.getClass().getSimpleName(),deStorageMode));
}
}
/**
* NoSQL存储模式的表格查询填充权限条件
* @param searchContext
* @param entity
* @param dataSetName
* @param permissionList
*/
private void noSqlPermissionBuilder(Object searchContext, EntityBase entity, String dataSetName, JSONObject permissionList) {
if(searchContext instanceof QueryBuildContext){
//获取权限表达式[全部数据、本单位、本部门等]
String entityName=entity.getClass().getSimpleName();
JSONObject entityObj=permissionList.getJSONObject(entityName);
JSONObject permissionType=entityObj.getJSONObject(DataSetTag);
JSONArray dataRange=permissionType.getJSONArray(dataSetName);
if(dataRange.size()==0)
return ;
//根据权限表达式生成查询条件,并将查询条件设置到SearchContext
fillNoSqlPermissionCond(dataRange,entity,((QueryBuildContext) searchContext).getSelectCond());
}
}
/**
* 拼接权限条件(表单/表格)共用
* @param entityOperation
* @param permissionField
* SQL存储模式的表格查询填充权限条件
* @param searchContext
* @param entity
* @param dataSetName
* @param permissionList
*/
private void sqlPermissionBuilder(Object searchContext, EntityBase entity, String dataSetName, JSONObject permissionList){
//获取权限表达式[全部数据、本单位、本部门等]
String entityName=entity.getClass().getSimpleName();
JSONObject entityObj=permissionList.getJSONObject(entityName);//获取实体
JSONObject permissionType=entityObj.getJSONObject(DataSetTag);
JSONArray dataRange=permissionType.getJSONArray(dataSetName);//获取实体数据集
if(dataRange.size()==0)
return ;
//根据权限条件获取SQL
String permissionSQL=getPermissionSQL(entity,dataRange);
//SQL拼接到SearchContext
if(searchContext instanceof QueryWrapperContext){
QueryWrapperContext queryWrapperContext = (QueryWrapperContext) searchContext;
QueryWrapper queryWrapper = queryWrapperContext.getSelectCond();
queryWrapper.apply(permissionSQL);
}
}
/**
* NoSQL存储模式的表格查询填充权限条件
* @param oppriList
* @param entity
* @param permissionSQL
*/
private void fillNoSqlPermissionCond(JSONArray oppriList, EntityBase entity, QueryBuilder permissionSQL){
Map<String,String> permissionField=getPermissionField(entity);//获取组织、部门预置属性
String orgField=permissionField.get("orgfield");
String orgDeptField=permissionField.get("orgsecfield");
String createManField=permissionField.get("createmanfield");
AuthenticationUser authenticationUser = AuthenticationUser.getAuthenticationUser();
JSONObject userInfo = authenticationUser.getOrgInfo();
JSONObject orgObject = userInfo.getJSONObject("org");
JSONArray orgParent = orgObject.getJSONArray("porg");
JSONArray orgChild = orgObject.getJSONArray("sorg");
JSONObject orgDeptObject = userInfo.getJSONObject("orgdept");
JSONArray orgDeptParent = orgDeptObject.getJSONArray("porgdept");
JSONArray orgDeptChild = orgDeptObject.getJSONArray("sorgdept");
for(int i=0;i<oppriList.size();i++){
String permissionCond=oppriList.getString(i);//权限配置条件
if(permissionCond.equals("CURORG")){ //本单位
permissionSQL.or(new QueryBuilder().and(orgField).is(AuthenticationUser.getAuthenticationUser().getOrgid()).get());
}
else if(permissionCond.equals("PORG")){//上级单位
permissionSQL.or(new QueryBuilder().and(orgField).in(formatStringArr(orgParent)).get());
}
else if(permissionCond.equals("SORG")){//下级单位
permissionSQL.or(new QueryBuilder().and(orgField).in(formatStringArr(orgChild)).get());
}
else if(permissionCond.equals("CREATEMAN")){//建立人
permissionSQL.or(new QueryBuilder().and(createManField).is(AuthenticationUser.getAuthenticationUser().getUserid()).get());
}
else if(permissionCond.equals("CURORGDEPT")){//本部门
permissionSQL.or(new QueryBuilder().and(orgDeptField).is(AuthenticationUser.getAuthenticationUser().getMdeptid()).get());
}
else if(permissionCond.equals("PORGDEPT")){//上级部门
permissionSQL.or(new QueryBuilder().and(orgDeptField).in(formatStringArr(orgDeptParent)).get());
}
else if(permissionCond.equals("SORGDEPT")){//下级部门
permissionSQL.or(new QueryBuilder().and(orgDeptField).in(formatStringArr(orgDeptChild)).get());
}
else if(permissionCond.equals("ALL")){
permissionSQL.or(new QueryBuilder().get());
}
}
}
/**
* SQL获取权限条件
* @param entity
* @param oppriList
* @return
*/
private String getPermissionCond(JSONArray entityOperation, Map<String,String> permissionField){
private String getPermissionSQL(EntityBase entity, JSONArray oppriList){
Map<String,String> permissionField=getPermissionField(entity);//获取组织、部门预置属性
String nPermissionSQL = "1<>1";
String orgField=permissionField.get("orgfield");
String orgDeptField=permissionField.get("orgsecfield");
String createManField=permissionField.get("createmanfield");
StringBuffer permissionSQL=new StringBuffer();
AuthenticationUser authenticationUser = AuthenticationUser.getAuthenticationUser();
JSONObject userInfo = authenticationUser.getOrgInfo();
JSONObject orgObject = userInfo.getJSONObject("org");
......@@ -305,61 +503,55 @@ public class AuthPermissionEvaluator implements PermissionEvaluator {
JSONArray orgDeptParent = orgDeptObject.getJSONArray("porgdept");
JSONArray orgDeptChild = orgDeptObject.getJSONArray("sorgdept");
for(int i=0;i<entityOperation.size();i++){
if(i>0 && (!StringUtils.isEmpty(permissionSQL.toString())))
permissionSQL.append("OR");
String permissionCond=entityOperation.getString(i);//权限配置条件
for(int i=0;i<oppriList.size();i++){
permissionSQL.append("OR");
String permissionCond=oppriList.getString(i);//权限配置条件
if(permissionCond.equals("CURORG")){ //本单位
permissionSQL.append(String.format("(%s='%s')",orgField,AuthenticationUser.getAuthenticationUser().getOrgid()));
}
if(permissionCond.equals("SORG")){//下级单位
else if(permissionCond.equals("PORG")){//上级单位
permissionSQL.append(String.format(" %s in(%s) ", orgField, formatStringArr(orgParent)));
}
else if(permissionCond.equals("SORG")){//下级单位
permissionSQL.append(String.format(" %s in(%s) ", orgField, formatStringArr(orgChild)));
}
if(permissionCond.equals("PORG")){//上级单位
permissionSQL.append(String.format(" %s in(%s) ", orgField, formatStringArr(orgParent)));
else if(permissionCond.equals("CREATEMAN")){//建立人
permissionSQL.append(String.format("(%s='%s')",createManField,AuthenticationUser.getAuthenticationUser().getUserid()));
}
if(permissionCond.equals("CREATEMAN")){//建立人
permissionSQL.append(String.format("(createman='%s')",AuthenticationUser.getAuthenticationUser().getUserid()));
else if(permissionCond.equals("CURORGDEPT")){//本部门
permissionSQL.append(String.format("(%s='%s')",orgDeptField,AuthenticationUser.getAuthenticationUser().getMdeptid()));
}
if(permissionCond.equals("CURORGDEPT")){//部门
permissionSQL.append(String.format("(orgsecid='%s')",AuthenticationUser.getAuthenticationUser().getMdeptid()));
else if(permissionCond.equals("PORGDEPT")){//上级部门
permissionSQL.append(String.format(" %s in (%s) ", orgDeptField, formatStringArr(orgDeptParent)));
}
if(permissionCond.equals("SORGDEPT")){//下级部门
else if(permissionCond.equals("SORGDEPT")){//下级部门
permissionSQL.append(String.format(" %s in (%s) ", orgDeptField, formatStringArr(orgDeptChild)));
}
if(permissionCond.equals("PORGDEPT")){//上级部门
permissionSQL.append(String.format(" %s in (%s) ", orgDeptField, formatStringArr(orgDeptParent)));
else if(permissionCond.equals("ALL")){//全部数据
permissionSQL.append("(1=1)");
}
else{
permissionSQL.append(nPermissionSQL);
}
if(permissionCond.equals("ALL")){//全部数据
permissionSQL.append("(1=1)");
}
}
if(StringUtils.isEmpty(permissionSQL.toString()))
return "";
String resultCond=permissionSQL.toString();
if(resultCond.endsWith("OR")){
resultCond=resultCond.substring(0,resultCond.lastIndexOf("OR"));
}
String resultCond=parseResult(permissionSQL, "OR");
return resultCond;
}
/**
* 拼接权限查询条件(表单/表格)共用
* 构造 wrapper
* @param whereCond
* @param permissionField
* @return
*/
private QueryWrapper getPermissionCond(String whereCond, Map<String,String> permissionField){
QueryWrapper allPermissionCond=new QueryWrapper();
private QueryWrapper getPermissionWrapper(String whereCond){
if(StringUtils.isEmpty(whereCond))
return allPermissionCond;
allPermissionCond.apply(whereCond);
return allPermissionCond;
QueryWrapper permissionWrapper=new QueryWrapper();
if(!StringUtils.isEmpty(whereCond)){
permissionWrapper.apply(whereCond);
}
return permissionWrapper;
}
/**
......@@ -368,47 +560,76 @@ public class AuthPermissionEvaluator implements PermissionEvaluator {
* @return
*/
private Map<String,String> getPermissionField(EntityBase entityBase){
Map<String,String> permissionFiled=new HashMap<>();
String orgField="orgid"; //组织权限默认值
String orgsecField="orgsecid"; //部门权限默认值
// Map<Field, PreField> preFields= entityBase.SearchPreField(); //从缓存中获取当前类预置属性
// //寻找实体权限属性
// for (Map.Entry<Field,PreField> entry : preFields.entrySet()){
// Field prefield=entry.getKey();//获取注解字段
// PreField fieldAnnotation=entry.getValue();//获取注解值
// PredefinedType prefieldType=fieldAnnotation.preType();
// if(prefieldType==PredefinedType.ORGID)//用户配置系统预置属性-组织机构标识
// orgField=prefield.getName();
// if(prefieldType==PredefinedType.ORGSECTORID)//用户配置系统预置属性-部门标识
// orgsecField=prefield.getName();
// }
String orgField="orgid"; //组织属性
String orgDeptField="orgsecid"; //部门属性
String createManField="createman"; //创建人属性
String keyField="";//主键属性
DEFieldCacheMap.getFieldMap(entityBase.getClass().getName());
Map <Field, DEField> preFields= SearchDEField(entityBase.getClass().getName()); //从缓存中获取当前类预置属性
for (Map.Entry<Field,DEField> entry : preFields.entrySet()){
Field preField=entry.getKey();//获取注解字段
DEField fieldAnnotation=entry.getValue();//获取注解值
DEPredefinedFieldType prefieldType=fieldAnnotation.preType();
if(prefieldType==prefieldType.ORGID)//用户配置系统预置属性-组织机构标识
orgField=preField.getName();
if(prefieldType==prefieldType.ORGSECTORID)//用户配置系统预置属性-部门标识
orgDeptField=preField.getName();
if(fieldAnnotation.isKeyField())//用户配置系统预置属性-部门标识
keyField=preField.getName();
}
permissionFiled.put("orgfield",orgField);
permissionFiled.put("orgsecfield",orgsecField);
permissionFiled.put("orgsecfield",orgDeptField);
permissionFiled.put("createmanfield",createManField);
permissionFiled.put("keyfield",keyField);
return permissionFiled;
}
/**
* 获取bean名称
* @param className
*获取含有@DEField注解的实体属性
* @param className do对象类名
* @return
*/
private String getBeanName(String className) {
if (Character.isLowerCase(className.charAt(0))) {
return className;
} else {
return (new StringBuilder()).append(Character.toLowerCase(className.charAt(0))).append(className.substring(1)).toString();
private Map <Field, DEField> SearchDEField(String className){
List<Field> fields = DEFieldCacheMap.getFields(className);
Map <Field, DEField> deFieldMap =new HashMap<>();
for(Field field:fields){
DEField deField=field.getAnnotation(DEField.class);
if(!ObjectUtils.isEmpty(deField)) {
deFieldMap.put(field,deField);
}
}
return deFieldMap;
}
/**
* 转换[a,b]格式字符串到 'a','b'格式
*
* @return
*/
private String formatStringArr(JSONArray array) {
String[] arr = array.toArray(new String[array.size()]);
return "'" + String.join("','", arr) + "'";
}
/**
* 格式转换
* @param cond
* @param operator
* @return
*/
private String parseResult(StringBuffer cond, String operator) {
String resultCond = cond.toString();
if (resultCond.startsWith(operator))
resultCond = resultCond.replaceFirst(operator, "");
if (resultCond.endsWith(operator))
resultCond = resultCond.substring(0, resultCond.lastIndexOf(operator));
return resultCond;
}
}
\ No newline at end of file
......@@ -58,7 +58,7 @@ public class AuthenticationUser implements UserDetails
private String fontsize;
private String lang;
private String memo;
private Map <String,String> sessionParams;
private Map <String,Object> sessionParams;
@JsonIgnore
private Collection<GrantedAuthority> authorities;
@JsonIgnore
......@@ -68,7 +68,7 @@ public class AuthenticationUser implements UserDetails
private String orglevel;//单位级别
private String deptlevel;//部门级别
@JsonIgnore
private Map<String,String> userSessionParam;//用户自定义session
private Map<String,Object> userSessionParam;//用户自定义session
@JsonIgnore
private JSONObject orgInfo;//上下级组织信息
......@@ -118,7 +118,7 @@ public class AuthenticationUser implements UserDetails
return authuserdetail;
}
public Map <String,String> getSessionParams()
public Map <String,Object> getSessionParams()
{
if(this.sessionParams==null)
{
......@@ -142,7 +142,7 @@ public class AuthenticationUser implements UserDetails
}
return this.sessionParams;
}
private Map<String, String> getUserSessionParam() {
private Map<String, Object> getUserSessionParam() {
if(userSessionParam!=null)
return userSessionParam;
else
......
......@@ -4,8 +4,9 @@ TARGET=PSSYSTEM
package ${pub.getPKGCodeName()}.util.service;
import ${pub.getPKGCodeName()}.util.domain.FileItem;
import com.cmbchina.util.errors.InternalServerErrorException;
import ${pub.getPKGCodeName()}.util.errors.InternalServerErrorException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
......@@ -14,7 +15,6 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;
@Primary
@Slf4j
......@@ -24,26 +24,22 @@ public class SimpleFileService implements FileService {
@Value("${r'${ibiz.filePath:/app/file/}'}")
private String fileRoot;
@Override
public FileItem saveFile(MultipartFile multipartFile) {
FileItem item=null;
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
// 获取文件后缀
String extname="."+getExtensionName(fileName);
// uuid作为文件名,防止生成的临时文件重复
String fileid= UUID.randomUUID().toString();
String fileFullPath = this.fileRoot+"ibztuit"+File.separator+fileid+File.separator+fileName;
File file = new File(fileFullPath);
File parent = new File(file.getParent());
if(!parent.exists())
parent.mkdirs();
try {
FileCopyUtils.copy(multipartFile.getInputStream() , Files.newOutputStream(file.toPath()));
item=new FileItem(fileid,fileName, (int)multipartFile.getSize() ,extname);
String fileid= DigestUtils.md5DigestAsHex(multipartFile.getInputStream());
String fileFullPath = this.fileRoot+"ibizutil"+File.separator+fileid+File.separator+fileName;
File file = new File(fileFullPath);
File parent = new File(file.getParent());
if(!parent.exists())
parent.mkdirs();
FileCopyUtils.copy(multipartFile.getInputStream(),Files.newOutputStream(file.toPath()));
item=new FileItem(fileid,fileName,fileid,fileName,(int)multipartFile.getSize(),extname);
} catch (IOException e) {
throw new InternalServerErrorException("文件上传失败");
}
......@@ -52,7 +48,7 @@ public class SimpleFileService implements FileService {
@Override
public File getFile(String fileid) {
String dirpath = this.fileRoot+"ibztuit"+File.separator+fileid;
String dirpath = this.fileRoot+"ibizutil"+File.separator+fileid;
File parent = new File(dirpath);
if (parent.exists() && parent.isDirectory() && parent.listFiles().length > 0) {
return parent.listFiles()[0];
......
......@@ -112,7 +112,10 @@ public class SimpleUserService implements AuthenticationUserService{
JSONObject orgInfo=ouFeignClient.getOrgInfo(user.getLoginname());
if(orgInfo==null)
throw new RuntimeException("获取用户信息失败,请检查用户中心[IBZOU]中是否存在当前用户!");
JSONObject curUser=orgInfo.getJSONObject("curuser");
user.setOrgInfo(orgInfo);
user.setMdeptid(curUser.getString("orgdept"));
user.setOrgid(curUser.getString("org"));
}
}
......
......@@ -78,3 +78,7 @@ logging:
ribbon:
ReadTimeout: 60000
ConnectTimeout: 60000
#系统是否开启权限验证
ibiz:
enablePermissionValid: false
......@@ -2,7 +2,7 @@
TARGET=PSSYSTEM
</#ibiztemplate>
<#if pub.getPSDeployCenter()?? && sysrun.getRunMode()??>
<#if pub.getPSDeployCenter().getDeployCenterType()?? && (pub.getPSDeployCenter().getDeployCenterType()=="JENKINS") >
<#if pub.getPSDeployCenter().getCIType()?? && (pub.getPSDeployCenter().getCIType()=="JENKINS") >
<#if sysrun.getRunMode() == "STARTMSAPI">
<#assign depapi = sysrun.getPSDevSlnMSDepAPI()>
<#assign configId = depapi.getId()>
......@@ -53,6 +53,7 @@ TARGET=PSSYSTEM
<hudson.tasks.Shell>
<command>
BUILD_ID=DONTKILLME
echo "${pub.getPSDeployCenter().getPSRegistryRepo().getConnStr()}"
source /etc/profile
rm -rf ${sys.codeName?lower_case}
git clone -b ${branch} $para2 ${sys.codeName?lower_case}/
......@@ -60,10 +61,13 @@ TARGET=PSSYSTEM
cd ${sys.codeName?lower_case}/
<#if sysrun.getRunMode() == "STARTMSAPP">
mvn clean package -P${pub.getPSApplication().getPKGCodeName()?lower_case}
<#if pub.getPSDeployCenter().getCDType()?? && (pub.getPSDeployCenter().getCDType()=="SWARM") >
cd ${pub.getCodeName()?lower_case}-app/${pub.getCodeName()?lower_case}-app-${pub.getPSApplication().getPKGCodeName()?lower_case}
mvn -P${pub.getPSApplication().getPKGCodeName()?lower_case} docker:build
mvn -P${pub.getPSApplication().getPKGCodeName()?lower_case} docker:push
docker -H tcp://172.16.102.110:2375 stack deploy --compose-file=src/main/docker/${pub.getCodeName()?lower_case}-app-${pub.getPSApplication().getPKGCodeName()?lower_case}.yaml dev --with-registry-auth
docker -H $para1 stack deploy --compose-file=src/main/docker/${pub.getCodeName()?lower_case}-app-${pub.getPSApplication().getPKGCodeName()?lower_case}.yaml dev --with-registry-auth
<#elseif pub.getPSDeployCenter().getCDType()?? && (pub.getPSDeployCenter().getCDType()=="K8S") >
<#else>
echo &apos;echo &quot;$para1&quot;&apos; &gt; apppasswd.sh
chmod -R 777 *
setsid env SSH_ASKPASS=&apos;./apppasswd.sh&apos; DISPLAY=&apos;none:0&apos; ssh ${depnode.getSSHUserName()}@${depnode.getSSHIPAddr()} &quot;mkdir -p ${depnode.getWorkshopPath()}/${configId}&quot;
......@@ -71,18 +75,23 @@ TARGET=PSSYSTEM
setsid env SSH_ASKPASS=&apos;./apppasswd.sh&apos; DISPLAY=&apos;none:0&apos; ssh ${depnode.getSSHUserName()}@${depnode.getSSHIPAddr()} &quot;ps -ef | grep &apos;${depnode.getWorkshopPath()}/${configId}&apos;| tr -s &apos; &apos;|cut -d&apos; &apos; -f2,8,9 | grep -v grep | grep &apos;jar&apos; | cut -d&apos; &apos; -f1|xargs --no-run-if-empty kill -9&quot;
setsid env SSH_ASKPASS=&apos;./apppasswd.sh&apos; DISPLAY=&apos;none:0&apos; ssh ${depnode.getSSHUserName()}@${depnode.getSSHIPAddr()} &quot;source /etc/profile;source ~/.bash_profile; nohup java -jar -Xms512m -Xmx1024m -XX:PermSize=128M -XX:MaxPermSize=128m ${depnode.getWorkshopPath()}/${configId}/${pub.getCodeName()?lower_case}-app-${pub.getPSApplication().getPKGCodeName()?lower_case}.jar &gt;&gt;${depnode.getWorkshopPath()}/${configId}/${sys.codeName?lower_case}_${config?lower_case}-`date --date=&apos;0 days ago&apos; +%Y-%m-%d`.log 2&gt;&amp;1 &amp;&quot;
</#if>
</#if>
<#if sysrun.getRunMode() == "STARTMSAPI">
mvn clean package -P${pub.getPSSysServiceAPI().getCodeName()?lower_case}
<#if pub.getPSDeployCenter().getCDType()?? && (pub.getPSDeployCenter().getCDType()=="SWARM") >
cd ${pub.getCodeName()?lower_case}-provider/${pub.getCodeName()?lower_case}-provider-${pub.getPSSysServiceAPI().getCodeName()?lower_case}
mvn -P${pub.getPSSysServiceAPI().getCodeName()?lower_case} docker:build
mvn -P${pub.getPSSysServiceAPI().getCodeName()?lower_case} docker:push
docker -H tcp://172.16.102.110:2375 stack deploy --compose-file=src/main/docker/${pub.getCodeName()?lower_case}-provider-${pub.getPSSysServiceAPI().getCodeName()?lower_case}.yaml dev --with-registry-auth
docker -H $para1 stack deploy --compose-file=src/main/docker/${pub.getCodeName()?lower_case}-provider-${pub.getPSSysServiceAPI().getCodeName()?lower_case}.yaml dev --with-registry-auth
<#elseif pub.getPSDeployCenter().getCDType()?? && (pub.getPSDeployCenter().getCDType()=="K8S") >
<#else>
echo &apos;echo &quot;$para1&quot;&apos; &gt; apppasswd.sh
chmod -R 777 *
setsid env SSH_ASKPASS=&apos;./apppasswd.sh&apos; DISPLAY=&apos;none:0&apos; ssh ${depnode.getSSHUserName()}@${depnode.getSSHIPAddr()} &quot;mkdir -p ${depnode.getWorkshopPath()}/${configId}&quot;
setsid env SSH_ASKPASS=&apos;./apppasswd.sh&apos; DISPLAY=&apos;none:0&apos; scp -r ${pub.getCodeName()?lower_case}-provider-${pub.getPSSysServiceAPI().getCodeName()?lower_case}.jar ${depnode.getSSHUserName()}@${depnode.getSSHIPAddr()}:${depnode.getWorkshopPath()}/${configId}
setsid env SSH_ASKPASS=&apos;./apppasswd.sh&apos; DISPLAY=&apos;none:0&apos; ssh ${depnode.getSSHUserName()}@${depnode.getSSHIPAddr()} &quot;ps -ef | grep &apos;${depnode.getWorkshopPath()}/${configId}&apos;| tr -s &apos; &apos;|cut -d&apos; &apos; -f2,8,9 | grep -v grep | grep &apos;jar&apos; | cut -d&apos; &apos; -f1|xargs --no-run-if-empty kill -9&quot;
setsid env SSH_ASKPASS=&apos;./apppasswd.sh&apos; DISPLAY=&apos;none:0&apos; ssh ${depnode.getSSHUserName()}@${depnode.getSSHIPAddr()} &quot;source /etc/profile;source ~/.bash_profile; nohup java -jar -Xms512m -Xmx1024m -XX:PermSize=128M -XX:MaxPermSize=128m ${depnode.getWorkshopPath()}/${configId}/${pub.getCodeName()?lower_case}-provider-${pub.getPSSysServiceAPI().getCodeName()?lower_case}.jar &gt;&gt;${depnode.getWorkshopPath()}/${configId}/${sys.codeName?lower_case}_${config?lower_case}-`date --date=&apos;0 days ago&apos; +%Y-%m-%d`.log 2&gt;&amp;1 &amp;&quot;
</#if>
</#if>
</command>
</hudson.tasks.Shell>
......
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册