validation
stringlengths 16
3.54k
| validationType
stringclasses 2
values | function
stringlengths 49
6.38k
| author
stringclasses 5
values | context
stringclasses 5
values |
|---|---|---|---|---|
@PreAuthorize("hasRole('PRODUCTS')")
|
annotation
|
@RequestMapping("/admin/files/downloads/{storeCode}/{fileName}.{extension}")
public @ResponseBody byte[] downloadProduct(@PathVariable final String storeCode, @PathVariable final String fileName, @PathVariable final String extension, HttpServletRequest request, HttpServletResponse response) throws Exception {
FileContentType fileType = FileContentType.PRODUCT_DIGITAL;
String fileNameAndExtension = new StringBuilder().append(fileName).append(".").append(extension).toString();
// needs to query the new API
OutputContentFile file = contentService.getContentFile(storeCode, fileType, fileNameAndExtension);
if(file!=null) {
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileNameAndExtension + "\"");
return file.getFile().toByteArray();
} else {
LOGGER.debug("File not found " + fileName + "." + extension);
response.sendError(404, Constants.FILE_NOT_FOUND);
return null;
}
}
|
万爽
| |
// 校验数据范围
List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
if(!loginUserDataScope.containsAll(orgIdList)) {
throw new CommonException("您没有权限删除这些机构,机构id:{}", orgIdList);
}
} else {
throw new CommonException("您没有权限删除这些机构,机构id:{}", orgIdList);
}
|
conventional
|
@Transactional(rollbackFor = Exception.class)
@Override
public void delete(List<BizOrgIdParam> bizOrgIdParamList) {
List<String> orgIdList = CollStreamUtil.toList(bizOrgIdParamList, BizOrgIdParam::getId);
if(ObjectUtil.isNotEmpty(orgIdList)) {
List<BizOrg> allOrgList = this.list();
// 获取所有子机构
List<String> toDeleteOrgIdList = CollectionUtil.newArrayList();
orgIdList.forEach(orgId -> toDeleteOrgIdList.addAll(this.getChildListById(allOrgList, orgId, true).stream()
.map(BizOrg::getId).collect(Collectors.toList())));
// 机构下有人不能删除(直属机构)
boolean hasOrgUser = bizUserService.count(new LambdaQueryWrapper<BizUser>().in(BizUser::getOrgId, toDeleteOrgIdList)) > 0;
if(hasOrgUser) {
throw new CommonException("请先删除机构下的人员");
}
// 机构下有人不能删除(兼任机构)
List<String> positionJsonList = bizUserService.list(new LambdaQueryWrapper<BizUser>()
.isNotNull(BizUser::getPositionJson)).stream().map(BizUser::getPositionJson).collect(Collectors.toList());
if(ObjectUtil.isNotEmpty(positionJsonList)) {
List<String> positionOrgIdList = CollectionUtil.newArrayList();
positionJsonList.forEach(positionJson -> JSONUtil.toList(JSONUtil.parseArray(positionJson), JSONObject.class)
.forEach(jsonObject -> positionOrgIdList.add(jsonObject.getStr("orgId"))));
boolean hasPositionUser = CollectionUtil.intersectionDistinct(toDeleteOrgIdList, CollectionUtil.removeNull(positionOrgIdList)).size() > 0;
if(hasPositionUser) {
throw new CommonException("请先删除机构下的人员");
}
}
// 机构下有角色不能删除
boolean hasRole = sysRoleApi.orgHasRole(toDeleteOrgIdList);
if(hasRole) {
throw new CommonException("请先删除机构下的角色");
}
// 机构下有岗位不能删除
boolean hasPosition = bizPositionService.count(new LambdaQueryWrapper<BizPosition>().in(BizPosition::getOrgId, toDeleteOrgIdList)) > 0;
if(hasPosition) {
throw new CommonException("请先删除机构下的岗位");
}
// 执行删除
this.removeByIds(toDeleteOrgIdList);
// 发布删除事件
CommonDataChangeEventCenter.doDeleteWithDataId(BizDataTypeEnum.ORG.getValue(), toDeleteOrgIdList);
}
}
|
万爽
| |
// 校验数据范围
List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
if(!loginUserDataScope.contains(bizOrgAddParam.getParentId())) {
throw new CommonException("您没有权限在该机构下增加机构,机构id:{}", bizOrgAddParam.getParentId());
}
} else {
throw new CommonException("您没有权限增加机构");
}
|
conventional
|
@Transactional(rollbackFor = Exception.class)
@Override
public void add(BizOrgAddParam bizOrgAddParam) {
BizOrgCategoryEnum.validate(bizOrgAddParam.getCategory());
BizOrg bizOrg = BeanUtil.toBean(bizOrgAddParam, BizOrg.class);
// 重复名称
boolean repeatName = this.count(new LambdaQueryWrapper<BizOrg>().eq(BizOrg::getParentId, bizOrg.getParentId())
.eq(BizOrg::getName, bizOrg.getName())) > 0;
if(repeatName) {
throw new CommonException("存在重复的同级机构,名称为:{}", bizOrg.getName());
}
bizOrg.setCode(RandomUtil.randomString(10));
this.save(bizOrg);
// 发布增加事件
CommonDataChangeEventCenter.doAddWithData(BizDataTypeEnum.ORG.getValue(), JSONUtil.createArray().put(bizOrg));
}
|
万爽
| |
// 校验数据范围
List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
if(!loginUserDataScope.containsAll(positionOrgIdList)) {
throw new CommonException("您没有权限删除这些机构下的岗位,机构id:{}", positionOrgIdList);
}
} else {
throw new CommonException("您没有权限删除这些机构下的岗位,机构id:{}", positionOrgIdList);
}
|
conventional
|
@Transactional(rollbackFor = Exception.class)
@Override
public void delete(List<BizPositionIdParam> bizPositionIdParamList) {
List<String> positionIdList = CollStreamUtil.toList(bizPositionIdParamList, BizPositionIdParam::getId);
if(ObjectUtil.isNotEmpty(positionIdList)) {
// 获取这些岗位的的机构id集合
Set<String> positionOrgIdList = this.listByIds(positionIdList).stream().map(BizPosition::getOrgId).collect(Collectors.toSet());
// 岗位下有人不能删除(直属岗位)
boolean hasOrgUser = bizUserService.count(new LambdaQueryWrapper<BizUser>().in(BizUser::getPositionId, positionIdList)) > 0;
if(hasOrgUser) {
throw new CommonException("请先删除岗位下的用户");
}
// 岗位下有人不能删除(兼任岗位)
List<String> positionJsonList = bizUserService.list(new LambdaQueryWrapper<BizUser>()
.isNotNull(BizUser::getPositionJson)).stream().map(BizUser::getPositionJson).collect(Collectors.toList());
if(ObjectUtil.isNotEmpty(positionJsonList)) {
List<String> extPositionIdList = CollectionUtil.newArrayList();
positionJsonList.forEach(positionJson -> JSONUtil.toList(JSONUtil.parseArray(positionJson), JSONObject.class)
.forEach(jsonObject -> extPositionIdList.add(jsonObject.getStr("positionId"))));
boolean hasPositionUser = CollectionUtil.intersectionDistinct(positionIdList, CollectionUtil.removeNull(extPositionIdList)).size() > 0;
if(hasPositionUser) {
throw new CommonException("请先删除岗位下的用户");
}
}
// 执行删除
this.removeByIds(positionIdList);
// 发布删除事件
CommonDataChangeEventCenter.doDeleteWithDataId(BizDataTypeEnum.POSITION.getValue(), positionIdList);
}
}
|
万爽
| |
@RequiresPermissions("system:dept:add")
|
annotation
|
/**
* 新增保存部门
*/
@Log(title = "部门管理", businessType = BusinessType.INSERT)
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(SysDept dept)
{
dept.setCreateBy(ShiroUtils.getLoginName());
return toAjax(deptService.insertDept(dept));
}
|
万爽
| |
@RequiresPermissions("tool:swagger:view")
|
annotation
|
@Controller
@RequestMapping("/tool/swagger")
public class SwaggerController extends BaseController
{
@GetMapping()
public String index()
{
return redirect("/swagger-ui.html");
}
}
|
万爽
| |
@RequiresPermissions("system:menu:remove")
|
annotation
|
/**
* 删除菜单
*/
@Log(title = "菜单管理", businessType = BusinessType.DELETE)
@PostMapping("/remove/{menuId}")
@ResponseBody
public AjaxResult remove(@PathVariable("menuId") Long menuId)
{
if (menuService.selectCountMenuByParentId(menuId) > 0)
{
return error(1, "存在子菜单,不允许删除");
}
if (menuService.selectCountRoleMenuByMenuId(menuId) > 0)
{
return error(1, "菜单已分配,不允许删除");
}
ShiroUtils.clearCachedAuthorizationInfo();
return toAjax(menuService.deleteMenuById(menuId));
}
|
万爽
| |
@PermissionData(pageComponent = "jeecg/JeecgDemoList")
|
annotation
|
@ApiOperation(value = "获取Demo数据列表", notes = "获取所有Demo数据列表")
@GetMapping(value = "/list")
public Result<?> list(JeecgDemo jeecgDemo, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
QueryWrapper<JeecgDemo> queryWrapper = QueryGenerator.initQueryWrapper(jeecgDemo, req.getParameterMap());
queryWrapper.orderByDesc("create_time");
Page<JeecgDemo> page = new Page<JeecgDemo>(pageNo, pageSize);
IPage<JeecgDemo> pageList = jeecgDemoService.page(page, queryWrapper);
log.info("查询当前页:" + pageList.getCurrent());
log.info("查询当前页数量:" + pageList.getSize());
log.info("查询结果数量:" + pageList.getRecords().size());
log.info("数据总数:" + pageList.getTotal());
return Result.OK(pageList);
}
|
万爽
| |
@PermissionData(pageComponent = "jeecg/JeecgDemoList")
|
annotation
|
/**
* 导出excel
*
* @param request
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, JeecgDemo jeecgDemo) {
//获取导出表格字段
String exportFields = jeecgDemoService.getExportFields();
//分sheet导出表格字段
return super.exportXlsSheet(request, jeecgDemo, JeecgDemo.class, "单表模型",exportFields,500);
}
|
万爽
|
@Pointcut("@annotation(org.jeecg.common.aspect.annotation.PermissionData)")
public void pointCut() {
}
@Around("pointCut()")
public Object arround(ProceedingJoinPoint point) throws Throwable{
HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
PermissionData pd = method.getAnnotation(PermissionData.class);
String component = pd.pageComponent();
String requestMethod = request.getMethod();
String requestPath = request.getRequestURI().substring(request.getContextPath().length());
requestPath = filterUrl(requestPath);
//update-begin-author:taoyan date:20211027 for:JTC-132【online报表权限】online报表带参数的菜单配置数据权限无效
//先判断是否online报表请求
// TODO 参数顺序调整有隐患
if(requestPath.indexOf(UrlMatchEnum.CGREPORT_DATA.getMatchUrl())>=0){
// 获取地址栏参数
String urlParamString = request.getParameter(CommonConstant.ONL_REP_URL_PARAM_STR);
if(oConvertUtils.isNotEmpty(urlParamString)){
requestPath+="?"+urlParamString;
}
}
//update-end-author:taoyan date:20211027 for:JTC-132【online报表权限】online报表带参数的菜单配置数据权限无效
log.info("拦截请求 >> {} ; 请求类型 >> {} . ", requestPath, requestMethod);
String username = JwtUtil.getUserNameByToken(request);
//查询数据权限信息
//TODO 微服务情况下也得支持缓存机制
List<SysPermissionDataRuleModel> dataRules = commonApi.queryPermissionDataRule(component, requestPath, username);
if(dataRules!=null && dataRules.size()>0) {
//临时存储
JeecgDataAutorUtils.installDataSearchConditon(request, dataRules);
//TODO 微服务情况下也得支持缓存机制
SysUserCacheInfo userinfo = commonApi.getCacheUser(username);
JeecgDataAutorUtils.installUserInfo(request, userinfo);
}
return point.proceed();
}
|
@PermissionData(pageComponent = "system/TenantList")
|
annotation
|
/**
* 获取列表数据
* @param sysTenant
* @param pageNo
* @param pageSize
* @param req
* @return
*/
//@RequiresPermissions("system:tenant:list")
@RequestMapping(value = "/list", method = RequestMethod.GET)
public Result<IPage<SysTenant>> queryPageList(SysTenant sysTenant, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
@RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
Result<IPage<SysTenant>> result = new Result<IPage<SysTenant>>();
//---author:zhangyafei---date:20210916-----for: 租户管理添加日期范围查询---
Date beginDate=null;
Date endDate=null;
if(oConvertUtils.isNotEmpty(sysTenant)) {
beginDate=sysTenant.getBeginDate();
endDate=sysTenant.getEndDate();
sysTenant.setBeginDate(null);
sysTenant.setEndDate(null);
}
//---author:zhangyafei---date:20210916-----for: 租户管理添加日期范围查询---
QueryWrapper<SysTenant> queryWrapper = QueryGenerator.initQueryWrapper(sysTenant, req.getParameterMap());
//---author:zhangyafei---date:20210916-----for: 租户管理添加日期范围查询---
if(oConvertUtils.isNotEmpty(sysTenant)){
queryWrapper.ge(oConvertUtils.isNotEmpty(beginDate),"begin_date",beginDate);
queryWrapper.le(oConvertUtils.isNotEmpty(endDate),"end_date",endDate);
}
//---author:zhangyafei---date:20210916-----for: 租户管理添加日期范围查询---
Page<SysTenant> page = new Page<SysTenant>(pageNo, pageSize);
IPage<SysTenant> pageList = sysTenantService.page(page, queryWrapper);
result.setSuccess(true);
result.setResult(pageList);
return result;
}
|
万爽
| |
if (!adminUserService.isAdmin(loginUser)) {
return Result.error(HttpStatus.BAD_REQUEST,"无权限");
}
|
conventional
|
public Result getReportDetail(@RequestBody SecureWafReportDetailQuery query,HttpServletRequest request) throws IOException {
String loginUser = userInfoService.getUserErp(request);
return secureWafTaskRecordService.getReportDetail(query);
}
|
文承业
| |
if (!adminUserService.isAdmin(user)&& agentClusterAddReqVo.getIsDefault()) {
return Result.error("只有管理员才可以操作默认集群");
}
|
conventional
|
public Result insertOrUpdate(AgentClusterAddReqVo agentClusterAddReqVo,String user) {
Result baseResponse = new Result();
try {
log.debug("AgentClusterServiceImpl.insertOrUpdate(), agentClusterAddReqVo is {}", JSON.toJSONString(agentClusterAddReqVo));
AgentCluster agentCluster = new AgentCluster();
agentCluster.setClusterName(agentClusterAddReqVo.getClusterName());
agentCluster.setClusterInfo(agentClusterAddReqVo.getClusterInfo());
agentCluster.setHealthCheckPath(agentClusterAddReqVo.getHealthCheckPath());
agentCluster.setHealthCheckStatusCode(agentClusterAddReqVo.getHealthCheckStatusCode());
agentCluster.setHealthCheckIncludeBody(agentClusterAddReqVo.getHealthCheckIncludeBody());
agentCluster.setHealthCheckTimeout(agentClusterAddReqVo.getHealthCheckTimeout());
agentCluster.setHealthCheckNodeRetryMax(agentClusterAddReqVo.getHealthCheckNodeRetryMax());
agentCluster.setIsDefault(agentClusterAddReqVo.getIsDefault());
agentCluster.setProjectId(agentClusterAddReqVo.getProjectId());
// 唯一性
boolean uniq = checkAgentClusterNameUnique(agentCluster.getClusterName());
// 插入或者更新
if (agentClusterAddReqVo.getClusterId() != null && agentClusterAddReqVo.getClusterId() != 0) {
log.info("AgentClusterServiceImpl.insertOrUpdate(), update cluster, clusterId: {}", agentClusterAddReqVo.getClusterId());
// 更新
agentCluster.setClusterId(agentClusterAddReqVo.getClusterId());
agentCluster.setUpdateUser(agentClusterAddReqVo.getUsername());
AgentClusterRspVo agentClusterRspVo = agentClusterMapper.selectClusterById(agentClusterAddReqVo.getClusterId());
if(agentClusterRspVo==null){
return new Result<>(ResponseCode.AGENT_CLUSTER_NOT_EXIST.code,ResponseCode.AGENT_CLUSTER_NOT_EXIST.message);
}
if (!agentClusterRspVo.getClusterName().equals(agentClusterAddReqVo.getClusterName())) {
if (!uniq) {
log.error("AgentClusterServiceImpl.insertOrUpdate error {}, clusterName is {}", ResponseCode.AGENT_CLUSTER_NOT_UNIQUE.message, agentCluster.getClusterName());
return new Result<>(ResponseCode.AGENT_CLUSTER_NOT_UNIQUE.code, ResponseCode.AGENT_CLUSTER_NOT_UNIQUE.message);
}
}
} else {
// 插入
log.info("AgentClusterServiceImpl.insertOrUpdate(), insert cluster");
agentCluster.setCreateUser(agentClusterAddReqVo.getUsername());
if (!uniq) {
log.error("AgentClusterServiceImpl.insertOrUpdate error {}, clusterName is {}", ResponseCode.AGENT_CLUSTER_NOT_UNIQUE.message, agentCluster.getClusterName());
return new Result<>(ResponseCode.AGENT_CLUSTER_NOT_UNIQUE.code, ResponseCode.AGENT_CLUSTER_NOT_UNIQUE.message);
}
}
int ret = agentClusterMapper.insertOrUpdateAgentCluster(agentCluster);
// 更新集群系统列表
agentClusterAddReqVo.setClusterId(agentCluster.getClusterId());
// agentSystemClusterService.updateClusterSystem(agentClusterAddReqVo);
Map<String, Integer> insertResult = new HashMap<>();
insertResult.put("clusterId",agentCluster.getClusterId());
insertResult.put("影响行数",ret);
baseResponse.setData(insertResult);
baseResponse.setCode(200);
baseResponse.setMsg("操作成功");
} catch (Exception e) {
e.printStackTrace();
log.error("AgentClusterServiceImpl.insertOrUpdate error, {}", e.toString());
return new Result<>(ResponseCode.AGENT_CLUSTER_INTERNAL_ERROR.code, ResponseCode.AGENT_CLUSTER_INTERNAL_ERROR.message);
}
return baseResponse;
}
|
文承业
| |
if (!adminUserService.isAdmin(user)&& agentCluster.getIsDefault()) {
return new Result(501,"只有管理员才可以操作默认集群");
}
|
conventional
|
public Result insertOrUpdate(AgentNodeAddReqVo agentNodeAddReqVo,String user) {
Integer clusterId = agentNodeAddReqVo.getClusterId();
if (clusterId == null) {
return new Result(501,"clusterId为空");
}
AgentClusterRspVo agentCluster = agentClusterService.selectClusterById(clusterId).getData();
Result baseResponse = new Result();
try {
log.debug("AgentNodeServiceImpl.insertOrUpdate(), agentNodeAddReqVo is {}", JSON.toJSONString(agentNodeAddReqVo));
AgentNode agentNode = new AgentNode();
agentNode.setClusterId(agentNodeAddReqVo.getClusterId());
agentNode.setNodeName(agentNodeAddReqVo.getNodeName());
agentNode.setNodeInfo(agentNodeAddReqVo.getNodeInfo());
agentNode.setIp(agentNodeAddReqVo.getIp());
agentNode.setPort(agentNodeAddReqVo.getPort());
agentNode.setEnable(agentNodeAddReqVo.getEnable());
boolean uniq = checkAgentNodeNameUnique(agentNode);
Integer nodeId = agentNodeAddReqVo.getNodeId();
//List<AgentNodeRspVo> agentNodeRspVoList = ClusterHashMap.getNodeList(agentNode.getClusterId().toString());
if (nodeId != null && nodeId != 0) {
// 更新
agentNode.setNodeId(nodeId);
agentNode.setUpdateUser(agentNodeAddReqVo.getUsername());
AgentNodeRspVo agentNodeRspVo = agentNodeMapper.selectAgentNodeById(nodeId);
if(agentNodeRspVo==null){
return new Result<>(ResponseCode.AGENT_NODE_NOT_EXIST.code,ResponseCode.AGENT_NODE_NOT_EXIST.message);
}
if (!agentNodeAddReqVo.getNodeName().equals(agentNodeRspVo.getNodeName())) {
if (!uniq) {
log.debug("AgentNodeServiceImpl.insertOrUpdate(), agentNodeAddReqVo is {} while update, uniq is false", JSON.toJSONString(agentNodeAddReqVo));
return new Result(ResponseCode.AGENT_NODE_NOT_UNIQUE.code, ResponseCode.AGENT_NODE_NOT_UNIQUE.message);
}
}
//启用变为启用,修改并替换
/**
if (agentNodeRspVo.getEnable() && agentNodeAddReqVo.getEnable()) {
for (int i = 0; i < agentNodeRspVoList.size(); i++) {
AgentNodeRspVo node = agentNodeRspVoList.get(i);
if (node.getNodeId() == agentNodeRspVo.getNodeId()) {
AgentNodeRspVo nodeNew = new AgentNodeRspVo();
BeanUtils.copyBeanProp(nodeNew, agentNode);
agentNodeRspVoList.set(i, nodeNew);
break;
}
}
}
**/
//由不启用变成启用状态,增加
/**
if (!agentNodeRspVo.getEnable() && agentNodeAddReqVo.getEnable()) {
AgentNodeRspVo node = new AgentNodeRspVo();
BeanUtils.copyBeanProp(node, agentNode);
if (agentNodeRspVoList == null) {
agentNodeRspVoList = new ArrayList<>();
}
agentNodeRspVoList.add(node);
ClusterHashMap.setNodeListMap(agentNode.getClusterId().toString(), agentNodeRspVoList);
}
**/
//由启用变成不启用状态,删除,并停止定时任务
if (agentNodeRspVo.getEnable() && !agentNodeAddReqVo.getEnable()) {
/**
for (Iterator<AgentNodeRspVo> agentNodeRspVoIterator = agentNodeRspVoList.iterator(); agentNodeRspVoIterator.hasNext(); ) {
AgentNodeRspVo node = agentNodeRspVoIterator.next();
if (node.getNodeId() == agentNodeRspVo.getNodeId()) {
agentNodeRspVoIterator.remove();
ClusterHashMap.setNodeListMap(agentNodeRspVo.getClusterId().toString(), agentNodeRspVoList);
break;
}
}
**/
// 停止健康检查的定时任务
// Future future = ClusterHashMap.getScheduledFutureMap(
// agentNodeAddReqVo.getClusterId()+ CommonConstants.HEALTHCHECK_JOIN+agentNodeRspVo.getNodeId());
// if (future != null && !future.isDone() && !future.isCancelled()) {
// future.cancel(true);
// ClusterHashMap.deleteScheduledFutureMap(
// agentNodeAddReqVo.getClusterId()+ CommonConstants.HEALTHCHECK_JOIN+agentNodeRspVo.getNodeId()
// );
// }
}
} else {
// 插入
agentNode.setCreateUser(agentNodeAddReqVo.getUsername());
if (!uniq) {
log.debug("AgentNodeServiceImpl.insertOrUpdate(), agentNodeAddReqVo is {} while create, uniq is false", JSON.toJSONString(agentNodeAddReqVo));
return new Result(ResponseCode.AGENT_NODE_NOT_UNIQUE.code, ResponseCode.AGENT_NODE_NOT_UNIQUE.message);
}
//若是启用状态则插入启用节点map中
/**
if (agentNode.getEnable()) {
AgentNodeRspVo agentNodeRspVo = new AgentNodeRspVo();
BeanUtils.copyBeanProp(agentNodeRspVo, agentNode);
if (agentNodeRspVoList == null) {
agentNodeRspVoList = new ArrayList<>();
}
agentNodeRspVoList.add(agentNodeRspVo);
ClusterHashMap.setNodeListMap(agentNode.getClusterId().toString(), agentNodeRspVoList);
}
**/
}
agentNodeMapper.insertOrUpdateAgentNode(agentNode);
baseResponse.setCode(200);
baseResponse.setMsg("操作成功");
baseResponse.setData(agentNode.getNodeId());
} catch (Exception e) {
e.printStackTrace();
log.error("AgentNodeServiceImpl.insertOrUpdate(), error is {}", e.toString());
return new Result<>(ResponseCode.AGENT_NODE_INTERNAL_ERROR.code, ResponseCode.AGENT_NODE_INTERNAL_ERROR.message);
}
return baseResponse;
}
|
文承业
| |
if (adminUserService.isAdmin(login)) {
}else {
List<NewProject> projectList = projectService.getProjectById(login,projectQuery.getProjectId());
if (projectList.size()==0) {
return Result.success();
}
}
|
conventional
|
public Result getCaseTree(ProjectQueryParam projectQuery, String login) {
log.info("CaseServeceImpl.getCaseTree, projectQuery is {}", JSON.toJSONString(projectQuery));
if (ObjectUtil.isEmpty(projectQuery.getProjectId())) {
return Result.success();
}
try {
QueryWrapper queryWrapper = new QueryWrapper();
if (ObjectUtil.isNotEmpty(projectQuery.getProjectId())) {
queryWrapper.eq("project_id", projectQuery.getProjectId());
}
if (ObjectUtil.isNotEmpty(projectQuery.getParent())) {
queryWrapper.eq("parent_id", projectQuery.getParent());
}
if (ObjectUtil.isNotEmpty(projectQuery.getCaseType())) {
queryWrapper.in("case_type", projectQuery.getCaseType());
}
queryWrapper.eq("del_flag", 0);
List<NewCaseInfo> caseInfos = baseMapper.selectList(queryWrapper);
List<NewCaseTree> caseTreeList = new ArrayList<>();
for (int i = 0; i < caseInfos.size(); i++) {
NewCaseInfo caseInfo = caseInfos.get(i);
NewCaseTree tree = new NewCaseTree();
tree.setCaseId(caseInfo.getId());
tree.setCaseType(caseInfo.getCaseType());
tree.setCaseName(caseInfo.getCaseName());
tree.setParentId(caseInfo.getParentId());
tree.setCaseLevel(caseInfo.getCaseLevel());
tree.setStatus(caseInfo.getStatus());
tree.setUpdateTime(caseInfo.getUpdateTime());
tree.setCreateTime(caseInfo.getCreateTime());
tree.setUpdateUser(caseInfo.getUpdateUser());
tree.setCreateUser(caseInfo.getCreateUser());
tree.setSelected(0);
tree.setCaseDesc(caseInfo.getCaseDesc());
tree.setRunAfterId(caseInfo.getRunAfterId());
tree.setRunBeforeId(caseInfo.getRunBeforeId());
caseTreeList.add(tree);
}
List<NewCaseTree> result = listToTree(caseTreeList);
return Result.success(result);
} catch (Exception e) {
return Result.error(HttpStatus.ERROR, e.toString());
}
}
|
文承业
| |
Long userId = getCookie(request.getCookies(), "userId");
if (orderDetail.userId != userId){
return return CommonResult.fail(500, "无权查看订单");
}
|
conventional
|
@ApiOperation("根据ID获取订单详情")
@RequestMapping(value = "/detail/{orderId}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<OmsOrderDetail> detail(@PathVariable Long orderId) {
OmsOrderDetail orderDetail = portalOrderService.detail(orderId);
return CommonResult.success(orderDetail);
}
|
文承业
| |
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
NewBeeMallOrderDetailVO orderDetailVO = newBeeMallOrderService.getOrderDetailByOrderNo(orderNo, user.getUserId());
|
conventional
|
@GetMapping("/orders/{orderNo}")
public String orderDetailPage(HttpServletRequest request, @PathVariable("orderNo") String orderNo, HttpSession httpSession) {
NewBeeMallOrderDetailVO orderDetailVO = newBeeMallOrderService.getOrderDetailByOrderNo(orderNo);
request.setAttribute("orderDetailVO", orderDetailVO);
return "mall/order-detail";
}
|
文承业
| |
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
//判断订单userId
if (!user.getUserId().equals(newBeeMallOrder.getUserId())) {
NewBeeMallException.fail(ServiceResultEnum.NO_PERMISSION_ERROR.getResult());
}
|
conventional
|
@GetMapping("/selectPayType")
public String selectPayType(HttpServletRequest request, @RequestParam("orderNo") String orderNo, HttpSession httpSession) {
NewBeeMallOrder newBeeMallOrder = newBeeMallOrderService.getNewBeeMallOrderByOrderNo(orderNo);
//判断订单状态
if (newBeeMallOrder.getOrderStatus().intValue() != NewBeeMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus()) {
NewBeeMallException.fail(ServiceResultEnum.ORDER_STATUS_ERROR.getResult());
}
request.setAttribute("orderNo", orderNo);
request.setAttribute("totalPrice", newBeeMallOrder.getTotalPrice());
return "mall/pay-select";
}
|
文承业
| |
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
//判断订单userId
if (!user.getUserId().equals(newBeeMallOrder.getUserId())) {
NewBeeMallException.fail(ServiceResultEnum.NO_PERMISSION_ERROR.getResult());
}
|
conventional
|
@GetMapping("/payPage")
public String payOrder(HttpServletRequest request, @RequestParam("orderNo") String orderNo, HttpSession httpSession, @RequestParam("payType") int payType) {
NewBeeMallOrder newBeeMallOrder = newBeeMallOrderService.getNewBeeMallOrderByOrderNo(orderNo);
//判断订单状态
if (newBeeMallOrder.getOrderStatus().intValue() != NewBeeMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus()) {
NewBeeMallException.fail(ServiceResultEnum.ORDER_STATUS_ERROR.getResult());
}
request.setAttribute("orderNo", orderNo);
request.setAttribute("totalPrice", newBeeMallOrder.getTotalPrice());
if (payType == 1) {
return "mall/alipay";
} else {
return "mall/wxpay";
}
}
|
文承业
| |
int accessLevel = userPermissionFacade.getUserAccessLevel(SessionHolder.getUsername());
if (accessLevel < 100) {
log.warn("越权访问: 业务资源只有{SUPER_SA}才能访问!");
throw new AuthenticationException("越权访问: 业务资源只有{SUPER_SA}才能访问!");
}
|
conventional
|
public void interceptLoginServer(int serverId) {
Tag tag = tagService.getByTagKey(TagConstants.SUPER_ADMIN.getTag());
// SA标签不存在
if (tag == null) {
return;
}
BusinessTag bizTag = BusinessTag.builder()
.businessType(BusinessTypeEnum.SERVER.getType())
.businessId(serverId)
.tagId(tag.getId())
.build();
// 服务器未打SA标签
if (bizTagService.countByBusinessTag(bizTag) == 0) {
return;
}
log.info("SA Interceptor passed: serverId={}", serverId);
}
|
黄琛
| |
if (!loginUser.getUserId().equals(orderInfo.getUser_id())) {
return toResponseFail("越权操作!");
}
|
conventional
|
/**
* 获取订单详情
*/
@ApiOperation(value = "获取订单详情")
@PostMapping("detail")
public Object detail(Integer orderId, @LoginUser UserVo loginUser) {
Map resultObj = new HashMap();
//
OrderVo orderInfo = orderService.queryObject(orderId);
if (null == orderInfo) {
return toResponsObject(400, "订单不存在", "");
}
Map orderGoodsParam = new HashMap();
orderGoodsParam.put("order_id", orderId);
//订单的商品
List<OrderGoodsVo> orderGoods = orderGoodsService.queryList(orderGoodsParam);
//订单最后支付时间
if (orderInfo.getOrder_status() == 0) {
// if (moment().subtract(60, 'minutes') < moment(orderInfo.add_time)) {
// orderInfo.final_pay_time = moment("001234", "Hmmss").format("mm:ss")
// } else {
// //超过时间不支付,更新订单状态为取消
// }
}
//订单可操作的选择,删除,支付,收货,评论,退换货
Map handleOption = orderInfo.getHandleOption();
//
resultObj.put("orderInfo", orderInfo);
resultObj.put("orderGoods", orderGoods);
resultObj.put("handleOption", handleOption);
if (!StringUtils.isEmpty(orderInfo.getShipping_code()) && !StringUtils.isEmpty(orderInfo.getShipping_no())) {
// 快递
List Traces = apiKdniaoService.getOrderTracesByJson(orderInfo.getShipping_code(), orderInfo.getShipping_no());
resultObj.put("shippingList", Traces);
}
return toResponseSuccess(resultObj);
}
|
黄琛
|
/**
* @author lipengjun
* @email [email protected]
* @date 2017-08-15 08:03:41
*/
public class UserVo implements Serializable {
private static final long serialVersionUID = 1L;
//主键
private Long userId;
//会员名称
private String username;
//会员密码
private String password;
//性别
private Integer gender;
//出生日期
private Date birthday;
//注册时间
private Date register_time;
//最后登录时间
private Date last_login_time;
//最后登录Ip
private String last_login_ip;
//会员等级
private Integer user_level_id;
//别名
private String nickname;
//手机号码
private String mobile;
//注册Ip
private String register_ip;
//头像
private String avatar;
//微信Id
private String weixin_openid;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getRegister_time() {
return register_time;
}
public void setRegister_time(Date register_time) {
this.register_time = register_time;
}
public Date getLast_login_time() {
return last_login_time;
}
public void setLast_login_time(Date last_login_time) {
this.last_login_time = last_login_time;
}
public String getLast_login_ip() {
return last_login_ip;
}
public void setLast_login_ip(String last_login_ip) {
this.last_login_ip = last_login_ip;
}
public Integer getUser_level_id() {
return user_level_id;
}
public void setUser_level_id(Integer user_level_id) {
this.user_level_id = user_level_id;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getRegister_ip() {
return register_ip;
}
public void setRegister_ip(String register_ip) {
this.register_ip = register_ip;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getWeixin_openid() {
return weixin_openid;
}
public void setWeixin_openid(String weixin_openid) {
this.weixin_openid = weixin_openid;
}
}
|
if (!loginUser.getUserId().equals(orderInfo.getUser_id())) {
return toResponseFail("越权操作!");
}
|
conventional
|
@ApiOperation(value = "修改订单")
@PostMapping("updateSuccess")
public Object updateSuccess(Integer orderId, @LoginUser UserVo loginUser) {
OrderVo orderInfo = orderService.queryObject(orderId);
if (orderInfo == null) {
return toResponseFail("订单不存在");
} else if (orderInfo.getOrder_status() != 0) {
return toResponseFail("订单状态不正确orderStatus" + orderInfo.getOrder_status() + "payStatus" + orderInfo.getPay_status());
}
orderInfo.setId(orderId);
orderInfo.setPay_status(2);
orderInfo.setOrder_status(201);
orderInfo.setShipping_status(0);
orderInfo.setPay_time(new Date());
int num = orderService.update(orderInfo);
if (num > 0) {
return toResponseSuccess("修改订单成功");
} else {
return toResponseFail("修改订单失败");
}
}
|
黄琛
| |
if (!loginUser.getUserId().equals(orderVo.getUser_id())) {
return toResponseFail("越权操作!");
}
|
conventional
|
/**
* 取消订单
*/
@ApiOperation(value = "取消订单")
@PostMapping("cancelOrder")
public Object cancelOrder(Integer orderId, @LoginUser UserVo loginUser) {
try {
OrderVo orderVo = orderService.queryObject(orderId);
if (null == orderVo) {
return toResponseFail("订单不存在!");
}
if (orderVo.getOrder_status() == 300) {
return toResponseFail("已发货,不能取消");
} else if (orderVo.getOrder_status() == 301) {
return toResponseFail("已收货,不能取消");
}
// 需要退款
if (orderVo.getPay_status() == 2) {
WechatRefundApiResult result = WechatUtil.wxRefund(orderVo.getOrder_sn(),
0.01, 0.01);
if (result.getResult_code().equals("SUCCESS")) {
if (orderVo.getOrder_status() == 201) {
orderVo.setOrder_status(401);
} else if (orderVo.getOrder_status() == 300) {
orderVo.setOrder_status(402);
}
orderVo.setPay_status(4);
orderService.update(orderVo);
return toResponseSuccess("取消成功");
} else {
return toResponsObject(400, "取消成失败", "");
}
} else {
orderVo.setOrder_status(101);
orderService.update(orderVo);
return this.toResponseSuccess("取消成功");
}
} catch (Exception e) {
e.printStackTrace();
}
return toResponseFail("提交失败");
}
|
黄琛
| |
if (!loginUser.getUserId().equals(orderVo.getUser_id())) {
return toResponseFail("越权操作!");
}
|
conventional
|
/**
* 确认收货
*/
@ApiOperation(value = "确认收货")
@PostMapping("confirmOrder")
public Object confirmOrder(Integer orderId, @LoginUser UserVo loginUser) {
try {
OrderVo orderVo = orderService.queryObject(orderId);
if (null == orderVo) {
return toResponseFail("订单不存在!");
}
orderVo.setOrder_status(301);
orderVo.setShipping_status(2);
orderVo.setConfirm_time(new Date());
orderService.update(orderVo);
return this.toResponseSuccess("确认收货成功");
} catch (Exception e) {
e.printStackTrace();
}
return toResponseFail("提交失败");
}
|
黄琛
| |
@PermissionData(pageComponent = "system/UserList")
|
annotation
|
@RequestMapping(value = "/list", method = RequestMethod.GET)
public Result<IPage<SysUser>> queryPageList(SysUser user,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
//------------------------------------------------------------------------------------------------
//是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
String tenantId = oConvertUtils.getString(TenantContext.getTenant(), "0");
//update-begin---author:wangshuai ---date:20221223 for:[QQYUN-3371]租户逻辑改造,改成关系表------------
List<String> userIds = userTenantService.getUserIdsByTenantId(Integer.valueOf(tenantId));
if (oConvertUtils.listIsNotEmpty(userIds)) {
queryWrapper.in("id", userIds);
}else{
queryWrapper.eq("id", "通过租户查询不到任何用户");
}
//update-end---author:wangshuai ---date:20221223 for:[QQYUN-3371]租户逻辑改造,改成关系表------------
}
//------------------------------------------------------------------------------------------------
return sysUserService.queryPageList(req, queryWrapper, pageSize, pageNo);
}
|
万爽
| |
@EruptRouter(authIndex = 2, verifyType = EruptRouter.VerifyType.ERUPT)
|
annotation
|
@PostMapping("/auto-complete/{erupt}/{field}")
public List<Object> findAutoCompleteValue(@PathVariable("erupt") String eruptName,
@PathVariable("field") String field,
@RequestParam("val") String val,
@RequestBody(required = false) Map<String, Object> formData) {
EruptFieldModel fieldModel = EruptCoreService.getErupt(eruptName).getEruptFieldMap().get(field);
AutoCompleteType autoCompleteType = fieldModel.getEruptField().edit().autoCompleteType();
if (val.length() < autoCompleteType.triggerLength()) {
throw new EruptWebApiRuntimeException("char length must >= " + autoCompleteType.triggerLength());
}
try {
return EruptSpringUtil.getBean(autoCompleteType.handler()).completeHandler(formData, val, autoCompleteType.param());
} catch (Exception e) {
e.printStackTrace();
throw new EruptApiErrorTip(e.getMessage(), EruptApiModel.PromptWay.MESSAGE);
}
}
|
万爽
|
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
@Comment("接口菜单权限校验,仅对/erupt-api/**下的接口有效")
public @interface EruptRouter {
@Comment("根据请求地址'/'进行分隔,定义处于第几个下标为的字符为菜单权限标识字符")
int authIndex() default 0;
@Comment("配合authIndex使用,计算后权限下标位置为:skipAuthIndex + authIndex")
int skipAuthIndex() default 2;
@Comment("权限校验类型")
VerifyType verifyType();
@Comment("权限校验方式")
VerifyMethod verifyMethod() default EruptRouter.VerifyMethod.HEADER;
@Comment("定义路由校验规则")
Class<? extends VerifyHandler> verifyHandler() default VerifyHandler.class;
@Comment("自定义参数")
String[] params() default {};
enum VerifyMethod {
@Comment("token必须放在请求头")
HEADER,
@Comment("token必须放在URL参数中")
PARAM
}
enum VerifyType {
@Comment("仅验证是否登录")
LOGIN,
@Comment("验证登录与菜单权限")
MENU,
@Comment("验证登录与erupt权限")
ERUPT
}
interface VerifyHandler {
/**
* 动态转换授权菜单权限标识字符
*
* @param authStr 原始权限标识字符
* @return 新的权限字符
*/
default String convertAuthStr(EruptRouter eruptRouter, HttpServletRequest request, String authStr) {
return authStr;
}
}
}
|
@EruptRouter(authIndex = 2, verifyType = EruptRouter.VerifyType.ERUPT)
|
annotation
|
@GetMapping("/tags-item/{erupt}/{field}")
public List<String> findTagsItem(@PathVariable("erupt") String eruptName,
@PathVariable("field") String field) {
EruptFieldModel fieldModel = EruptCoreService.getErupt(eruptName).getEruptFieldMap().get(field);
return EruptUtil.getTagList(fieldModel.getEruptField().edit().tagsType());
}
|
万爽
|
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
@Comment("接口菜单权限校验,仅对/erupt-api/**下的接口有效")
public @interface EruptRouter {
@Comment("根据请求地址'/'进行分隔,定义处于第几个下标为的字符为菜单权限标识字符")
int authIndex() default 0;
@Comment("配合authIndex使用,计算后权限下标位置为:skipAuthIndex + authIndex")
int skipAuthIndex() default 2;
@Comment("权限校验类型")
VerifyType verifyType();
@Comment("权限校验方式")
VerifyMethod verifyMethod() default EruptRouter.VerifyMethod.HEADER;
@Comment("定义路由校验规则")
Class<? extends VerifyHandler> verifyHandler() default VerifyHandler.class;
@Comment("自定义参数")
String[] params() default {};
enum VerifyMethod {
@Comment("token必须放在请求头")
HEADER,
@Comment("token必须放在URL参数中")
PARAM
}
enum VerifyType {
@Comment("仅验证是否登录")
LOGIN,
@Comment("验证登录与菜单权限")
MENU,
@Comment("验证登录与erupt权限")
ERUPT
}
interface VerifyHandler {
/**
* 动态转换授权菜单权限标识字符
*
* @param authStr 原始权限标识字符
* @return 新的权限字符
*/
default String convertAuthStr(EruptRouter eruptRouter, HttpServletRequest request, String authStr) {
return authStr;
}
}
}
|
@EruptRouter(authIndex = 1, verifyType = EruptRouter.VerifyType.ERUPT)
|
annotation
|
@GetMapping("/{erupt}")
@SneakyThrows
public EruptBuildModel getEruptBuild(@PathVariable("erupt") String eruptName) {
EruptModel eruptView = EruptCoreService.getEruptView(eruptName);
{
//default search conditions
Map<String, Object> conditionsMap = new HashMap<>();
DataProxyInvoke.invoke(eruptView, it -> it.searchCondition(conditionsMap));
eruptView.setSearchCondition(conditionsMap);
}
EruptBuildModel eruptBuildModel = new EruptBuildModel();
eruptBuildModel.setPower(PowerInvoke.getPowerObject(eruptView));
eruptBuildModel.setEruptModel(eruptView);
eruptView.getEruptFieldModels().forEach(fieldModel -> {
switch (fieldModel.getEruptField().edit().type()) {
case TAB_TREE:
eruptBuildModel.setTabErupts(Optional.ofNullable(eruptBuildModel.getTabErupts()).orElse(new LinkedHashMap<>()));
EruptBuildModel m1 = new EruptBuildModel();
m1.setEruptModel(EruptCoreService.getEruptView(fieldModel.getFieldReturnName()));
eruptBuildModel.getTabErupts().put(fieldModel.getFieldName(), m1);
break;
case TAB_TABLE_ADD:
case TAB_TABLE_REFER:
eruptBuildModel.setTabErupts(Optional.ofNullable(eruptBuildModel.getTabErupts()).orElse(new LinkedHashMap<>()));
eruptBuildModel.getTabErupts().put(fieldModel.getFieldName(), getEruptBuild(fieldModel.getFieldReturnName()));
break;
case COMBINE:
eruptBuildModel.setCombineErupts(Optional.ofNullable(eruptBuildModel.getCombineErupts()).orElse(new LinkedHashMap<>()));
eruptBuildModel.getCombineErupts().put(fieldModel.getFieldName(), EruptCoreService.getEruptView(fieldModel.getFieldReturnName()));
break;
}
});
Arrays.stream(eruptBuildModel.getEruptModel().getErupt().rowOperation()).filter(operation ->
operation.eruptClass() != void.class && operation.type() == RowOperation.Type.ERUPT).forEach(operation -> {
eruptBuildModel.setOperationErupts(Optional.ofNullable(eruptBuildModel.getOperationErupts()).orElse(new LinkedHashMap<>()));
eruptBuildModel.getOperationErupts().put(operation.code(), EruptCoreService.getEruptView(operation.eruptClass().getSimpleName()));
});
return eruptBuildModel;
}
|
万爽
|
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
@Comment("接口菜单权限校验,仅对/erupt-api/**下的接口有效")
public @interface EruptRouter {
@Comment("根据请求地址'/'进行分隔,定义处于第几个下标为的字符为菜单权限标识字符")
int authIndex() default 0;
@Comment("配合authIndex使用,计算后权限下标位置为:skipAuthIndex + authIndex")
int skipAuthIndex() default 2;
@Comment("权限校验类型")
VerifyType verifyType();
@Comment("权限校验方式")
VerifyMethod verifyMethod() default EruptRouter.VerifyMethod.HEADER;
@Comment("定义路由校验规则")
Class<? extends VerifyHandler> verifyHandler() default VerifyHandler.class;
@Comment("自定义参数")
String[] params() default {};
enum VerifyMethod {
@Comment("token必须放在请求头")
HEADER,
@Comment("token必须放在URL参数中")
PARAM
}
enum VerifyType {
@Comment("仅验证是否登录")
LOGIN,
@Comment("验证登录与菜单权限")
MENU,
@Comment("验证登录与erupt权限")
ERUPT
}
interface VerifyHandler {
/**
* 动态转换授权菜单权限标识字符
*
* @param authStr 原始权限标识字符
* @return 新的权限字符
*/
default String convertAuthStr(EruptRouter eruptRouter, HttpServletRequest request, String authStr) {
return authStr;
}
}
}
|
@Permission(role = UserRole.ADMIN)
|
annotation
|
@GetMapping(path = "operate")
public ResVo<String> operate(@RequestParam(name = "articleId") Long articleId, @RequestParam(name = "operateType") Integer operateType) {
OperateArticleEnum operate = OperateArticleEnum.fromCode(operateType);
if (operate == OperateArticleEnum.EMPTY) {
return ResVo.fail(StatusEnum.ILLEGAL_ARGUMENTS_MIXED, operateType + "非法");
}
articleSettingService.operateArticle(articleId, operate);
return ResVo.ok("ok");
}
|
万爽
| |
@Permission(role = UserRole.ADMIN)
|
annotation
|
@RestController
@Api(value = "发布文章作者白名单管理控制器", tags = "作者白名单")
@RequestMapping(path = {"api/admin/author/whitelist"})
public class AuthorWhiteListController {
@Autowired
private AuthorWhiteListService articleWhiteListService;
@GetMapping(path = "get")
@ApiOperation(value = "白名单列表", notes = "返回作者白名单列表")
public ResVo<List<BaseUserInfoDTO>> whiteList() {
return ResVo.ok(articleWhiteListService.queryAllArticleWhiteListAuthors());
}
@GetMapping(path = "add")
@ApiOperation(value = "添加白名单", notes = "将指定作者加入作者白名单列表")
@ApiImplicitParam(name = "authorId", value = "传入需要添加白名单的作者UserId", required = true, allowEmptyValue = false, example = "1")
public ResVo<Boolean> addAuthor(@RequestParam("authorId") Long authorId) {
articleWhiteListService.addAuthor2ArticleWhitList(authorId);
return ResVo.ok(true);
}
@GetMapping(path = "remove")
@ApiOperation(value = "删除白名单", notes = "将作者从白名单列表")
@ApiImplicitParam(name = "authorId", value = "传入需要删除白名单的作者UserId", required = true, allowEmptyValue = false, example = "1")
public ResVo<Boolean> rmAuthor(@RequestParam("authorId") Long authorId) {
articleWhiteListService.removeAuthorFromArticleWhiteList(authorId);
return ResVo.ok(true);
}
}
|
万爽
| |
@Permission(role = UserRole.ADMIN)
|
annotation
|
@GetMapping(path = "delete")
public ResVo<String> delete(@RequestParam(name = "categoryId") Integer categoryId) {
categorySettingService.deleteCategory(categoryId);
return ResVo.ok("ok");
}
|
万爽
| |
@Permission(role = UserRole.ADMIN)
|
annotation
|
@GetMapping(path = "operate")
public ResVo<String> operate(@RequestParam(name = "categoryId") Integer categoryId,
@RequestParam(name = "pushStatus") Integer pushStatus) {
if (pushStatus != PushStatusEnum.OFFLINE.getCode() && pushStatus!= PushStatusEnum.ONLINE.getCode()) {
return ResVo.fail(StatusEnum.ILLEGAL_ARGUMENTS);
}
categorySettingService.operateCategory(categoryId, pushStatus);
return ResVo.ok("ok");
}
|
万爽
| |
@Permission(role = UserRole.ADMIN)
|
annotation
|
@PostMapping(path = "saveColumn")
public ResVo<String> saveColumn(@RequestBody ColumnReq req) {
columnSettingService.saveColumn(req);
return ResVo.ok("ok");
}
|
万爽
| |
@Permission(role = UserRole.ADMIN)
|
annotation
|
@PostMapping(path = "saveColumnArticle")
public ResVo<String> saveColumnArticle(@RequestBody ColumnArticleReq req) {
// 要求文章必须存在,且已经发布
ArticleDO articleDO = articleReadService.queryBasicArticle(req.getArticleId());
if (articleDO == null || articleDO.getStatus() == PushStatusEnum.OFFLINE.getCode()) {
return ResVo.fail(StatusEnum.ILLEGAL_ARGUMENTS_MIXED, "教程对应的文章不存在或未发布!");
}
columnSettingService.saveColumnArticle(req);
return ResVo.ok("ok");
}
|
万爽
| |
@Permission(role = UserRole.LOGIN)
|
annotation
|
@GetMapping(path = "home")
public String getUserHome(@RequestParam(name = "userId") Long userId,
@RequestParam(name = "homeSelectType", required = false) String homeSelectType,
@RequestParam(name = "followSelectType", required = false) String followSelectType,
Model model) {
UserHomeVo vo = new UserHomeVo();
vo.setHomeSelectType(StringUtils.isBlank(homeSelectType) ? HomeSelectEnum.ARTICLE.getCode() : homeSelectType);
vo.setFollowSelectType(StringUtils.isBlank(followSelectType) ? FollowTypeEnum.FOLLOW.getCode() : followSelectType);
UserStatisticInfoDTO userInfo = userService.queryUserInfoWithStatistic(userId);
vo.setUserHome(userInfo);
List<TagSelectDTO> homeSelectTags = homeSelectTags(vo.getHomeSelectType(), Objects.equals(userId, ReqInfoContext.getReqInfo().getUserId()));
vo.setHomeSelectTags(homeSelectTags);
userHomeSelectList(vo, userId);
model.addAttribute("vo", vo);
SpringUtil.getBean(SeoInjectService.class).initUserSeo(vo);
return "views/user/index";
}
|
万爽
| |
@Permission(role = UserRole.ADMIN)
|
annotation
|
@RequestMapping(path = "email")
public ResVo<String> email(EmailReqVo req) {
if (StringUtils.isBlank(req.getTo()) || req.getTo().indexOf("@") <= 0) {
return ResVo.fail(Status.newStatus(StatusEnum.ILLEGAL_ARGUMENTS_MIXED, "非法的邮箱接收人"));
}
if (StringUtils.isBlank(req.getTitle())) {
req.setTitle("技术派的测试邮件发送");
}
if (StringUtils.isBlank(req.getContent())) {
req.setContent("技术派的测试发送内容");
} else {
// 测试邮件内容,不支持发送邮件正文,避免出现垃圾情况
req.setContent(StringEscapeUtils.escapeHtml4(req.getContent()));
}
|
default
| |
@AuthorshipInterceptor(moduleName = Module.PORTFOLIO)
|
annotation
|
@PutMapping("/post")
public GlobalResult<Portfolio> update(@RequestBody Portfolio portfolio) {
if (portfolio.getIdPortfolio() == null || portfolio.getIdPortfolio() == 0) {
throw new IllegalArgumentException("作品集主键参数异常!");
}
User user = UserUtils.getCurrentUserByToken();
portfolio.setPortfolioAuthorId(user.getIdUser());
portfolio = portfolioService.postPortfolio(portfolio);
return GlobalResultGenerator.genSuccessResult(portfolio);
}
|
万爽
| |
@AuthorshipInterceptor(moduleName = Module.PORTFOLIO)
|
annotation
|
@GetMapping("/{idPortfolio}/unbind-articles")
public GlobalResult<PageInfo> unbindArticles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @RequestParam(defaultValue = "") String searchText, @PathVariable Long idPortfolio) {
if (idPortfolio == null || idPortfolio == 0) {
throw new IllegalArgumentException("作品集主键参数异常!");
}
User user = UserUtils.getCurrentUserByToken();
PageInfo pageInfo = portfolioService.findUnbindArticles(page, rows, searchText, idPortfolio, user.getIdUser());
return GlobalResultGenerator.genSuccessResult(pageInfo);
}
|
万爽
| |
if (idAuthor > 0) {
String authHeader = request.getHeader(JwtConstants.AUTHORIZATION);
if (StringUtils.isNotBlank(authHeader)) {
TokenUser tokenUser = UserUtils.getTokenUser(authHeader);
if (!idAuthor.equals(tokenUser.getIdUser())) {
boolean hasPermission = false;
if (Module.ARTICLE_TAG.equals(log.moduleName())) {
// 判断管理员权限
hasPermission = userMapper.hasAdminPermission(tokenUser.getAccount());
}
if (!hasPermission) {
throw new UnauthorizedException();
}
}
}
} else {
throw new BusinessException("参数异常");
}
}
|
conventional
|
@Before(value = "authorshipPointCut()")
public void doBefore(JoinPoint joinPoint) {
logger.info("检查作者身份 start ...");
String methodName = joinPoint.getSignature().getName();
Method method = currentMethod(joinPoint, methodName);
AuthorshipInterceptor log = method.getAnnotation(AuthorshipInterceptor.class);
if (Objects.nonNull(log)) {
boolean isArticle = true;
if (Module.PORTFOLIO.equals(log.moduleName())) {
isArticle = false;
}
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
String id;
Long idAuthor = 0L;
if (isAjax(request)) {
Object[] objects = joinPoint.getArgs();
JSONObject jsonObject;
if (objects[0] instanceof Integer) {
jsonObject = new JSONObject();
if (isArticle) {
jsonObject.put("idArticle", objects[0].toString());
} else {
jsonObject.put("idPortfolio", objects[0].toString());
}
} else {
jsonObject = JSONObject.parseObject(JSON.toJSONString(objects[0]));
}
if (Objects.nonNull(jsonObject)) {
if (isArticle) {
id = jsonObject.getString("idArticle");
Article article = articleService.findById(id);
if (Objects.nonNull(article)) {
idAuthor = article.getArticleAuthorId();
}
} else {
id = jsonObject.getString("idPortfolio");
Portfolio portfolio = portfolioService.findById(id);
if (Objects.nonNull(portfolio)) {
idAuthor = portfolio.getPortfolioAuthorId();
}
}
}
} else {
Map params = getParams(request);
if (params.isEmpty()) {
params = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
} else {
params.putAll((Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE));
}
if (isArticle) {
id = (String) params.get("idArticle");
Article article = articleService.findById(id);
if (Objects.nonNull(article)) {
idAuthor = article.getArticleAuthorId();
}
} else {
id = (String) params.get("idPortfolio");
Portfolio portfolio = portfolioService.findById(id);
if (Objects.nonNull(portfolio)) {
idAuthor = portfolio.getPortfolioAuthorId();
}
}
}
logger.info("检查作者身份 end ...");
}
|
万爽
| |
@SecurityInterceptor
|
annotation
|
@GetMapping("/detail/{idUser}")
public GlobalResult<UserInfoDTO> detail(@PathVariable Long idUser) {
UserInfoDTO userInfo = userService.findUserInfo(idUser);
return GlobalResultGenerator.genSuccessResult(userInfo);
}
|
万爽
| |
@SecurityInterceptor
|
annotation
|
@GetMapping("/detail/{idUser}/extend-info")
public GlobalResult<UserExtend> extendInfo(@PathVariable Long idUser) {
UserExtend userExtend = userService.findUserExtendInfo(idUser);
return GlobalResultGenerator.genSuccessResult(userExtend);
}
|
万爽
| |
@SecurityInterceptor
|
annotation
|
@PatchMapping("/update")
public GlobalResult<UserInfoDTO> updateUserInfo(@RequestBody UserInfoDTO user) throws ServiceException {
user = userService.updateUserInfo(user);
return GlobalResultGenerator.genSuccessResult(user);
}
|
万爽
| |
@SecurityInterceptor
|
annotation
|
@PatchMapping("/update-extend")
public GlobalResult<UserExtend> updateUserExtend(@RequestBody UserExtend userExtend) throws ServiceException {
userExtend = userService.updateUserExtend(userExtend);
return GlobalResultGenerator.genSuccessResult(userExtend);
}
|
万爽
| |
@SecurityInterceptor
|
annotation
|
@PatchMapping("/update-email")
public GlobalResult<Boolean> updateEmail(@RequestBody ChangeEmailDTO changeEmailDTO) throws ServiceException {
boolean flag = userService.updateEmail(changeEmailDTO);
return GlobalResultGenerator.genSuccessResult(flag);
}
|
万爽
| |
@SecurityInterceptor
|
annotation
|
@PatchMapping("/update-password")
public GlobalResult<Boolean> updatePassword(@RequestBody UpdatePasswordDTO updatePasswordDTO) {
boolean flag = userService.updatePassword(updatePasswordDTO);
return GlobalResultGenerator.genSuccessResult(flag);
}
|
万爽
| |
@SecurityInterceptor
|
annotation
|
@GetMapping("/login-records")
public GlobalResult<PageInfo<LoginRecord>> loginRecords(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @RequestParam Integer idUser) {
PageHelper.startPage(page, rows);
List<LoginRecord> list = loginRecordService.findLoginRecordByIdUser(idUser);
PageInfo<LoginRecord> pageInfo = new PageInfo<>(list);
return GlobalResultGenerator.genSuccessResult(pageInfo);
}
|
万爽
| |
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(hr, authentication.getCredentials(), authentication.getAuthorities()));
|
conventional
|
@PutMapping("/hr/info")
public RespBean updateHr(@RequestBody Hr hr, Authentication authentication) {
if (hrService.updateHr(hr) == 1) {
return RespBean.ok("更新成功!");
}
return RespBean.error("更新失败!");
}
|
万爽
| |
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(hr, authentication.getCredentials(), authentication.getAuthorities()));
|
conventional
|
@PostMapping("/hr/userface")
public RespBean updateHrUserface(MultipartFile file, Integer id,Authentication authentication) {
String fileId = FastDFSUtils.upload(file);
String url = nginxHost + fileId;
if (hrService.updateUserface(url, id) == 1) {
Hr hr = (Hr) authentication.getPrincipal();
hr.setUserface(url);
return RespBean.ok("更新成功!", url);
}
return RespBean.error("更新失败!");
}
|
万爽
| |
if (user == null) {
return ResultDTO.errorOf(CustomizeErrorCode.NO_LOGIN);
}
|
conventional
|
@ResponseBody
@RequestMapping(value = "/comment", method = RequestMethod.POST)
public Object post(@RequestBody CommentCreateDTO commentCreateDTO,
HttpServletRequest request) {
User user = (User) request.getSession().getAttribute("user");
if (user.getDisable() != null && user.getDisable() == 1) {
return ResultDTO.errorOf(CustomizeErrorCode.USER_DISABLE);
}
if (commentCreateDTO == null || StringUtils.isBlank(commentCreateDTO.getContent())) {
return ResultDTO.errorOf(CustomizeErrorCode.CONTENT_IS_EMPTY);
}
if (questionRateLimiter.reachLimit(user.getId())) {
return ResultDTO.errorOf(CustomizeErrorCode.RATE_LIMIT);
}
Comment comment = new Comment();
comment.setParentId(commentCreateDTO.getParentId());
comment.setContent(commentCreateDTO.getContent());
comment.setType(commentCreateDTO.getType());
comment.setGmtModified(System.currentTimeMillis());
comment.setGmtCreate(System.currentTimeMillis());
comment.setCommentator(user.getId());
comment.setLikeCount(0L);
commentService.insert(comment, user);
return ResultDTO.okOf();
}
|
万爽
|
·
|
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
return "redirect:/";
}
|
conventional
|
@GetMapping("/notification/{id}")
public String profile(HttpServletRequest request,
@PathVariable(name = "id") Long id) {
NotificationDTO notificationDTO = notificationService.read(id, user);
if (NotificationTypeEnum.REPLY_COMMENT.getType() == notificationDTO.getType()
|| NotificationTypeEnum.REPLY_QUESTION.getType() == notificationDTO.getType()) {
return "redirect:/question/" + notificationDTO.getOuterid();
} else {
return "redirect:/";
}
}
|
万爽
| |
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
return "redirect:/";
}
|
conventional
|
@GetMapping("/profile/{action}")
public String profile(HttpServletRequest request,
@PathVariable(name = "action") String action,
Model model,
@RequestParam(name = "page", defaultValue = "1") Integer page,
@RequestParam(name = "size", defaultValue = "5") Integer size) {
if ("questions".equals(action)) {
model.addAttribute("section", "questions");
model.addAttribute("sectionName", "我的提问");
PaginationDTO paginationDTO = questionService.list(user.getId(), page, size);
model.addAttribute("pagination", paginationDTO);
} else if ("replies".equals(action)) {
PaginationDTO paginationDTO = notificationService.list(user.getId(), page, size);
model.addAttribute("section", "replies");
model.addAttribute("pagination", paginationDTO);
model.addAttribute("sectionName", "最新回复");
}
return "profile";
}
|
万爽
| |
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
model.addAttribute("error", "用户未登录");
return "publish";
}
|
conventional
|
@PostMapping("/publish")
public String doPublish(
@RequestParam(value = "title", required = false) String title,
@RequestParam(value = "description", required = false) String description,
@RequestParam(value = "tag", required = false) String tag,
@RequestParam(value = "id", required = false) Long id,
HttpServletRequest request,
Model model) {
model.addAttribute("title", title);
model.addAttribute("description", description);
model.addAttribute("tag", tag);
model.addAttribute("tags", TagCache.get());
if (StringUtils.isBlank(title)) {
model.addAttribute("error", "标题不能为空");
return "publish";
}
if (StringUtils.length(title) > 50) {
model.addAttribute("error", "标题最多 50 个字符");
return "publish";
}
if (StringUtils.isBlank(description)) {
model.addAttribute("error", "问题补充不能为空");
return "publish";
}
if (StringUtils.isBlank(tag)) {
model.addAttribute("error", "标签不能为空");
return "publish";
}
String invalid = TagCache.filterInvalid(tag);
if (StringUtils.isNotBlank(invalid)) {
model.addAttribute("error", "输入非法标签:" + invalid);
return "publish";
}
if (user.getDisable() != null && user.getDisable() == 1) {
model.addAttribute("error", "操作被禁用,如有疑问请联系管理员");
return "publish";
}
if (questionRateLimiter.reachLimit(user.getId())) {
model.addAttribute("error", "操作太快,请求被限制");
return "publish";
}
Question question = new Question();
question.setTitle(title);
question.setDescription(description);
question.setTag(tag);
question.setCreator(user.getId());
question.setId(id);
questionService.createOrUpdate(question);
return "redirect:/";
}
|
万爽
| |
if (cookies != null && cookies.length != 0)
for (Cookie cookie : cookies) {
if (cookie.getName().equals("token") && StringUtils.isNotBlank(cookie.getValue())) {
String token = cookie.getValue();
UserExample userExample = new UserExample();
userExample.createCriteria()
.andTokenEqualTo(token);
List<User> users = userMapper.selectByExample(userExample);
if (users.size() != 0) {
HttpSession session = request.getSession();
session.setAttribute("user", users.get(0));
Long unreadCount = notificationService.unreadCount(users.get(0).getId());
session.setAttribute("unreadCount", unreadCount);
}
break;
}
}
|
conventional
|
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//设置 context 级别的属性
request.getServletContext().setAttribute("giteeRedirectUri", giteeRedirectUri);
request.getServletContext().setAttribute("githubRedirectUri", githubRedirectUri);
// 没有登录的时候也可以查看导航
for (AdPosEnum adPos : AdPosEnum.values()) {
request.getServletContext().setAttribute(adPos.name(), adService.list(adPos.name()));
}
Cookie[] cookies = request.getCookies();
return true;
}
|
万爽
| |
.antMatchers("/admin/**","/reg").hasRole("超级管理员")
|
conventional
|
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/category/all").authenticated()
.anyRequest().authenticated()//其他的路径都是登录后即可访问
.and().formLogin().loginPage("/login_page").successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
httpServletResponse.setContentType("application/json;charset=utf-8");
PrintWriter out = httpServletResponse.getWriter();
out.write("{\"status\":\"success\",\"msg\":\"登录成功\"}");
out.flush();
out.close();
}
})
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
httpServletResponse.setContentType("application/json;charset=utf-8");
PrintWriter out = httpServletResponse.getWriter();
out.write("{\"status\":\"error\",\"msg\":\"登录失败\"}");
out.flush();
out.close();
}
}).loginProcessingUrl("/login")
.usernameParameter("username").passwordParameter("password").permitAll()
.and().logout().permitAll().and().csrf().disable().exceptionHandling().accessDeniedHandler(getAccessDeniedHandler());
}
|
万爽
| |
if (adminUser == null) {
return "admin/login";
}
|
conventional
|
@GetMapping("/profile")
public String profile(HttpServletRequest request) {
Integer loginUserId = (int) request.getSession().getAttribute("loginUserId");
AdminUser adminUser = adminUserService.getUserDetailById(loginUserId);
request.setAttribute("path", "profile");
request.setAttribute("loginUserName", adminUser.getLoginUserName());
request.setAttribute("nickName", adminUser.getNickName());
return "admin/profile";
}
|
万爽
| |
if (requestServletPath.startsWith("/admin") && null == request.getSession().getAttribute("loginUser")) {
request.getSession().setAttribute("errorMsg", "请重新登陆");
response.sendRedirect(request.getContextPath() + "/admin/login");
return false;
}
|
conventional
|
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
String requestServletPath = request.getServletPath();
request.getSession().removeAttribute("errorMsg");
return true;
}
|
万爽
| |
// 防止横向越权
shipping.setUserId(userId);
|
conventional
|
@Override
public ServerResponse update(Integer userId, Shipping shipping) {
if (shipping == null) {
return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDescription());
}
int count = shippingMapper.updateByIdAndUserId(shipping);
if (count > 0) {
return ServerResponse.createBySuccessMessage("更新地址成功");
}
return ServerResponse.createByErrorMessage("更新地址失败");
}
|
万爽
| |
checkRole(user);
|
conventional
|
@Override
@Transactional
public void updateUserRole(SysUser user) {
if (StringUtils.isBlank(user.getPassword())) {
user.setPassword(null);
} else {
user.setPassword(passwordEncoder.encode(user.getPassword()));
}
baseMapper.updateById(user);
sysUserRoleMapper.delete(Wrappers.<SysUserRole>update().lambda().eq(SysUserRole::getUserId, user.getUserId()));
saveUserRoleList(user);
}
|
万爽
| |
// 防止横向越权,要校验用户的旧密码
int resCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
if (resCount == 0) {
return ServerResponse.createByError("旧密码错误");
}
|
conventional
|
@Override
public ServerResponse<String> resetPassword(String passwordNew, String passwordOld, User user) {
int resCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
if (resCount == 0) {
return ServerResponse.createByError("旧密码错误");
}
user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
int updateCount = userMapper.updateByPrimaryKeySelective(user);
if (updateCount > 0) {
return ServerResponse.createBySuccessMessage("密码更新成功");
} else
return ServerResponse.createByError("密码更新失败");
}
|
万爽
| |
@RequiresPermissions<method*start>org.apache.shiro.authz.annotation.RequiresPermissions<method*end>("sys:menu:edit")
|
annotation
|
@RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>(value<method*start>org.springframework.web.bind.annotation.RequestMapping.value<method*end> = "save")
public String save(Menu menu, Model model, RedirectAttributes redirectAttributes) {
if (!UserUtils.getUser().isAdmin()) {
addMessage(redirectAttributes, "越权操作,只有超级管理员才能添加或修改数据!");
return "redirect:" + adminPath + "/sys/role/?repage";
}
if (Global.isDemoMode()) {
addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/menu/";
}
if (!beanValidator(model, menu)) {
return form(menu, model);
}
systemService.saveMenu(menu);
addMessage(redirectAttributes, "保存菜单'" + menu.getName() + "'成功");
return "redirect:" + adminPath + "/sys/menu/";
}
|
万爽
| |
if (StringUtils.isBlank<method*start>org.apache.commons.lang3.StringUtils.isBlank<method*end>(hasAclReq.getUrl<method*start>com.momo.mapper.req.sysmain.HasAclReq.getUrl<method*end>())) {
return false;
}
String<method*start>java.lang.String<method*end> url = truncateUrlPage<method*start>com.momo.service.service.authority.CommonSysCoreService.truncateUrlPage<method*end>(hasAclReq.getUrl<method*start>com.momo.mapper.req.sysmain.HasAclReq.getUrl<method*end>());
List<method*start>java.util.List<method*end><AclDO> userAclList = getUserAclList(new DynamicMenuAuthorReq(), hasAclReq);
Set<method*start>java.util.Set<method*end><String<method*start>java.lang.String<method*end>> userAclIdSet = userAclList.stream<method*start>java.util.List.stream<method*end>().map<method*start>java.util.stream.Stream.map<method*end>(AclDO::getSysAclUrl).collect<method*start>java.util.stream.Stream.collect<method*end>(Collectors.toSet<method*start>java.util.stream.Collectors.toSet<method*end>());
// 规则:只要有一个权限点有权限,那么我们就认为有访问权限
for (String<method*start>java.lang.String<method*end> aclUrl : userAclIdSet) {
// 判断一个用户是否具有某个权限点的访问权限
if (StringUtils.isBlank<method*start>org.apache.commons.lang3.StringUtils.isBlank<method*end>(aclUrl)) {
// 权限点无效
continue;
}
if (url.equals<method*start>java.lang.String.equals<method*end>(aclUrl)) {
return true;
}
}
|
conventional
|
public boolean hasUrlAcl(HasAclReq<method*start>com.momo.mapper.req.sysmain.HasAclReq<method*end> hasAclReq) {
if (StringUtils.isBlank<method*start>org.apache.commons.lang3.StringUtils.isBlank<method*end>(hasAclReq.getUrl<method*start>com.momo.mapper.req.sysmain.HasAclReq.getUrl<method*end>())) {
return false;
}
String<method*start>java.lang.String<method*end> url = truncateUrlPage<method*start>com.momo.service.service.authority.CommonSysCoreService.truncateUrlPage<method*end>(hasAclReq.getUrl<method*start>com.momo.mapper.req.sysmain.HasAclReq.getUrl<method*end>());
List<method*start>java.util.List<method*end><AclDO> userAclList = getUserAclList(new DynamicMenuAuthorReq(), hasAclReq);
Set<method*start>java.util.Set<method*end><String<method*start>java.lang.String<method*end>> userAclIdSet = userAclList.stream<method*start>java.util.List.stream<method*end>().map<method*start>java.util.stream.Stream.map<method*end>(AclDO::getSysAclUrl).collect<method*start>java.util.stream.Stream.collect<method*end>(Collectors.toSet<method*start>java.util.stream.Collectors.toSet<method*end>());
return false;
}
|
万爽
| |
// 检查该权限是否已经获取
int i = ContextCompat.checkSelfPermission<method*start>android.support.v4.content.ContextCompat.checkSelfPermission<method*end>(context, permission);
// 权限是否已经 授权 GRANTED---授权 DINIED---拒绝
if (i == PackageManager.PERMISSION_GRANTED<method*start>android.content.pm.PackageManager.PERMISSION_GRANTED<method*end>) {
return true;
}
|
conventional
|
public static boolean checkPermission(Context<method*start>android.content.Context<method*end> context, @NonNull<method*start>android.support.annotation.NonNull<method*end> String permission) {
List<method*start>java.util.List<method*end><String> noPermission = new ArrayList<method*start>java.util.ArrayList<method*end><>();
if (i == PackageManager.PERMISSION_GRANTED<method*start>android.content.pm.PackageManager.PERMISSION_GRANTED<method*end>) {
return true;
}
return false;
}
|
万爽
| |
List<method*start>java.util.List<method*end><Long<method*start>java.lang.Long<method*end>> menuIdList = sysRoleMapper.queryAllMenuId(role.getCreateUserId());
if (!menuIdList.containsAll(role.getMenuIdList())) {
throw new RRException("新增角色的权限,已超出你的权限范围");
}
}
|
conventional
|
private void checkPrems(SysRole<method*start>com.suke.czx.modules.sys.entity.SysRole<method*end> role) {
// 如果不是超级管理员,则需要判断角色的权限是否超过自己的权限
if (role.getCreateUserId() == Constant.SUPER_ADMIN) {
return;
}
}
|
万爽
| |
// 防止横向越权,要校验一下这个用户的旧密码,一定要指定是这个用户.因为我们会查询一个count(1),如果不指定id,那么结果就是true啦count>0;
int resultCount = userMapper.checkPassword<method*start>com.mmall.dao.UserMapper.checkPassword<method*end>(MD5Util.MD5EncodeUtf8<method*start>com.mmall.util.MD5Util.MD5EncodeUtf8<method*end>(passwordOld), user.getId<method*start>com.mmall.pojo.User.getId<method*end>());
if (resultCount == 0) {
return ServerResponse.createByErrorMessage<method*start>com.mmall.common.ServerResponse.createByErrorMessage<method*end>("旧密码错误");
}
|
conventional
|
public ServerResponse<method*start>com.mmall.common.ServerResponse<method*end><String<method*start>java.lang.String<method*end>> resetPassword(String<method*start>java.lang.String<method*end> passwordOld, String<method*start>java.lang.String<method*end> passwordNew, User<method*start>com.mmall.pojo.User<method*end> user) {
user.setPassword<method*start>com.mmall.pojo.User.setPassword<method*end>(MD5Util.MD5EncodeUtf8<method*start>com.mmall.util.MD5Util.MD5EncodeUtf8<method*end>(passwordNew));
int updateCount = userMapper.updateByPrimaryKeySelective<method*start>com.mmall.dao.UserMapper.updateByPrimaryKeySelective<method*end>(user);
if (updateCount > 0) {
return ServerResponse.createBySuccessMessage<method*start>com.mmall.common.ServerResponse.createBySuccessMessage<method*end>("密码更新成功");
}
return ServerResponse.createByErrorMessage<method*start>com.mmall.common.ServerResponse.createByErrorMessage<method*end>("密码更新失败");
}
|
万爽
| |
// 防止横向越权,要校验一下这个用户的旧密码,一定要指定是这个用户.因为我们会查询一个count(1),如果不指定id,那么结果就是true啦count>0;
int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
if (resultCount == 0) {
return ServerResponse.createByErrorMessage("旧密码错误");
}
|
conventional
|
@Override
public ServerResponse<java.lang.String> resetPassword(String passwordOld, String passwordNew, User user) {
int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
if (resultCount == 0) {
return ServerResponse.createByErrorMessage("旧密码错误");
}
user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
int updateCount = userMapper.updateByPrimaryKeySelective(user);
if (updateCount > 0) {
return ServerResponse.createBySuccessMessage("密码更新成功");
}
return ServerResponse.createByErrorMessage("密码更新失败");
}
|
万爽
| |
if (!status) {
response.setStatus<method*start>javax.servlet.http.HttpServletResponse.setStatus<method*end>(403);
return Hret.error<method*start>com.asofdate.utils.Hret.error<method*end>(403, "您没有权限修改域[" + domainid + "]的授权信息", null);
}
|
conventional
|
@RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>(method<method*start>org.springframework.web.bind.annotation.RequestMapping.method<method*end> = RequestMethod.POST<method*start>org.springframework.web.bind.annotation.RequestMethod.POST<method*end>)
public String<method*start>java.lang.String<method*end> add(HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response, HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request) {
ShareDomainEntity<method*start>com.asofdate.hauth.entity.ShareDomainEntity<method*end> arg = parse<method*start>com.asofdate.hauth.controller.ShareDomainController.parse<method*end>(request);
String<method*start>java.lang.String<method*end> domainid = arg.getDomain_id<method*start>com.asofdate.hauth.entity.ShareDomainEntity.getDomain_id<method*end>();
Boolean<method*start>java.lang.Boolean<method*end> status = authService.domainAuth<method*start>com.asofdate.hauth.service.AuthService.domainAuth<method*end>(request, domainid, "w").getStatus<method*start>com.asofdate.hauth.dto.AuthDTO.getStatus<method*end>();
if (arg == null) {
return Hret.error<method*start>com.asofdate.utils.Hret.error<method*end>(421, "解析参数失败", null);
}
int size = shareDomainService.add<method*start>com.asofdate.hauth.service.ShareDomainService.add<method*end>(arg);
if (size == 1) {
return Hret.success<method*start>com.asofdate.utils.Hret.success<method*end>(200, "success", null);
}
response.setStatus<method*start>javax.servlet.http.HttpServletResponse.setStatus<method*end>(421);
return Hret.error<method*start>com.asofdate.utils.Hret.error<method*end>(421, "授权域权限信息失败,请联系管理员", null);
}
|
万爽
| |
@RequiresPermissions("permission:delete")
|
annotation
|
public Result delete(@RequestParam long id) {
SysPermission sysPermission = sysPermissionService.selectById(id);
if (sysPermission == null) {
return Result.error(ResponseCode.data_not_exist.getMsg());
}
if (sysPermission.getIsFinal() == 2) {
return Result.error(ResponseCode.can_not_edit.getMsg());
}
sysPermission.setStatus(2);
// TODO: 2016/10/26 级联删除关联表 ,角色权限,用户权限
sysPermissionService.update(sysPermission);
return Result.success();
}
|
万爽
| |
Preconditions.checkNotNull(acl, "还原前的权限点为空,无法还原");
Preconditions.checkNotNull(before, "待还原的权限点不存在");
|
conventional
|
@Override
public void recover(int targetId, Object o) {
SysAcl acl = (SysAcl) o;
SysAcl before = sysAclDao.findById(targetId);
if (checkExist(acl.getAclModuleId(), acl.getName(), acl.getId())) {
throw new ParaException("当前模块下存在相同名称的权限点");
}
sysAclDao.update(acl);
sysLogService.saveAclLog(before, acl);
}
|
万爽
| |
if (!hasPermissions(mContext, permissions)) {
// 需要向用户解释为什么申请这个权限
boolean shouldShowRationale = false;
for (Stringjava.lang.String perm : permissions) {
shouldShowRationale = shouldShowRationale || shouldShowRequestPermissionRationale(mContext, perm);
}
executePermissionsRequest(mContext, permissions, REQUEST_PERMISSION_CODE);
}
|
conventional
|
public void requestPermissions(@NonNull android.support.annotation.NonNull CharSequence hintMessage, @Nullable android.support.annotation.Nullable PermissionListener listener, @NonNullandroid.support.annotation.NonNull final Stringjava.lang.String... permissions) {
if (listener != null) {
mListener = listener;
}
mPermissionList = Arrays.asList(permissions);
// 没全部权限
if (!hasPermissions(mContext, permissions)) {
// 需要向用户解释为什么申请这个权限
boolean shouldShowRationale = false;
for (Stringjava.lang.String perm : permissions) {
shouldShowRationale = shouldShowRationale || shouldShowRequestPermissionRationale(mContext, perm);
}
executePermissionsRequest(mContext, permissions, REQUEST_PERMISSION_CODE);
} else if (mListener != null) {
// 有全部权限
mListener.doAfterGrand(permissions);
}
}
|
万爽
| |
@RequiresPermissions("role:edit")
|
annotation
|
@GetMapping("/edit")
public String edit(Integer id, Model model) {
model.addAttribute("role", roleService.selectById(id));
model.addAttribute("currentPermissions", permissionService.selectByRoleId(id));
model.addAttribute("permissions", permissionService.selectAll());
return "admin/role/edit";
}
|
万爽
| |
Boolean<method*start>java.lang.Boolean<method*end> status = authService.domainAuth<method*start>com.asofdate.hauth.service.AuthService.domainAuth<method*end>(request, domainId, "w").getStatus<method*start>com.asofdate.hauth.dto.AuthDTO.getStatus<method*end>();
if (!status) {
response.setStatus<method*start>javax.servlet.http.HttpServletResponse.setStatus<method*end>(403);
return Hret.error<method*start>com.asofdate.utils.Hret.error<method*end>(403, "您没有权限修改域[" + domainId + "]的授权信息", null);
}
|
conventional
|
@RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>(method<method*start>org.springframework.web.bind.annotation.RequestMapping.method<method*end> = RequestMethod.PUT<method*start>org.springframework.web.bind.annotation.RequestMethod.PUT<method*end>)
public String<method*start>java.lang.String<method*end> update(HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response, HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request) {
ShareDomainEntity<method*start>com.asofdate.hauth.entity.ShareDomainEntity<method*end> arg = parse<method*start>com.asofdate.hauth.controller.ShareDomainController.parse<method*end>(request);
if (arg == null) {
return Hret.error<method*start>com.asofdate.utils.Hret.error<method*end>(421, "解析参数失败", null);
}
String<method*start>java.lang.String<method*end> domainId = arg.getDomain_id<method*start>com.asofdate.hauth.entity.ShareDomainEntity.getDomain_id<method*end>();
int size = shareDomainService.update<method*start>com.asofdate.hauth.service.ShareDomainService.update<method*end>(arg);
if (size == 1) {
return Hret.success<method*start>com.asofdate.utils.Hret.success<method*end>(200, "success", null);
}
response.setStatus<method*start>javax.servlet.http.HttpServletResponse.setStatus<method*end>(421);
return Hret.error<method*start>com.asofdate.utils.Hret.error<method*end>(421, "更新域权限信息失败,请联系管理员", null);
}
|
万爽
| |
if (handler instanceof HandlerMethod) {
SSOToken token = SSOHelper.attrToken(request);
if (token == null) {
return true;
}
try {
return unauthorizedAccess(request, response);
} catch (Exception e) {
throw AoomsExceptions.create(e.getMessage(), e);
}
}
|
conventional
|
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
return true;
}
|
万爽
| |
if (user == null) {
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
}
if (iUserService.checkAdminRole(user).isSuccess()) {
// 0->10000->100000
return iCategoryService.selectCategoryAndChildrenById(categoryId);
} else {
return ServerResponse.createByErrorMessage("无权限操作,需要管理员权限");
}
|
conventional
|
@RequestMapping("get_deep_category.do")
public ServerResponse<com.mmall.common.ServerResponse> getCategoryAndDeepChildrenCategory(HttpSession session, @RequestParam(value = "categoryId", defaultValue = "0") Integer categoryId) {
}
|
万爽
| |
if (SSOConfig.getInstance().isPermissionUri()) {
String uri = request.getRequestURI();
if (uri == null || this.getAuthorization().isPermitted(token, uri)) {
return true;
}
}
|
conventional
|
protected boolean isVerification(HttpServletRequest request, Object handler, SSOToken token) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
Permission pm = method.getAnnotation(Permission.class);
if (pm != null) {
if (pm.action() == Action.Skip) {
/**
* 忽略拦截
*/
return true;
} else if (!"".equals(pm.value()) && this.getAuthorization().isPermitted(token, pm.value())) {
/**
* 权限合法
*/
return true;
}
} else if (this.isNothingAnnotationPass()) {
/**
* 无注解情况下,设置为true,不进行期限验证
*/
return true;
}
/**
* 非法访问
*/
return false;
}
|
万爽
| |
if (uuid == null) {
throw BizException.fail<method*start>com.momo.common.core.error.BizException.fail<method*end>("用户所在的企业不存在");
}
UserDO userDO = userMapper.uuid<method*start>com.momo.mapper.mapper.manual.UserMapper.uuid<method*end>(sysEnterpriseUserReq.getUuid<method*start>com.momo.mapper.req.aclmanager.SysEnterpriseUserReq.getUuid<method*end>());
if (null == userDO) {
throw BizException.fail<method*start>com.momo.common.core.error.BizException.fail<method*end>("待授权的用户不存在");
}
List<method*start>java.util.List<method*end><Long<method*start>java.lang.Long<method*end>> originAclIdList = authorityMapper.rolesByUserId<method*start>com.momo.mapper.mapper.manual.AuthorityMapper.rolesByUserId<method*end>(userDO.getId<method*start>com.momo.mapper.dataobject.UserDO.getId<method*end>());
if (originAclIdList.size<method*start>java.util.List.size<method*end>() == roles.size<method*start>java.util.List.size<method*end>()) {
Set<method*start>java.util.Set<method*end><Long<method*start>java.lang.Long<method*end>> originAclIdSet = Sets.newHashSet<method*start>com.google.common.collect.Sets.newHashSet<method*end>(originAclIdList);
Set<method*start>java.util.Set<method*end><Long<method*start>java.lang.Long<method*end>> aclIdSet = Sets.newHashSet<method*start>com.google.common.collect.Sets.newHashSet<method*end>(roles);
originAclIdSet.removeAll<method*start>java.util.Set.removeAll<method*end>(aclIdSet);
if (CollectionUtils.isEmpty<method*start>org.apache.commons.collections4.CollectionUtils.isEmpty<method*end>(originAclIdSet)) {
return "为企业用户授权角色成功";
}
}
|
conventional
|
public String<method*start>java.lang.String<method*end> rolesToUser(SysEnterpriseUserReq<method*start>com.momo.mapper.req.aclmanager.SysEnterpriseUserReq<method*end> sysEnterpriseUserReq) {
UserGroupDO<method*start>com.momo.mapper.dataobject.UserGroupDO<method*end> uuid = userGroupMapper.uuid<method*start>com.momo.mapper.mapper.manual.UserGroupMapper.uuid<method*end>(sysEnterpriseUserReq.getEnterpriseUuid<method*start>com.momo.mapper.req.aclmanager.SysEnterpriseUserReq.getEnterpriseUuid<method*end>());
}
|
万爽
| |
if (perms != null && perms.length > 0) {
if (perms.length == 1) {
if (!subject.isPermitted(perms[0])) {
log.debug("授权认证:未通过");
isPermitted = false;
}
} else {
if (!subject.isPermittedAll(perms)) {
log.debug("授权认证:未通过");
isPermitted = false;
}
}
}
|
conventional
|
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
Subject subject = getSubject(request, response);
String[] perms = (String[]) mappedValue;
boolean isPermitted = true;
return isPermitted;
}
|
万爽
| |
String<method*start>java.lang.String<method*end>[] methods = e.getSupportedMethods<method*start>org.springframework.web.HttpRequestMethodNotSupportedException.getSupportedMethods<method*end>();
if (methods != null) {
for (String<method*start>java.lang.String<method*end> str : methods) {
sb.append<method*start>java.lang.StringBuffer.append<method*end>(str);
sb.append<method*start>java.lang.StringBuffer.append<method*end>("、");
}
}
|
conventional
|
@ExceptionHandler<method*start>org.springframework.web.bind.annotation.ExceptionHandler<method*end>(HttpRequestMethodNotSupportedException<method*start>org.springframework.web.HttpRequestMethodNotSupportedException<method*end>.class)
public Result<method*start>org.jeecg.common.api.vo.Result<method*end><?> HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException<method*start>org.springframework.web.HttpRequestMethodNotSupportedException<method*end> e) {
log.error<method*start>org.slf4j.Logger.error<method*end>(sb.toString<method*start>java.lang.StringBuffer.toString<method*end>(), e);
// return Result.error("没有权限,请联系管理员授权");
return Result.error<method*start>org.jeecg.common.api.vo.Result.error<method*end>(405, sb.toString<method*start>java.lang.StringBuffer.toString<method*end>());
}
|
万爽
| |
if (!aclReq.getSysAclParentIdStr().equals(0L)) {
if (null == aclDO) {
throw BizException.fail("父权限不存在");
}
if (!before.getSysAclPermissionCode().equals(aclDO.getSysAclPermissionCode())) {
throw BizException.fail("无法跨模块编辑");
}
after.setSysAclLevel(LevelUtil.calculateLevel(aclDO.getSysAclLevel(), aclReq.getSysAclParentIdStr()));
} else {
after.setSysAclLevel("0");
}
if (checkUrl(aclReq.getSysAclUrl(), aclReq.getSysAclPermissionCode(), before.getId())) {
throw BizException.fail("url重复");
}
if (!aclReq.getSysAclParentIdStr().equals(0L) && !before.getSysAclPermissionCode().equals(aclReq.getSysAclPermissionCode())) {
throw BizException.fail("权限码不允许编辑");
}
|
conventional
|
@Transactional
public String updateByPrimaryKeySelective(AclReq aclReq) {
AclDO before = aclMapper.selectByPrimaryUuid(aclReq.getUuid());
if (null == before) {
throw BizException.fail("待编辑的权限不存在");
}
if (before.getId().equals(aclReq.getSysAclParentIdStr())) {
throw BizException.fail("无法将当前模块挂在自己模块下");
}
AclDO after = new AclDO();
BeanUtils.copyProperties(aclReq, after);
RedisUser redisUser = this.redisUser();
AclDO aclDO = aclMapper.selectByPrimaryKey(aclReq.getSysAclParentIdStr());
after.setUpdateBy(redisUser.getSysUserName());
after.setUpdateTime(DateUtils.getDateTime());
after.setId(before.getId());
after.setSysAclParentId(aclReq.getSysAclParentIdStr());
after.setSysAclPermissionCode(before.getSysAclPermissionCode());
updateWithChild(before, after);
return "编辑权限成功";
}
|
万爽
| |
String authorizeToken = ServerExtConfigBean.getInstance().getAuthorizeToken();
if (StrUtil.isEmpty(authorizeToken)) {
return;
}
if (authorizeToken.length() < 6) {
DefaultSystemLog.getLog().error("", new JpomRuntimeException("配置的授权token长度小于六位不生效"));
System.exit(-1);
}
int password = CheckPassword.checkPassword(authorizeToken);
if (password != 2) {
DefaultSystemLog.getLog().error("", new JpomRuntimeException("配置的授权token 需要包含数字,字母,符号的组合"));
System.exit(-1);
}
|
conventional
|
@PreLoadMethod
private static void check() {
}
|
万爽
| |
if (!this.client.doesBucketExist(bucketName)) {
throw new OssApiException("[阿里云OSS] 无法获取文件的访问权限!Bucket不存在:" + bucketName);
}
if (!this.client.doesObjectExist(bucketName, fileName)) {
throw new OssApiException("[阿里云OSS] 无法获取文件的访问权限!文件不存在:" + bucketName + "/" + fileName);
}
|
conventional
|
public Object getFileAcl(String fileName, String bucketName) {
return this.client.getObjectAcl(bucketName, fileName).getPermission();
this.shutdown();
}
|
万爽
| |
if (StrUtil.isNullOrEmpty(name)) {
throw new NullPointerException("获取API权限验证实现-->失败:工厂名字不能为空");
}
if (SESSION_TOKEN_AUTH.equalsIgnoreCase(name)) {
return new VxApiAuthSessionTokenImpl(options);
}
if (JWT_TOKEN_AUTH.equalsIgnoreCase(name)) {
return new VxApiAuthJwtTokenImpl(options);
}
|
conventional
|
public static VxApiAuth getVxApiAuth(String name, JsonObject options, VxApis api, HttpClient httpClient) throws NullPointerException, ClassNotFoundException {
throw new ClassNotFoundException("没有找到名字为 : " + name + " 的API权限验证实现类");
}
|
万爽
| |
if (imMgr.validation<method*start>com.tencent.qcloud.roomservice.logic.IMMgr.validation<method*end>(userID, token) != 0) {
rsp.setCode<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp.setCode<method*end>(7);
rsp.setMessage<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp.setMessage<method*end>("请求失败,鉴权失败");
log.error<method*start>org.slf4j.Logger.error<method*end>("getPushUrl失败:鉴权失败:" + "userID:" + userID);
return rsp;
}
|
conventional
|
@Override
public GetPushUrlRsp<method*start>com.tencent.qcloud.roomservice.pojo.Response.GetPushUrlRsp<method*end> getPushUrl(String<method*start>java.lang.String<method*end> userID, String<method*start>java.lang.String<method*end> token) {
GetPushUrlRsp<method*start>com.tencent.qcloud.roomservice.pojo.Response.GetPushUrlRsp<method*end> rsp = new GetPushUrlRsp<method*start>com.tencent.qcloud.roomservice.pojo.Response.GetPushUrlRsp<method*end>();
if (userID == null || token == null) {
rsp.setCode<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp.setCode<method*end>(2);
rsp.setMessage<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp.setMessage<method*end>("请求失败,缺少参数");
log.error<method*start>org.slf4j.Logger.error<method*end>("getPushUrl失败:缺少参数:" + "userID:" + userID + ",token: " + token);
return rsp;
}
rsp.setPushURL<method*start>com.tencent.qcloud.roomservice.pojo.Response.GetPushUrlRsp.setPushURL<method*end>(liveUtil.genPushUrl<method*start>com.tencent.qcloud.roomservice.logic.LiveUtil.genPushUrl<method*end>(userID));
return rsp;
}
|
万爽
| |
// 没有权限
if (isAjax((HttpServletRequest) request)) {
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = response.getWriter();
Map<String, Object> map = new HashMap<>();
map.put("code", 0);
map.put("msg", "没有权限访问");
writer.write(JSONObject.toJSONString(map));
} else {
WebUtils.issueRedirect(request, response, "/403");
}
|
conventional
|
@Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
// 请求的url
String requestURL = getPathWithinApplication(request);
System.out.println("请求的url :" + requestURL);
Subject subject = SecurityUtils.getSubject();
if (!subject.isAuthenticated()) {
// 如果没有登录, 进入登录流程
WebUtils.issueRedirect(request, response, "/admin/login");
return false;
}
// 从session里读取当前用户的权限URL列表
Set<String> urls = (Set<String>) subject.getSession().getAttribute("permissionUrls");
if (urls.contains(requestURL)) {
return true;
}
return false;
}
|
万爽
| |
this.checkAuthorityRole(noticeAuthorityRole.getNoticeId(), noticeAuthorityRole.getRole().getId())
|
conventional
|
public void saveTSNoticeAuthorityRole(TSNoticeAuthorityRole noticeAuthorityRole) {
if (this.checkAuthorityRole(noticeAuthorityRole.getNoticeId(), noticeAuthorityRole.getRole().getId())) {
throw new BusinessException("该角色已授权,请勿重复操作。");
} else {
final String noticeId = noticeAuthorityRole.getNoticeId();
final String roleId = noticeAuthorityRole.getRole().getId();
executor.execute(new Runnable() {
@Override
public void run() {
String hql = "from TSRoleUser roleUser where roleUser.TSRole.id = ?";
List<TSRoleUser> roleUserList = systemService.findHql(hql, roleId);
for (TSRoleUser roleUser : roleUserList) {
String userId = roleUser.getTSUser().getId();
String noticeReadHql = "from TSNoticeReadUser where noticeId = ? and userId = ?";
List<TSNoticeReadUser> noticeReadList = systemService.findHql(noticeReadHql, noticeId, userId);
if (noticeReadList == null || noticeReadList.isEmpty()) {
// 未授权过的消息,添加授权记录
TSNoticeReadUser noticeRead = new TSNoticeReadUser();
noticeRead.setNoticeId(noticeId);
noticeRead.setUserId(userId);
noticeRead.setCreateTime(new Date());
systemService.save(noticeRead);
} else if (noticeReadList.size() > 0) {
for (TSNoticeReadUser readUser : noticeReadList) {
if (readUser.getDelFlag() == 1) {
readUser.setDelFlag(0);
systemService.updateEntitie(readUser);
}
}
}
}
roleUserList.clear();
}
});
this.save(noticeAuthorityRole);
}
|
万爽
| |
if (user.isAdmin<method*start>com.dimple.project.system.domain.SysUser.isAdmin<method*end>()) {
roles.add<method*start>java.util.Set.add<method*end>("admin");
} else {
roles.addAll<method*start>java.util.Set.addAll<method*end>(roleService.selectRolePermissionByUserId<method*start>com.dimple.project.system.service.RoleService.selectRolePermissionByUserId<method*end>(user.getId<method*start>com.dimple.project.system.domain.SysUser.getId<method*end>()));
}
|
conventional
|
public Set<method*start>java.util.Set<method*end><String<method*start>java.lang.String<method*end>> getRolePermission(SysUser<method*start>com.dimple.project.system.domain.SysUser<method*end> user) {
Set<method*start>java.util.Set<method*end><String<method*start>java.lang.String<method*end>> roles = new HashSet<method*start>java.util.HashSet<method*end><>();
roles.add<method*start>java.util.Set.add<method*end>("admin");
roles.addAll<method*start>java.util.Set.addAll<method*end>(roleService.selectRolePermissionByUserId<method*start>com.dimple.project.system.service.RoleService.selectRolePermissionByUserId<method*end>(user.getId<method*start>com.dimple.project.system.domain.SysUser.getId<method*end>()));
return roles;
}
|
万爽
| |
if (userID == null || token == null) {
rsp.setCode(2);
rsp.setMessage("请求失败,缺少参数");
log.error("logout失败:缺少参数:" + "userID:" + userID + ",token: " + token);
return rsp;
}
if (imMgr.validation(userID, token) != 0) {
rsp.setCode(7);
rsp.setMessage("请求失败,鉴权失败");
log.error("logout失败:鉴权失败:" + "userID:" + userID);
return rsp;
}
|
conventional
|
@Override
public BaseRsp logout(String userID, String token) {
BaseRsp rsp = new BaseRsp();
// 删除session
imMgr.delLoginSession(userID);
return rsp;
}
|
万爽
| |
if (isPermitted(request, path)) {
return true;
} else {
responseJson(response, SsoResultCode.SSO_PERMISSION_ERROR, '没有访问权限');
return false;
}
|
conventional
|
@Override
public boolean isAccessAllowed(HttpServletRequest request, HttpServletResponse response) throws IOException {
String path = request.getServletPath();
return true;
}
|
万爽
| |
if (securityDigest != null) {
if (!sysUsers.getSecurityDigest<method*start>cms.bean.staff.SysUsers.getSecurityDigest<method*end>().equals<method*start>java.lang.String.equals<method*end>(securityDigest)) {
throw new AccessDeniedException<method*start>org.springframework.security.access.AccessDeniedException<method*end>("没有权限访问");
}
} else {
throw new AccessDeniedException<method*start>org.springframework.security.access.AccessDeniedException<method*end>("没有权限访问");
}
}
|
conventional
|
public void decide(Authentication<method*start>org.springframework.security.core.Authentication<method*end> authentication, Object<method*start>java.lang.Object<method*end> object, Collection<method*start>java.util.Collection<method*end><ConfigAttribute<method*start>org.springframework.security.access.ConfigAttribute<method*end>> configAttributes) throws AccessDeniedException<method*start>org.springframework.security.access.AccessDeniedException<method*end>, InsufficientAuthenticationException<method*start>org.springframework.security.authentication.InsufficientAuthenticationException<method*end> {
if (configAttributes == null) {
return;
}
Object<method*start>java.lang.Object<method*end> obj = SecurityContextHolder.getContext<method*start>org.springframework.security.core.context.SecurityContextHolder.getContext<method*end>().getAuthentication<method*start>org.springframework.security.core.context.SecurityContext.getAuthentication<method*end>().getPrincipal<method*start>org.springframework.security.core.Authentication.getPrincipal<method*end>();
if (obj instanceof SysUsers) {
SysUsers sysUsers = (SysUsers) obj;
String<method*start>java.lang.String<method*end> userAccount = sysUsers.getUserAccount<method*start>cms.bean.staff.SysUsers.getUserAccount<method*end>();
String<method*start>java.lang.String<method*end> securityDigest = staffManage.query_staffSecurityDigest<method*start>cms.web.action.staff.StaffManage.query_staffSecurityDigest<method*end>(userAccount);
// 所请求的资源拥有的权限(一个资源对多个权限)
Iterator<method*start>java.util.Iterator<method*end><ConfigAttribute<method*start>org.springframework.security.access.ConfigAttribute<method*end>> ite = configAttributes.iterator<method*start>java.util.Collection.iterator<method*end>();
while (ite.hasNext<method*start>java.util.Iterator.hasNext<method*end>()) {
ConfigAttribute<method*start>org.springframework.security.access.ConfigAttribute<method*end> ca = ite.next<method*start>java.util.Iterator.next<method*end>();
// 访问所请求资源所需要的权限
String<method*start>java.lang.String<method*end> needRole = ((SecurityConfig<method*start>org.springframework.security.access.SecurityConfig<method*end>) ca).getAttribute<method*start>org.springframework.security.access.SecurityConfig.getAttribute<method*end>();
// ga 为用户所被赋予的权限。 needRole 为访问相应的资源应该具有的权限。
for (GrantedAuthority<method*start>org.springframework.security.core.GrantedAuthority<method*end> ga : authentication.getAuthorities<method*start>org.springframework.security.core.Authentication.getAuthorities<method*end>()) {
if (needRole.trim<method*start>java.lang.String.trim<method*end>().equals<method*start>java.lang.String.equals<method*end>(ga.getAuthority<method*start>org.springframework.security.core.GrantedAuthority.getAuthority<method*end>().trim<method*start>java.lang.String.trim<method*end>())) {
return;
}
}
}
throw new AccessDeniedException<method*start>org.springframework.security.access.AccessDeniedException<method*end>("没有权限访问");
}
|
万爽
| |
// 调用设置管理员权限的方法
int ret = managerDAO.update(managerForm);
if (ret == 0) {
// 保存错误提示信息到error参数中
request.setAttribute("error", "设置管理员权限失败!");
// 转到错误提示页面
request.getRequestDispatcher("error.jsp").forward(request, response);
} else {
// 转到权限设置成功页面
request.getRequestDispatcher("manager_ok.jsp?para=2").forward(request, response);
}
|
conventional
|
private void managerModify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ManagerForm managerForm = new ManagerForm();
// 获取并设置管理员ID号
managerForm.setId(Integer.parseInt(request.getParameter("id")));
// 获取并设置管理员名称
managerForm.setName(request.getParameter("name"));
// 获取并设置管理员密码
managerForm.setPwd(request.getParameter("pwd"));
managerForm.setSysset(request.getParameter("sysset") == null ? 0 : Integer.parseInt(request.getParameter("sysset")));
managerForm.setReaderset(request.getParameter("readerset") == null ? 0 : Integer.parseInt(request.getParameter("readerset")));
managerForm.setBookset(request.getParameter("bookset") == null ? 0 : Integer.parseInt(request.getParameter("bookset")));
managerForm.setBorrowback(request.getParameter("borrowback") == null ? 0 : Integer.parseInt(request.getParameter("borrowback")));
managerForm.setSysquery(request.getParameter("sysquery") == null ? 0 : Integer.parseInt(request.getParameter("sysquery")));
int ret = managerDAO.update(managerForm);
if (ret == 0) {
request.setAttribute("error", "设置管理员权限失败!");
request.getRequestDispatcher("error.jsp").forward(request, response);
} else {
request.getRequestDispatcher("manager_ok.jsp?para=2").forward(request, response);
}
}
|
万爽
| |
// 越过filters
resource = doLoad<method*start>com.alibaba.citrus.service.resource.impl.AbstractResourceLoadingContext.doLoad<method*end>(resourceName, options);
|
conventional
|
public ResourceTrace<method*start>com.alibaba.citrus.service.resource.ResourceTrace<method*end> getTrace() throws ResourceNotFoundException<method*start>com.alibaba.citrus.service.resource.ResourceNotFoundException<method*end> {
trace<method*start>com.alibaba.citrus.service.resource.impl.ResourceLoaderContextImpl.trace<method*end> = createLinkedList<method*start>com.alibaba.citrus.util.CollectionUtil.createLinkedList<method*end>();
Resource<method*start>com.alibaba.citrus.service.resource.Resource<method*end> resource = null;
try {
} catch (ResourceNotFoundException<method*start>com.alibaba.citrus.service.resource.ResourceNotFoundException<method*end> e) {
// ignore
}
return new ResourceTrace<method*start>com.alibaba.citrus.service.resource.ResourceTrace<method*end>(trace, resource);
}
|
万爽
| |
int resultCount = userMapper.checkPassword<method*start>com.mmall.dao.UserMapper.checkPassword<method*end>(MD5Util.MD5EncodeUtf8<method*start>com.mmall.util.MD5Util.MD5EncodeUtf8<method*end>(passwordOld), user.getId<method*start>com.mmall.pojo.User.getId<method*end>());
if (resultCount == 0) {
return ServerResponse.createByErrorMessage<method*start>com.mmall.common.ServerResponse.createByErrorMessage<method*end>("旧密码错误");
}
|
conventional
|
public ServerResponse<method*start>com.mmall.common.ServerResponse<method*end><String<method*start>java.lang.String<method*end>> resetPassword(String<method*start>java.lang.String<method*end> passwordOld, String<method*start>java.lang.String<method*end> passwordNew, User<method*start>com.mmall.pojo.User<method*end> user) {
user.setPassword<method*start>com.mmall.pojo.User.setPassword<method*end>(MD5Util.MD5EncodeUtf8<method*start>com.mmall.util.MD5Util.MD5EncodeUtf8<method*end>(passwordNew));
int updateCount = userMapper.updateByPrimaryKeySelective<method*start>com.mmall.dao.UserMapper.updateByPrimaryKeySelective<method*end>(user);
if (updateCount > 0) {
return ServerResponse.createBySuccessMessage<method*start>com.mmall.common.ServerResponse.createBySuccessMessage<method*end>("密码更新成功");
}
return ServerResponse.createByErrorMessage<method*start>com.mmall.common.ServerResponse.createByErrorMessage<method*end>("密码更新失败");
}
|
万爽
| |
// 规则:只要有一个权限点有权限,那么我们就认为有访问权限
for (String<method*start>java.lang.String<method*end> aclUrl : userAclIdSet) {
if (StringUtils.isBlank<method*start>org.apache.commons.lang3.StringUtils.isBlank<method*end>(aclUrl)) {
continue;
}
if (url.equals<method*start>java.lang.String.equals<method*end>(aclUrl)) {
return true;
}
}
return false;
|
conventional
|
public boolean hasUrlAcl(HasAclReq<method*start>com.momo.mapper.req.sysmain.HasAclReq<method*end> hasAclReq) {
if (StringUtils.isBlank<method*start>org.apache.commons.lang3.StringUtils.isBlank<method*end>(hasAclReq.getUrl<method*start>com.momo.mapper.req.sysmain.HasAclReq.getUrl<method*end>())) {
return false;
}
String<method*start>java.lang.String<method*end> url = truncateUrlPage<method*start>com.momo.service.service.authority.CommonSysCoreService.truncateUrlPage<method*end>(hasAclReq.getUrl<method*start>com.momo.mapper.req.sysmain.HasAclReq.getUrl<method*end>());
List<method*start>java.util.List<method*end><AclDO> userAclList = getUserAclList(new DynamicMenuAuthorReq(), hasAclReq);
Set<method*start>java.util.Set<method*end><String<method*start>java.lang.String<method*end>> userAclIdSet = userAclList.stream<method*start>java.util.List.stream<method*end>().map<method*start>java.util.stream.Stream.map<method*end>(AclDO::getSysAclUrl).collect<method*start>java.util.stream.Stream.collect<method*end>(Collectors.toSet<method*start>java.util.stream.Collectors.toSet<method*end>());
return false;
}
|
万爽
| |
// 检查该权限是否已经获取
int i = checkSelfPermission(mPermissions[0]);
// 权限是否已经 授权 GRANTED---授权 DINIED---拒绝
if (i != PackageManager.PERMISSION_GRANTED) {
// 提示用户应该去应用设置界面手动开启权限
showDialogTipUserGoToAppSettting();
} else {
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
}
|
conventional
|
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 123) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
}
}
}
|
万爽
| |
List<method*start>java.util.List<method*end><String> noPermission = new ArrayList<method*start>java.util.ArrayList<method*end><>();
int i = ContextCompat.checkSelfPermission<method*start>android.support.v4.content.ContextCompat.checkSelfPermission<method*end>(context, permission);
if (i == PackageManager.PERMISSION_GRANTED<method*start>android.content.pm.PackageManager.PERMISSION_GRANTED<method*end>) {
return true;
}
|
annotation
|
@RequiresApi<method*start>android.support.annotation.RequiresApi<method*end>(api<method*start>android.support.annotation.RequiresApi.api<method*end> = Build.VERSION_CODES.M<method*start>android.os.Build.VERSION_CODES.M<method*end>)
public static boolean checkPermission(Context<method*start>android.content.Context<method*end> context, @NonNull<method*start>android.support.annotation.NonNull<method*end> String permission) {
return false;
}
|
万爽
| |
try {
UserPo loginUser = (UserPo) request.getSession().getAttribute(RtConstant.KEY_USER_PO);
if (loginUser.isCanWriteUser()) {
logger.info("用户{}更新用户权限,用户名:{}", loginUser.getUsername(), user.getUsername());
userService.updateUserPermissionByUsername(user);
} else {
logger.error("根据用户名更新用户权限错误,用户{}没有权限", loginUser.getUsername());
responseVo.setStatus(false);
responseVo.setMessage("根据用户名更新用户权限错误,没有权限");
}
} catch (Exception e) {
logger.error("根据用户名更新用户权限错误", e);
responseVo.setStatus(false);
responseVo.setMessage(e.getMessage());
}
|
conventional
|
@RequestMapping(value = { "/updateUserPermissionByUsername" })
@ResponseBody
public ResponseVo<String> updateUserPermissionByUsername(HttpServletRequest request, @RequestBody UserPo user) {
ResponseVo<String> responseVo = new ResponseVo<>();
return responseVo;
}
|
万爽
| |
checkRole(user);
|
conventional
|
@Override
@Transactional
public void updateUserRole(SysUser user) {
if (StringUtils.isBlank(user.getPassword())) {
user.setPassword(null);
} else {
user.setPassword(passwordEncoder.encode(user.getPassword()));
}
baseMapper.updateById(user);
sysUserRoleMapper.delete(Wrappers.<SysUserRole>update().lambda().eq(SysUserRole::getUserId, user.getUserId()));
saveUserRoleList(user);
}
|
万爽
| |
// 防止横向越权,要校验用户的旧密码
int resCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
if (resCount == 0) {
return ServerResponse.createByError("旧密码错误");
}
|
conventional
|
@Override
public ServerResponse<String> resetPassword(String passwordNew, String passwordOld, User user) {
user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
int updateCount = userMapper.updateByPrimaryKeySelective(user);
if (updateCount > 0) {
return ServerResponse.createBySuccessMessage("密码更新成功");
} else
return ServerResponse.createByError("密码更新失败");
}
|
万爽
| |
// 如果没有禁用安全检查,那么需要检查显式访问权限
if (!override<method*start>java.lang.reflect.AccessibleObject.override<method*end>) {
Class<method*start>java.lang.Class<method*end><?> caller = Reflection.getCallerClass<method*start>jdk.internal.reflect.Reflection.getCallerClass<method*end>();
checkAccess<method*start>java.lang.reflect.AccessibleObject.checkAccess<method*end>(caller, clazz, Modifier.isStatic<method*start>java.lang.reflect.Modifier.isStatic<method*end>(modifiers) ? null : obj.getClass<method*start>java.lang.Object.getClass<method*end>(), modifiers);
}
|
conventional
|
@CallerSensitive<method*start>jdk.internal.reflect.CallerSensitive<method*end>
@ForceInline<method*start>jdk.internal.vm.annotation.ForceInline<method*end>
@HotSpotIntrinsicCandidate<method*start>jdk.internal.HotSpotIntrinsicCandidate<method*end>
public Object<method*start>java.lang.Object<method*end> invoke(Object<method*start>java.lang.Object<method*end> obj, Object<method*start>java.lang.Object<method*end>... args) throws IllegalAccessException<method*start>java.lang.IllegalAccessException<method*end>, IllegalArgumentException<method*start>java.lang.IllegalArgumentException<method*end>, InvocationTargetException<method*start>java.lang.reflect.InvocationTargetException<method*end> {
MethodAccessor<method*start>jdk.internal.reflect.MethodAccessor<method*end> ma = methodAccessor;
if (ma == null) {
ma = acquireMethodAccessor<method*start>java.lang.reflect.Method.acquireMethodAccessor<method*end>();
}
return ma.invoke<method*start>jdk.internal.reflect.MethodAccessor.invoke<method*end>(obj, args);
}
|
万爽
| |
// 拦截器.
Map<String, String> map = new HashMap<>();
// 配置不会被拦截的链接 顺序判断 相关静态资源
map.put("/static/**", "anon");
// 配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
map.put("/admin/logout", "logout");
// <!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
// <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
map.put("/admin/**", "authc");
map.put("/adminlogin", "myShiroFilter");
// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
shiroFilterFactoryBean.setLoginUrl("/adminlogin");
// 登录成功后要跳转的链接
shiroFilterFactoryBean.setSuccessUrl("/admin/index");
// 未授权界面;
|
conventional
|
@Bean
public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager securityManager) {
log.info("开始配置shiroFilter...");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, Filter> filterMap = shiroFilterFactoryBean.getFilters();
filterMap.put("myShiroFilter", new MyShiroFilter());
shiroFilterFactoryBean.setFilters(filterMap);
shiroFilterFactoryBean.setUnauthorizedUrl("/error");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
|
万爽
| |
if (!hasBizPermission(request, apiDataType.getBizId())) {
return new ReturnT(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通");
}
List<XxlApiDataTypeField> list = xxlApiDataTypeFieldDao.findByFieldDatatypeId(id);
if (list != null && list.size() > 0) {
return new ReturnT(ReturnT.FAIL_CODE, "该数据类型被引用中,拒绝删除");
}
List<XxlApiDocument> apiList = xxlApiDocumentDao.findByResponseDataTypeId(id);
if (apiList != null && apiList.size() > 0) {
return new ReturnT(ReturnT.FAIL_CODE, "该数据类型被API引用,拒绝删除");
}
|
conventional
|
@RequestMapping("/deleteDataType")
@ResponseBody
public ReturnT<String> deleteDataType(HttpServletRequest request, int id) {
XxlApiDataType apiDataType = xxlApiDataTypeDao.load(id);
if (apiDataType == null) {
return new ReturnT(ReturnT.FAIL_CODE, "数据类型ID非法");
}
int ret = xxlApiDataTypeDao.delete(id);
xxlApiDataTypeFieldDao.deleteByParentDatatypeId(id);
return ret > 0 ? ReturnT.SUCCESS : ReturnT.FAIL;
}
|
万爽
| |
if (loader == null && ccl != null) {
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
|
conventional
|
private static void checkProxyAccess(Class<?> caller, ClassLoader loader, Class<?>... interfaces) {
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
return;
}
ClassLoader ccl = caller.getClassLoader();
ReflectUtil.checkProxyPackageAccess(ccl, interfaces);
}
|
万爽
|
End of preview. Expand
in Data Studio
- Downloads last month
- -