validation
stringlengths
16
3.54k
validationType
stringclasses
2 values
function
stringlengths
49
6.38k
author
stringclasses
5 values
context
stringclasses
5 values
if (!hasBizPermission(request, project.getBizId())) { throw new RuntimeException("您没有相关业务线的权限,请联系管理员开通"); }
conventional
@RequestMapping("/updatePage") public String updatePage(HttpServletRequest request, Model model, int id) { // document XxlApiDocument xxlApiDocument = xxlApiDocumentDao.load(id); if (xxlApiDocument == null) { throw new RuntimeException("操作失败,接口ID非法"); } model.addAttribute("document", xxlApiDocument); model.addAttribute("requestHeadersList", (StringTool.isNotBlank(xxlApiDocument.getRequestHeaders())) ? JacksonUtil.readValue(xxlApiDocument.getRequestHeaders(), List.class) : null); model.addAttribute("queryParamList", (StringTool.isNotBlank(xxlApiDocument.getQueryParams())) ? JacksonUtil.readValue(xxlApiDocument.getQueryParams(), List.class) : null); model.addAttribute("responseParamList", (StringTool.isNotBlank(xxlApiDocument.getResponseParams())) ? JacksonUtil.readValue(xxlApiDocument.getResponseParams(), List.class) : null); // project int projectId = xxlApiDocument.getProjectId(); model.addAttribute("projectId", projectId); // 权限 XxlApiProject project = xxlApiProjectDao.load(xxlApiDocument.getProjectId()); // groupList List<XxlApiGroup> groupList = xxlApiGroupDao.loadAll(projectId); model.addAttribute("groupList", groupList); // enum model.addAttribute("RequestMethodEnum", RequestConfig.RequestMethodEnum.values()); model.addAttribute("requestHeadersEnum", RequestConfig.requestHeadersEnum); model.addAttribute("QueryParamTypeEnum", RequestConfig.QueryParamTypeEnum.values()); model.addAttribute("ResponseContentType", RequestConfig.ResponseContentType.values()); // 响应数据类型 XxlApiDataType responseDatatypeRet = xxlApiDataTypeService.loadDataType(xxlApiDocument.getResponseDatatypeId()); model.addAttribute("responseDatatype", responseDatatypeRet); return "document/document.update"; }
万爽
@PreAuthorize<method*start>org.springframework.security.access.prepost.PreAuthorize<method*end>("hasAnyRole('ADMIN','USER_ALL','USER_DELETE')")
annotation
@Log<method*start>com.dxj.log.annotation.Log<method*end>("删除用户") @DeleteMapping<method*start>org.springframework.web.bind.annotation.DeleteMapping<method*end>(value<method*start>org.springframework.web.bind.annotation.GetMapping.value<method*end> = "/user/{id}") public ResponseEntity<method*start>org.springframework.http.ResponseEntity<method*end><Void<method*start>java.lang.Void<method*end>> delete(@PathVariable<method*start>org.springframework.web.bind.annotation.PathVariable<method*end> Long id) { Integer<method*start>java.lang.Integer<method*end> currentLevel = Collections.min<method*start>java.util.Collections.min<method*end>(roleService.findByUsers_Id<method*start>com.dxj.admin.service.RoleService.findByUsers_Id<method*end>(SecurityContextHolder.getUserId<method*start>com.dxj.common.util.SecurityContextHolder.getUserId<method*end>()).stream<method*start>java.util.List.stream<method*end>().map<method*start>java.util.stream.Stream.map<method*end>(RoleSmallDTO::getLevel).collect<method*start>java.util.stream.Stream.collect<method*end>(Collectors.toList<method*start>java.util.stream.Collectors.toList<method*end>())); Integer<method*start>java.lang.Integer<method*end> optLevel = Collections.min<method*start>java.util.Collections.min<method*end>(roleService.findByUsers_Id<method*start>com.dxj.admin.service.RoleService.findByUsers_Id<method*end>(id).stream<method*start>java.util.List.stream<method*end>().map<method*start>java.util.stream.Stream.map<method*end>(RoleSmallDTO::getLevel).collect<method*start>java.util.stream.Stream.collect<method*end>(Collectors.toList<method*start>java.util.stream.Collectors.toList<method*end>())); if (currentLevel > optLevel) { throw new BadRequestException("角色权限不足"); } userService.delete<method*start>com.dxj.admin.service.UserService.delete<method*end>(id); return new ResponseEntity<method*start>org.springframework.http.ResponseEntity<method*end><>(HttpStatus.OK<method*start>org.springframework.http.HttpStatus.OK<method*end>); }
万爽
// 当前登陆用户权限 Subject<method*start>org.apache.shiro.subject.Subject<method*end> subject = SecurityUtils.getSubject<method*start>org.apache.shiro.SecurityUtils.getSubject<method*end>(); String<method*start>java.lang.String<method*end> username = (String<method*start>java.lang.String<method*end>) subject.getPrincipal<method*start>org.apache.shiro.subject.Subject.getPrincipal<method*end>(); UpmsUser upmsUser = upmsApiService.selectUpmsUserByUsername<method*start>com.vua.upms.rpc.api.UpmsApiService.selectUpmsUserByUsername<method*end>(username); List<method*start>java.util.List<method*end><UpmsPermission> upmsPermissions = upmsApiService.selectUpmsPermissionByUpmsUserId<method*start>com.vua.upms.rpc.api.UpmsApiService.selectUpmsPermissionByUpmsUserId<method*end>(upmsUser.getUserId<method*start>com.vua.upms.dao.model.UpmsUser.getUserId<method*end>()); modelMap.put<method*start>org.springframework.ui.ModelMap.put<method*end>("upmsPermissions", upmsPermissions);
conventional
@ApiOperation<method*start>io.swagger.annotations.ApiOperation<method*end>(value<method*start>io.swagger.annotations.Api.value<method*end> = "后台首页") @RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>(value<method*start>io.swagger.annotations.Api.value<method*end> = "/index", method<method*start>org.springframework.web.bind.annotation.RequestMapping.method<method*end> = RequestMethod.GET<method*start>org.springframework.web.bind.annotation.RequestMethod.GET<method*end>) public String<method*start>java.lang.String<method*end> index(ModelMap<method*start>org.springframework.ui.ModelMap<method*end> modelMap) { UpmsSystemExample<method*start>com.vua.upms.dao.model.UpmsSystemExample<method*end> upmsSystemExample = new UpmsSystemExample(); upmsSystemExample.createCriteria<method*start>com.vua.upms.dao.model.UpmsSystemExample.createCriteria<method*end>().andStatusEqualTo<method*start>com.vua.upms.dao.model.UpmsSystemExample.GeneratedCriteria.andStatusEqualTo<method*end>((byte) 1); List<method*start>java.util.List<method*end><UpmsSystem> upmsSystems = upmsSystemService.selectByExample<method*start>com.vua.upms.rpc.api.UpmsSystemService.selectByExample<method*end>(upmsSystemExample); modelMap.put<method*start>org.springframework.ui.ModelMap.put<method*end>("upmsSystems", upmsSystems); return "/manage/index.jsp"; }
万爽
if (user == null) { return ServerResponse.createByErrorCodeMessage<method*start>com.mmall.common.ServerResponse.createByErrorCodeMessage<method*end>(ResponseCode.NEED_LOGIN.getCode<method*start>com.mmall.common.ResponseCode.getCode<method*end>(), "用户未登录,请登录管理员"); } if (iUserService.checkAdminRole<method*start>com.mmall.service.IUserService.checkAdminRole<method*end>(user).isSuccess<method*start>com.mmall.common.ServerResponse.isSuccess<method*end>()) { // 填充我们增加产品的业务逻辑 return iOrderService.manageSendGoods<method*start>com.mmall.service.IOrderService.manageSendGoods<method*end>(orderNo); } else { return ServerResponse.createByErrorMessage<method*start>com.mmall.common.ServerResponse.createByErrorMessage<method*end>("无权限操作"); }
conventional
@RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>("send_goods.do") @ResponseBody public ServerResponse<method*start>com.mmall.common.ServerResponse<method*end><String<method*start>java.lang.String<method*end>> orderSendGoods(HttpSession<method*start>javax.servlet.http.HttpSession<method*end> session, Long<method*start>java.lang.Long<method*end> orderNo) { User<method*start>com.mmall.pojo.User<method*end> user = (User<method*start>com.mmall.pojo.User<method*end>) session.getAttribute<method*start>javax.servlet.http.HttpSession.getAttribute<method*end>(Const.CURRENT_USER<method*start>com.mmall.common.Const.CURRENT_USER<method*end>); }
万爽
@AuthRuleAnnotation("admin/auth/role/auth")
annotation
@PostMapping("/admin/auth/role/auth") public BaseResponse<method*start>com.lmxdawn.api.common.res.BaseResponse<method*end> auth(@RequestBody @Valid AuthRoleAuthRequest authRoleAuthRequest, BindingResult<method*start>org.springframework.validation.BindingResult<method*end> bindingResult) { if (bindingResult.hasErrors<method*start>org.springframework.validation.BindingResult.hasErrors<method*end>()) { return ResultVOUtils.error<method*start>com.lmxdawn.api.common.util.ResultVOUtils.error<method*end>(ResultEnum.PARAM_VERIFY_FALL<method*start>com.lmxdawn.api.common.enums.ResultEnum.PARAM_VERIFY_FALL<method*end>, bindingResult.getFieldError<method*start>org.springframework.validation.BindingResult.getFieldError<method*end>().getDefaultMessage<method*start>org.springframework.validation.FieldError.getDefaultMessage<method*end>()); } authPermissionService.deleteByRoleId<method*start>com.lmxdawn.api.admin.service.auth.AuthPermissionService.deleteByRoleId<method*end>(authRoleAuthRequest.getRoleId<method*start>com.lmxdawn.api.admin.req.auth.AuthRoleAuthRequest.getRoleId<method*end>()); List<method*start>java.util.List<method*end><AuthPermission<method*start>com.lmxdawn.api.admin.entity.auth.AuthPermission<method*end>> authPermissionList = authRoleAuthRequest.getAuthRules<method*start>com.lmxdawn.api.admin.req.auth.AuthRoleAuthRequest.getAuthRules<method*end>().stream<method*start>java.util.List.stream<method*end>().map<method*start>java.util.stream.Stream.map<method*end>(aLong -> { AuthPermission<method*start>com.lmxdawn.api.admin.entity.auth.AuthPermission<method*end> authPermission = new AuthPermission<method*start>com.lmxdawn.api.admin.entity.auth.AuthPermission<method*end>(); authPermission.setRoleId<method*start>com.lmxdawn.api.admin.entity.auth.AuthPermission.setRoleId<method*end>(authRoleAuthRequest.getRoleId<method*start>com.lmxdawn.api.admin.req.auth.AuthRoleAuthRequest.getRoleId<method*end>()); authPermission.setPermissionRuleId<method*start>com.lmxdawn.api.admin.entity.auth.AuthPermission.setPermissionRuleId<method*end>(aLong); authPermission.setType<method*start>com.lmxdawn.api.admin.entity.auth.AuthPermission.setType<method*end>("admin"); return authPermission; }).collect(Collectors.toList<method*start>java.util.stream.Collectors.toList<method*end>()); int i = authPermissionService.insertAuthPermissionAll<method*start>com.lmxdawn.api.admin.service.auth.AuthPermissionService.insertAuthPermissionAll<method*end>(authPermissionList); return ResultVOUtils.success<method*start>com.lmxdawn.api.common.util.ResultVOUtils.success<method*end>(); }
万爽
// 当前是游客则无操作权限 if (currentUserId.equals(USER.VISITOR_ID)) { return false; } // 当前是admin if (currentUserId.equals(USER.ADMIN_ID)) { return true; } // 帖子作者是当前用户id if (writerId.equals(currentUserId)) { return true; } return false;
conventional
public static boolean hasEditPrivilege(Long writerId, Long currentUserId) { try { // 当前是游客则无操作权限 return true; } catch (Exception e) { logger.error("login valid permission error", e); return false; } }
万爽
if (id == 1) { return data = DataVo.failure("超级管理员组不能删除"); }
conventional
@PostMapping("/group_del") @ResponseBody public DataVo deleteGroup(@RequestParam(value = "id") Long id) { DataVo data = DataVo.failure("操作失败"); if (groupService.deleteGroup(id)) { data = DataVo.success("该权限组已删除"); } else { data = DataVo.failure("删除失败或者不存在!"); } return data; }
万爽
@RequiresPermissions<method*start>org.apache.shiro.authz.annotation.RequiresPermissions<method*end>("oss:pdf:view")
annotation
@ApiOperation<method*start>io.swagger.annotations.ApiOperation<method*end>(value = "pdf预览", notes<method*start>io.swagger.annotations.ApiOperation.notes<method*end> = "权限编码(oss:pdf:view)") @GetMapping<method*start>org.springframework.web.bind.annotation.GetMapping<method*end>("/view") public void pdfViewer(HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request, HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response) { HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> orgRequest = XssHttpServletRequestWrapper.getOrgRequest<method*start>com.king.utils.XssHttpServletRequestWrapper.getOrgRequest<method*end>(request); String<method*start>java.lang.String<method*end> urlpath = orgRequest.getParameter<method*start>javax.servlet.http.HttpServletRequest.getParameter<method*end>("urlpath"); logger.info<method*start>org.slf4j.Logger.info<method*end>("urlpath=" + urlpath); try { InputStream<method*start>java.io.InputStream<method*end> fileInputStream = IoUtil.getFileStream<method*start>com.king.common.utils.file.IoUtil.getFileStream<method*end>(urlpath); response.setHeader<method*start>javax.servlet.http.HttpServletResponse.setHeader<method*end>("Content-Disposition", "attachment;fileName=test.pdf"); response.setContentType<method*start>javax.servlet.http.HttpServletResponse.setContentType<method*end>("multipart/form-data"); OutputStream<method*start>java.io.OutputStream<method*end> outputStream = response.getOutputStream<method*start>javax.servlet.http.HttpServletResponse.getOutputStream<method*end>(); IOUtils.write<method*start>org.apache.commons.io.IOUtils.write<method*end>(IOUtils.toByteArray<method*start>org.apache.commons.io.IOUtils.toByteArray<method*end>(fileInputStream), outputStream); } catch (Exception<method*start>java.lang.Exception<method*end> e) { System.out.println<method*start>java.io.PrintStream.println<method*end>(e.getMessage<method*start>java.lang.Exception.getMessage<method*end>()); } }
肖敬先
if (command.getGmLevel() > gmLevel) { return "你没有权限执行此GM命令"; }
conventional
private String execGmCmd(Session session, String gmStr, int gmLevel) { gmStr = gmStr.substring(1); String[] commandArray = gmStr.split(" "); GMCommand command = GMCommand.getCommand(commandArray[0]); if (command == null) { return "没有对应GM命令"; } Gm gm = GMCommand.getGm(command); String ret = gm.executeGM(session, commandArray); if (ret != null) { return ret; } return "执行成功"; }
肖敬先
@PreAuthorize("@permissionService.hasPermission('system:role:add')")
annotation
@PostMapping public AjaxResult add(@RequestBody Role role) { if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) { return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在"); } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) { return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在"); } role.setCreateBy(SecurityUtils.getUsername()); return toAjax(roleService.insertRole(role)); }
肖敬先
// 角色已有权限 List<method*start>java.util.List<method*end><UpmsRolePermission> rolePermissions = upmsApiService.selectUpmsRolePermisstionByUpmsRoleId<method*start>com.vua.upms.rpc.api.UpmsApiService.selectUpmsRolePermisstionByUpmsRoleId<method*end>(id);
conventional
@Override public JSONArray<method*start>com.alibaba.fastjson.JSONArray<method*end> getTreeByRoleId(Integer<method*start>java.lang.Integer<method*end> id) { UpmsSystemExample upmsSystemExample = new UpmsSystemExample(); upmsSystemExample.createCriteria<method*start>com.vua.upms.dao.model.UpmsSystemExample.createCriteria<method*end>().andStatusEqualTo<method*start>com.vua.upms.dao.model.UpmsSystemExample.GeneratedCriteria.andStatusEqualTo<method*end>((byte) 1); upmsSystemExample.setOrderByClause<method*start>com.vua.upms.dao.model.UpmsSystemExample.setOrderByClause<method*end>("orders asc"); List<method*start>java.util.List<method*end><UpmsSystem> upmsSystems = upmsSystemMapper.selectByExample<method*start>com.vua.upms.dao.mapper.UpmsSystemMapper.selectByExample<method*end>(upmsSystemExample); JSONArray<method*start>com.alibaba.fastjson.JSONArray<method*end> systems = upmsSystems.parallelStream<method*start>java.util.List.parallelStream<method*end>().map<method*start>java.util.stream.Stream.map<method*end>(x -> { JSONObject<method*start>com.alibaba.fastjson.JSONObject<method*end> node = new JSONObject<method*start>com.alibaba.fastjson.JSONObject<method*end>(); node.put<method*start>com.alibaba.fastjson.JSONObject.put<method*end>("id", x.getSystemId<method*start>oracle.net.aso.x.getSystemId<method*end>()); node.put<method*start>com.alibaba.fastjson.JSONObject.put<method*end>("name", x.getTitle<method*start>oracle.net.aso.x.getTitle<method*end>()); node.put<method*start>com.alibaba.fastjson.JSONObject.put<method*end>("nocheck", true); node.put<method*start>com.alibaba.fastjson.JSONObject.put<method*end>("open", true); return node; }).collect<method*start>java.util.stream.Stream.collect<method*end>(JSONArray<method*start>com.alibaba.fastjson.JSONArray<method*end>::new, JSONArray<method*start>com.alibaba.fastjson.JSONArray<method*end>::add, JSONArray<method*start>com.alibaba.fastjson.JSONArray<method*end>::addAll); return systems; }
肖敬先
BirdSession session = authorizeManager.parseSession(exchange); if (StringUtils.equalsIgnoreCase(routeDefinition.getRpcType(), RpcTypeEnum.DUBBO.getName())) { if (BooleanUtils.isNotTrue(routeDefinition.getAnonymous())) { if (session == null) { return jsonResult(exchange, JsonResult.error(CommonErrorCode.UNAUTHORIZED, "需登录后才能访问")); } else { String[] permissions = StringUtils.split(routeDefinition.getPermissions(), ","); if (!authorizeManager.checkPermissions(session, permissions, BooleanUtils.isTrue(routeDefinition.getCheckAll()))) { return jsonResult(exchange, JsonResult.error(CommonErrorCode.UNAUTHORIZED, "当前用户权限不足")); } } } }
annotation
@Override protected Mono<Void> doExecute(ServerWebExchange exchange, PipeChain chain, RouteDefinition routeDefinition) { BirdSession session = authorizeManager.parseSession(exchange); } } SessionContext.setSession(session); return chain.execute(exchange); }
肖敬先
basicCheck(comment);
conventional
@PostMapping(value = "/revert") @ResponseBody @SystemLog(description = "回滚评论", type = LogTypeEnum.OPERATION) public JsonResult moveToPublish(@RequestParam("id") Long commentId) { User loginUser = getLoginUser(); // 评论 Comment comment = commentService.get(commentId); // 检查权限 Post post = postService.get(comment.getPostId()); Comment result = commentService.updateCommentStatus(commentId, CommentStatusEnum.PUBLISHED.getCode()); // 判断是否启用邮件服务 new NoticeToAuthor(result, post, loginUser, comment.getCommentStatus()).start(); return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.operation-success")); }
肖敬先
@LoginPassport if (auth == null || auth.equals("") || (!jwtUtil.getValueFromToken(auth, "role").equals("admin") && !jwtUtil.getValueFromToken(auth, "role").equals("release"))) { k8sConfs.get(i).getItems().get(j).setValue("******"); k8sConfs.get(i).getCurrencyRecord().setConfData("没有权限查看"); for (int h = 0; h < k8sConfs.get(i).getRecords().size(); h++) { k8sConfs.get(i).getRecords().get(h).setConfData("没有权限查看"); } }
conventional
@GetMapping(value = "/list") public JsonResult<com.mokn.istio.api.model.domain.JsonResult<com.mokn.istio.api.model.db.K8sConf>> list(@RequestParam(value = "pageNo", required = false) Integer pageNo, @RequestParam(value = "pageSize", required = false) Integer pageSize, @RequestParam(value = "namespace", required = false) String namespace, @RequestParam(value = "name", required = false) String name, @RequestHeader(value = "Authorization", required = false) String auth) { JsonResult<com.mokn.istio.api.model.domain.JsonResult<com.mokn.istio.api.model.db.K8sConf>> result = new JsonResult<>(); K8sConf<com.mokn.istio.api.model.db.K8sConf> condition = new K8sConf<>(); if (namespace != null && !namespace.equals("")) { condition.setNamespace(namespace); } if (name != null && !name.equals("")) { condition.setNamespace(name); } PageHelper.startPage(pageNo, pageSize); PageInfo<com.mokn.istio.api.model.db.K8sConf> pageInfo = new PageInfo<>(confService.listConf(condition)); List<com.mokn.istio.api.model.db.K8sConf> k8sConfs = pageInfo.getList(); for (int i = 0; i < k8sConfs.size(); i++) { for (int j = 0; j < k8sConfs.get(i).getItems().size(); j++) { for (int h = 0; h < k8sConfs.get(i).getRecords().size(); h++) { k8sConfs.get(i).getRecords().get(h).setConfData("没有权限查看"); } } } } return result.success(k8sConfs, pageInfo.getTotal()); }
肖敬先
if (CheckPermissionUtil.isNoPermission(authResult.getToken(), request, response, handler, urlPerm)) { throw new UnauthorizedException(); }
conventional
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 放行options请求 if (request.getMethod().toUpperCase().equals("OPTIONS")) { CheckPermissionUtil.passOptions(response); return false; } Method method = null; if (handler instanceof HandlerMethod) { method = ((HandlerMethod) handler).getMethod(); } // 检查是否忽略权限验证 if (method == null || CheckPermissionUtil.checkIgnore(method)) { return super.preHandle(request, response, handler); } // 获取token String access_token = CheckPermissionUtil.takeToken(request); if (access_token == null || access_token.trim().isEmpty()) { throw new ErrorTokenException("Token不能为空"); } if (authCenterUrl == null) { throw new RuntimeException("请配置authCenterUrl"); } String url = authCenterUrl + "/authentication?access_token=" + access_token; AuthResult authResult = new RestTemplate().getForObject(url, AuthResult.class); if (authResult == null) { throw new RuntimeException("'" + authCenterUrl + "/authentication' return null"); } else if (AuthResult.CODE_EXPIRED == authResult.getCode()) { throw new ExpiredTokenException(); } else if (AuthResult.CODE_OK != authResult.getCode()) { throw new ErrorTokenException(); } request.setAttribute(SubjectUtil.REQUEST_TOKEN_NAME, authResult.getToken()); return super.preHandle(request, response, handler); }
肖敬先
if (authResult == null) { throw new RuntimeException("'" + authCenterUrl + "/authentication' return null"); } else if (AuthResult.CODE_EXPIRED == authResult.getCode()) { throw new ExpiredTokenException(); } else if (AuthResult.CODE_OK != authResult.getCode()) { throw new ErrorTokenException(); } // 检查权限 if (CheckPermissionUtil.isNoPermission(authResult.getToken(), request, response, handler, urlPerm)) { throw new UnauthorizedException(); }
conventional
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 放行options请求 if (request.getMethod().toUpperCase().equals("OPTIONS")) { CheckPermissionUtil.passOptions(response); return false; } Method method = null; if (handler instanceof HandlerMethod) { method = ((HandlerMethod) handler).getMethod(); } request.setAttribute(SubjectUtil.REQUEST_TOKEN_NAME, authResult.getToken()); return super.preHandle(request, response, handler); }
肖敬先
if (!BaseUtil.getUserId<method*start>com.kakarote.crm9.utils.BaseUtil.getUserId<method*end>().equals<method*start>java.lang.Long.equals<method*end>(BaseConstant.SUPER_ADMIN_USER_ID<method*start>com.kakarote.crm9.common.constant.BaseConstant.SUPER_ADMIN_USER_ID<method*end>) && !AuthUtil.isRwAuth<method*start>com.kakarote.crm9.utils.AuthUtil.isRwAuth<method*end>(Integer.parseInt<method*start>java.lang.Integer.parseInt<method*end>(businessId), "business")) { return R.error<method*start>com.kakarote.crm9.utils.R.error<method*end>("无权限转移"); }
conventional
public R<method*start>com.kakarote.crm9.utils.R<method*end> transfer(CrmBusiness<method*start>com.kakarote.crm9.erp.crm.entity.CrmBusiness<method*end> crmBusiness) { String<method*start>java.lang.String<method*end>[] businessIdsArr = crmBusiness.getBusinessIds<method*start>com.kakarote.crm9.erp.crm.entity.CrmBusiness.getBusinessIds<method*end>().split<method*start>java.lang.String.split<method*end>(","); for (String<method*start>java.lang.String<method*end> businessId : businessIdsArr) { String<method*start>java.lang.String<method*end> memberId = "," + crmBusiness.getNewOwnerUserId<method*start>com.kakarote.crm9.erp.crm.entity.CrmBusiness.getNewOwnerUserId<method*end>() + ","; Db.update<method*start>com.jfinal.plugin.activerecord.Db.update<method*end>(Db.getSql<method*start>com.jfinal.plugin.activerecord.Db.getSql<method*end>("crm.business.deleteMember"), memberId, memberId, Integer.valueOf<method*start>java.lang.Integer.valueOf<method*end>(businessId)); CrmBusiness<method*start>com.kakarote.crm9.erp.crm.entity.CrmBusiness<method*end> oldBusiness = CrmBusiness.dao.findById<method*start>com.jfinal.plugin.activerecord.Model.findById<method*end>(Integer.valueOf<method*start>java.lang.Integer.valueOf<method*end>(businessId)); if (2 == crmBusiness.getTransferType<method*start>com.kakarote.crm9.erp.crm.entity.CrmBusiness.getTransferType<method*end>()) { if (1 == crmBusiness.getPower<method*start>com.kakarote.crm9.erp.crm.entity.CrmBusiness.getPower<method*end>()) { crmBusiness.setRoUserId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmBusiness.setRoUserId<method*end>(oldBusiness.getRoUserId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmBusiness.getRoUserId<method*end>() + oldBusiness.getOwnerUserId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmBusiness.getOwnerUserId<method*end>() + ","); } if (2 == crmBusiness.getPower<method*start>com.kakarote.crm9.erp.crm.entity.CrmBusiness.getPower<method*end>()) { crmBusiness.setRwUserId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmBusiness.setRwUserId<method*end>(oldBusiness.getRwUserId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmBusiness.getRwUserId<method*end>() + oldBusiness.getOwnerUserId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmBusiness.getOwnerUserId<method*end>() + ","); } } crmBusiness.setBusinessId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmBusiness.setBusinessId<method*end>(Integer.valueOf<method*start>java.lang.Integer.valueOf<method*end>(businessId)); crmBusiness.setOwnerUserId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmBusiness.setOwnerUserId<method*end>(crmBusiness.getNewOwnerUserId<method*start>com.kakarote.crm9.erp.crm.entity.CrmBusiness.getNewOwnerUserId<method*end>()); crmBusiness.update<method*start>com.jfinal.plugin.activerecord.Model.update<method*end>(); crmRecordService.addConversionRecord<method*start>com.kakarote.crm9.erp.crm.service.CrmRecordService.addConversionRecord<method*end>(Integer.valueOf<method*start>java.lang.Integer.valueOf<method*end>(businessId), CrmEnum.CRM_BUSINESS<method*start>com.kakarote.crm9.erp.crm.common.CrmEnum.CRM_BUSINESS<method*end>, crmBusiness.getNewOwnerUserId<method*start>com.kakarote.crm9.erp.crm.entity.CrmBusiness.getNewOwnerUserId<method*end>()); } return R.ok<method*start>com.kakarote.crm9.utils.R.ok<method*end>(); }
肖敬先
if (menuIds.contains(sysMenu.getId().toString())) { treeMenuAllowAccess.setAllowAccess(1); } if (sysMenu.getDeep() < 3) { treeMenuAllowAccess.setChildren(selectTreeMenuAllowAccessByMenuIdsAndPid(menuIds, sysMenu.getId().toString())); }
conventional
@Override public List<method*start>java.util.List<method*end><TreeMenuAllowAccess<method*start>com.github.vole.portal.model.vo.TreeMenuAllowAccess<method*end>> selectTreeMenuAllowAccessByMenuIdsAndPid(final List<method*start>java.util.List<method*end><String<method*start>java.lang.String<method*end>> menuIds, String<method*start>java.lang.String<method*end> pid) { QueryWrapper<method*start>com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<method*end><SysMenu<method*start>com.github.vole.portal.model.entity.SysMenu<method*end>> ew = new QueryWrapper<method*start>com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<method*end><SysMenu<method*start>com.github.vole.portal.model.entity.SysMenu<method*end>>(); ew.orderByAsc("sort"); ew.eq("parent_id", pid); List<method*start>java.util.List<method*end><SysMenu<method*start>com.github.vole.portal.model.entity.SysMenu<method*end>> sysMenus = this.list(ew); List<method*start>java.util.List<method*end><TreeMenuAllowAccess<method*start>com.github.vole.portal.model.vo.TreeMenuAllowAccess<method*end>> treeMenuAllowAccesss = new ArrayList<method*start>java.util.ArrayList<method*end><TreeMenuAllowAccess<method*start>com.github.vole.portal.model.vo.TreeMenuAllowAccess<method*end>>(); for (SysMenu<method*start>com.github.vole.portal.model.entity.SysMenu<method*end> sysMenu : sysMenus) { TreeMenuAllowAccess<method*start>com.github.vole.portal.model.vo.TreeMenuAllowAccess<method*end> treeMenuAllowAccess = new TreeMenuAllowAccess<method*start>com.github.vole.portal.model.vo.TreeMenuAllowAccess<method*end>(); treeMenuAllowAccess.setSysMenu(sysMenu); treeMenuAllowAccesss.add(treeMenuAllowAccess); } return treeMenuAllowAccesss; }
肖敬先
// 判断是否有权限 if (isAuthorized<method*start>com.honvay.cola.cloud.upm.service.impl.SysResourceServiceImpl.isAuthorized<method*end>(child.getCode()))
conventional
private List<method*start>java.util.List<method*end><SysResourceTreeNode<method*start>com.honvay.cola.cloud.upm.model.SysResourceTreeNode<method*end>> getResourceTree(Long<method*start>java.lang.Long<method*end> pid) { List<method*start>java.util.List<method*end><SysResourceTreeNode<method*start>com.honvay.cola.cloud.upm.model.SysResourceTreeNode<method*end>> menus = new ArrayList<method*start>java.util.ArrayList<method*end><>(); List<method*start>java.util.List<method*end><SysResource<method*start>com.honvay.cola.cloud.upm.entity.SysResource<method*end>> children = this.sysResourceCacheService.getChildrenCacheByResourceId(pid); for (SysResource<method*start>com.honvay.cola.cloud.upm.entity.SysResource<method*end> child : children) { SysResourceTreeNode<method*start>com.honvay.cola.cloud.upm.model.SysResourceTreeNode<method*end> menu = new SysResourceTreeNode<method*start>com.honvay.cola.cloud.upm.model.SysResourceTreeNode<method*end>(); BeanUtils.copyProperties(child, menu); menu.setChildren(this.getResourceTree(child.getId())); menus.add(menu); } menus.sort((o1, o2) -> { if (o1.getSort() == null) { return 0; } if (o2.getSort() == null) { return -1; } return o1.getSort() - o2.getSort(); }); return menus; }
肖敬先
User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null) { return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员"); } if (iUserService.checkAdminRole(user).isSuccess()) { // 填充业务 return iProductService.searchProduct(productName, productId, pageNum, pageSize); } else { return ServerResponse.createByErrorMessage("无权限操作"); }
conventional
@RequestMapping("search.do") public ServerResponse productSearch(HttpSession session, String productName, Integer productId, @RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) { User user = (User) session.getAttribute(Const.CURRENT_USER); // 填充业务 return iProductService.searchProduct(productName, productId, pageNum, }
肖敬先
// 权限校验 XxlApiProject xxlApiProject = xxlApiProjectDao.load(existGroup.getProjectId()); if (!hasBizPermission(request, xxlApiProject.getBizId())) { return new ReturnT(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通"); }
conventional
@RequestMapping("/update") @ResponseBody public ReturnT<String> update(HttpServletRequest request, XxlApiGroup xxlApiGroup) { // exist XxlApiGroup existGroup = xxlApiGroupDao.load(xxlApiGroup.getId()); if (existGroup == null) { return new ReturnT(ReturnT.FAIL_CODE, "更新失败,分组ID非法"); } // valid if (StringTool.isBlank(xxlApiGroup.getName())) { return new ReturnT(ReturnT.FAIL_CODE, "请输入“分组名称”"); } int ret = xxlApiGroupDao.update(xxlApiGroup); return (ret > 0) ? ReturnT.SUCCESS : ReturnT.FAIL; }
万爽
if (list1 == null) { throw new XmallException("查询角色权限失败"); } for (TbRolePerm tbRolePerm : list1) { if (tbRolePermMapper.deleteByPrimaryKey(tbRolePerm.getId()) != 1) { throw new XmallException("删除角色权限失败"); } }
conventional
@Override public int deleteRole(int id) { List<String> list = tbRoleMapper.getUsedRoles(id); if (list == null) { throw new XmallException("查询用户角色失败"); } if (list.size() > 0) { return 0; } if (tbRoleMapper.deleteByPrimaryKey(id) != 1) { throw new XmallException("删除角色失败"); } TbRolePermExample example = new TbRolePermExample(); TbRolePermExample.Criteria criteria = example.createCriteria(); criteria.andRoleIdEqualTo(id); List<TbRolePerm> list1 = tbRolePermMapper.selectByExample(example); return 1; }
万爽
@RequiresPermissions<method*start>org.apache.shiro.authz.annotation.RequiresPermissions<method*end>("sys:dept:list")
annotation
@ApiOperation<method*start>io.swagger.annotations.ApiOperation<method*end>(value = "部门树列表", response<method*start>io.swagger.annotations.ApiOperation.response<method*end> = Response.class, notes<method*start>io.swagger.annotations.ApiOperation.notes<method*end> = "权限编码(sys:dept:list)") @GetMapping<method*start>org.springframework.web.bind.annotation.GetMapping<method*end>("/info") public JsonResponse<method*start>com.king.common.utils.JsonResponse<method*end> info() { long deptId = 0; if (getUserId<method*start>com.king.utils.AbstractController.getUserId<method*end>() != Constant.SUPER_ADMIN<method*start>com.king.common.utils.constant.Constant.SUPER_ADMIN<method*end>) { SysDept dept = sysDeptService.queryObject<method*start>com.king.api.smp.SysDeptService.queryObject<method*end>(getDeptId<method*start>com.king.utils.AbstractController.getDeptId<method*end>()); deptId = dept.getParentId<method*start>com.king.dal.gen.model.smp.SysDept.getParentId<method*end>(); } return JsonResponse.success<method*start>com.king.common.utils.JsonResponse.success<method*end>(deptId); }
万爽
if (authRule != null && authRule.length() > 0) { List<String> authRules = authLoginService.listRuleByAdminId(adminId); // admin 为最高权限 for (String item : authRules) { if (item.equals("admin") || item.equals(authRule)) { return; } } throw new JsonException(ResultEnum.AUTH_FAILED); }
conventional
private void authRuleVerify(String authRule, Long adminId) { }
万爽
// 是否进行权限验证。 properties.setProperty("mail.smtp.auth", "true"); // 0.2确定权限(账号和密码) Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } };
conventional
@Override public Session instance() { // 如果session已经存在了,就不执行了,直接返回对象 if (session != null) return session; // session为空,判断系统是否配置了邮箱相关的参数,配置了继续,没配置白白 SystemConfig systemConfigHost = systemConfigService.selectByKey("mail_host"); String host = systemConfigHost.getValue(); SystemConfig systemConfigUsername = systemConfigService.selectByKey("mail_username"); String username = systemConfigUsername.getValue(); SystemConfig systemConfigPassword = systemConfigService.selectByKey("mail_password"); String password = systemConfigPassword.getValue(); if (StringUtils.isEmpty(host) || StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) return null; Properties properties = new Properties(); properties.setProperty("mail.host", host); // 1 获得连接 /* props:包含配置信息的对象,Properties类型 配置邮箱服务器地址、配置是否进行权限验证(帐号密码验证)等 authenticator:确定权限(帐号和密码) 所以就要在上面构建这两个对象。 */ this.session = Session.getDefaultInstance(properties, authenticator); return this.session; }
万爽
@Permission(Const.ADMIN_NAME)
annotation
@RequestMapping("/setAuthority") @BussinessLog(value = "配置权限", key = "roleId,ids", dict = RoleDict.class) @ResponseBody public Tip setAuthority(@RequestParam("roleId") Integer roleId, @RequestParam("ids") String ids) { if (ToolUtil.isOneEmpty(roleId)) { throw new GunsException(BizExceptionEnum.REQUEST_NULL); } this.roleService.setAuthority(roleId, ids); return SUCCESS_TIP; }
万爽
@RequiresPermissions<method*start>org.apache.shiro.authz.annotation.RequiresPermissions<method*end>("sys:config:save")
annotation
@Log("保存配置") @ApiOperation<method*start>io.swagger.annotations.ApiOperation<method*end>(value = "保存配置", response<method*start>io.swagger.annotations.ApiOperation.response<method*end> = Response.class, notes<method*start>io.swagger.annotations.ApiOperation.notes<method*end> = "权限编码(sys:config:save)") @PostMapping<method*start>org.springframework.web.bind.annotation.PostMapping<method*end>("/save") @DuplicateFilter(check<method*start>com.king.common.annotation.DuplicateFilter.check<method*end> = true) public JsonResponse<method*start>com.king.common.utils.JsonResponse<method*end> save(@RequestBody<method*start>org.springframework.web.bind.annotation.RequestBody<method*end>(required<method*start>org.springframework.web.bind.annotation.RequestBody.required<method*end> = false) SysConfig<method*start>com.king.dal.gen.model.smp.SysConfig<method*end> config) { ValidatorUtils.validateEntity<method*start>com.king.common.utils.validator.ValidatorUtils.validateEntity<method*end>(config); sysConfigService.save<method*start>com.king.api.smp.SysConfigService.save<method*end>(config); return JsonResponse.success<method*start>com.king.common.utils.JsonResponse.success<method*end>(); }
万爽
if (loginUser == null) { request.setAttribute("msg", "没有权限, 请先登录!"); request.getRequestDispatcher("/index.html").forward(request, response); return false; }
conventional
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object loginUser = request.getSession().getAttribute("loginUser"); return true; }
万爽
Permission permission = permissionService.findPermissionById(id); if (permission == null) { modelMap.addAttribute("message", "该权限不存在"); return theme.getAdminTemplate("common/message_tip"); }
conventional
@GetMapping(value = "/permission_update/{id}") public String updatePermissions(@PathVariable Long id, ModelMap modelMap) { modelMap.put("permission", permission); modelMap.addAttribute("admin", getAdminUser()); return theme.getAdminTemplate("admin/admin_permission_update"); }
万爽
int id = Integer.valueOf(username); User user = userMapper.getById(id); if (user == null) { log.info("登录用户id不存在:{}", username); throw new UsernameNotFoundException("用户名 " + username + "不存在"); } // 获取用户权限 List<GrantedAuthority> authorities = new ArrayList<>(); List<Jurisdiction> jurisdictions = jurisdictionMapper.selectByUserId(id); for (Jurisdiction item : jurisdictions) { GrantedAuthority authority = new MyGrantedAuthority(item.getMethod(), item.getUrl()); authorities.add(authority); }
conventional
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { log.info("登录用户id为:{}", username); user.setAuthorities(authorities); log.info("获取用户{}信息成功,权限为:{}", username, authorities); return user; }
万爽
// 验证用户 User user = userService.find(input); if (user == null) { model.addAttribute("error", "username or password is wrong."); return "redirect:/"; } // 授权 String token = UUID.randomUUID().toString(); request.getSession().setAttribute(AuthConst.IS_LOGIN, true); request.getSession().setAttribute(AuthConst.TOKEN, token); // 存储,用于注销 SessionStorage.INSTANCE.set(token, request.getSession()); // 子系统跳转过来的登录请求,授权、存储后,跳转回去 String clientUrl = request.getParameter(AuthConst.CLIENT_URL); if (clientUrl != null && !"".equals(clientUrl)) { // 存储,用于注销 ClientStorage.INSTANCE.set(token, clientUrl); return "redirect:" + clientUrl + "?" + AuthConst.TOKEN + "=" + token; }
conventional
@RequestMapping("/login") public String login(HttpServletRequest request, User input, Model model) { String token = UUID.randomUUID().toString(); request.getSession().setAttribute(AuthConst.IS_LOGIN, true); request.getSession().setAttribute(AuthConst.TOKEN, token); SessionStorage.INSTANCE.set(token, request.getSession()); String clientUrl = request.getParameter(AuthConst.CLIENT_URL); if (clientUrl != null && !"".equals(clientUrl)) { ClientStorage.INSTANCE.set(token, clientUrl); return "redirect:" + clientUrl + "?" + AuthConst.TOKEN + "=" + token; } return "redirect:/"; }
万爽
if (e instanceof UnauthorizedException<method*start>org.apache.shiro.authz.UnauthorizedException<method*end>) { // 请登录 log.error<method*start>org.slf4j.Logger.error<method*end>("无权访问", e); return new ModelAndView<method*start>org.springframework.web.servlet.ModelAndView<method*end>("common/error/403"); } if (e instanceof UnauthorizedException<method*start>org.apache.shiro.authz.UnauthorizedException<method*end>) { attributes.put<method*start>java.util.Map.put<method*end>("msg", "没有权限"); }
conventional
@ExceptionHandler<method*start>org.springframework.web.bind.annotation.ExceptionHandler<method*end>(value<method*start>org.springframework.context.annotation.PropertySource.value<method*end> = Exception<method*start>java.lang.Exception<method*end>.class) public ModelAndView<method*start>org.springframework.web.servlet.ModelAndView<method*end> defaultErrorHandler(HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request, HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response, Exception<method*start>java.lang.Exception<method*end> e, Model<method*start>org.springframework.ui.Model<method*end> model) throws IOException<method*start>java.io.IOException<method*end> { e.printStackTrace<method*start>java.lang.Exception.printStackTrace<method*end>(); if (isAjax(request)) { ModelAndView<method*start>org.springframework.web.servlet.ModelAndView<method*end> mav = new ModelAndView<method*start>org.springframework.web.servlet.ModelAndView<method*end>(); MappingJackson2JsonView<method*start>org.springframework.web.servlet.view.json.MappingJackson2JsonView<method*end> view = new MappingJackson2JsonView<method*start>org.springframework.web.servlet.view.json.MappingJackson2JsonView<method*end>(); Map<method*start>java.util.Map<method*end><String<method*start>java.lang.String<method*end>, Object> attributes = new HashMap<method*start>java.util.HashMap<method*end><String<method*start>java.lang.String<method*end>, Object>(); attributes.put<method*start>java.util.Map.put<method*end>("msg", e.getMessage<method*start>java.lang.Exception.getMessage<method*end>()); attributes.put<method*start>java.util.Map.put<method*end>("code", "0"); view.setAttributesMap<method*start>org.springframework.web.servlet.view.json.MappingJackson2JsonView.setAttributesMap<method*end>(attributes); mav.setView<method*start>org.springframework.web.servlet.ModelAndView.setView<method*end>(view); return mav; } // 其他异常 String<method*start>java.lang.String<method*end> message = e.getMessage<method*start>java.lang.Exception.getMessage<method*end>(); model.addAttribute<method*start>org.springframework.ui.Model.addAttribute<method*end>("code", 500); model.addAttribute<method*start>org.springframework.ui.Model.addAttribute<method*end>("message", message); return new ModelAndView<method*start>org.springframework.web.servlet.ModelAndView<method*end>("common/error/500"); }
万爽
// 权限 if (!hasBizPermission(request, project.getBizId())) { throw new RuntimeException("您没有相关业务线的权限,请联系管理员开通"); }
conventional
@RequestMapping("/addPage") public String addPage(HttpServletRequest request, Model model, int projectId, @RequestParam(required = false, defaultValue = "0") int groupId) { // project XxlApiProject project = xxlApiProjectDao.load(projectId); if (project == null) { throw new RuntimeException("操作失败,项目ID非法"); } model.addAttribute("projectId", projectId); model.addAttribute("groupId", groupId); // groupList List<XxlApiGroup> groupList = xxlApiGroupDao.loadAll(projectId); model.addAttribute("groupList", groupList); // enum model.addAttribute("RequestMethodEnum", RequestConfig.RequestMethodEnum.values()); model.addAttribute("requestHeadersEnum", RequestConfig.requestHeadersEnum); model.addAttribute("QueryParamTypeEnum", RequestConfig.QueryParamTypeEnum.values()); model.addAttribute("ResponseContentType", RequestConfig.ResponseContentType.values()); return "document/document.add"; }
万爽
if (sessionUser != null) { return true; }
conventional
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { WxWebUser sessionUser = WxWebUtils.getWxWebUserFromSession(request); String code = request.getParameter("code"); String state = request.getParameter("state"); if (!StringUtils.isEmpty(code)) { WxWebUser wxWebUser = wxUserManager.getWxWebUser(code); if (wxWebUser != null && wxWebUser.getOpenId() != null) { if (wxOAuth2Callback != null) { wxOAuth2Callback.after(new WxOAuth2Callback.WxOAuth2Context(wxWebUser, state, response, request)); } WxWebUtils.setWxWebUserToSession(request, wxWebUser); // 但本身这个code就是只能用一次的,故暂时不增加一次重定向 return true; } } String requestUrl = getRequestUrl(request); logger.info("WxOAuth2Interceptor request url is : " + requestUrl); // 如果重定向到授权,则肯定可以获得信息,但是如果重定向到基本,则无法获得信息,所以默认重定向到授权。默认为授权。 String redirectUrl = WxRedirectUtils.redirect(requestUrl); logger.info("WxOAuth2Interceptor redirect to auth url : " + redirectUrl); response.sendRedirect(redirectUrl); return false; }
万爽
if (stepNode == null) { throw new NoRecordFoundException<method*start>com.rebuild.server.helper.cache.NoRecordFoundException<method*end>("记录不存在或无权查看:" + this.record<method*start>com.rebuild.server.business.approval.ApprovalProcessor.record<method*end>); }
conventional
private String<method*start>java.lang.String<method*end> getCurrentNodeId() { Object<method*start>java.lang.Object<method*end>[] stepNode = Application.getQueryFactory<method*start>com.rebuild.server.Application.getQueryFactory<method*end>().unique<method*start>com.rebuild.server.service.query.QueryFactory.unique<method*end>(this.record<method*start>com.rebuild.server.business.approval.ApprovalProcessor.record<method*end>, EntityHelper.ApprovalStepNode<method*start>com.rebuild.server.metadata.EntityHelper.ApprovalStepNode<method*end>, EntityHelper.ApprovalState<method*start>com.rebuild.server.metadata.EntityHelper.ApprovalState<method*end>); String<method*start>java.lang.String<method*end> cNode = (String<method*start>java.lang.String<method*end>) stepNode[0]; if (StringUtils.isBlank<method*start>org.apache.commons.lang.StringUtils.isBlank<method*end>(cNode) || (Integer<method*start>java.lang.Integer<method*end>) stepNode[1] >= ApprovalState.REJECTED.getState<method*start>com.rebuild.server.business.approval.ApprovalState.getState<method*end>()) { cNode = "ROOT"; } return cNode; }
万爽
http.antMatcher("/**").authorizeRequests().anyRequest().authenticated().withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() { @Override public <O extends FilterSecurityInterceptor> O postProcess(O o) { // 动态获取url权限配置 o.setSecurityMetadataSource(filterInvocationSecurityMetadataSource); // 权限判断 o.setAccessDecisionManager(accessDecisionManager); return o; } }); // 将session策略设置为无状态的,通过token进行权限认证 //
conventional
protected void configure(HttpSecurity http) throws Exception { // 关闭csrf验证(防止跨站请求伪造攻击) http.csrf().disable(); // 未登录时:返回状态码401 http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); // 无权访问时:返回状态码403 http.exceptionHandling().accessDeniedHandler(accessDeniedHandler); // url权限认证处理 http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 开启自动配置的登录功能 // 开启登录 // 自定义登录请求路径(post) http.formLogin().loginProcessingUrl("/nonceLogin").usernameParameter("username").passwordParameter("password").successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler).authenticationDetailsSource(authenticationDetailsSource); // 开启自动配置的注销功能 // 用户注销, 清空session // 自定义注销请求路径 http.logout().logoutUrl("/nonceLogout").logoutSuccessHandler(logoutSuccessHandler); }
万爽
if (blogger == null) { log.info("无权限------->403.html"); return "errors/403"; }
conventional
@RequestMapping("/main") public String main() { Blogger blogger = (Blogger) SecurityUtils.getSubject().getSession().getAttribute("currentUser"); log.info("正常登录----->main.html"); return "main"; }
万爽
// 权限申请 AndPermission.with<method*start>com.yanzhenjie.permission.AndPermission.with<method*end>(mContext<method*start>com.loubii.account.ui.avtivity.BaseActivity.mContext<method*end>).requestCode<method*start>com.yanzhenjie.permission.option.Option.requestCode<method*end>(100).permission(Manifest.permission.READ_CALENDAR<method*start>android.Manifest.permission.READ_CALENDAR<method*end>, Manifest.permission.WRITE_CALENDAR<method*start>android.Manifest.permission.WRITE_CALENDAR<method*end>).callback(new PermissionListener<method*start>com.yanzhenjie.permission.PermissionListener<method*end>() { @Override public void onSucceed(int requestCode, @NonNull<method*start>android.support.annotation.NonNull<method*end> List<String<method*start>java.lang.String<method*end>> grantPermissions) { CalenderRemind.deleteCalendarEvent<method*start>com.loubii.account.util.CalenderRemind.deleteCalendarEvent<method*end>(mContext<method*start>com.loubii.account.ui.avtivity.BaseActivity.mContext<method*end>, "test"); } @Override public void onFailed(int requestCode, @NonNull<method*start>android.support.annotation.NonNull<method*end> List<String<method*start>java.lang.String<method*end>> deniedPermissions) { } }).start();
conventional
private void deleteCalender() { CalenderRemind.deleteCalendarEvent<method*start>com.loubii.account.util.CalenderRemind.deleteCalendarEvent<method*end>(mContext<method*start>com.loubii.account.ui.avtivity.BaseActivity.mContext<method*end>, "test"); }
万爽
if (userRoles != null)
conventional
@Override public void assertIsSystemAdmin(String userName) throws SaturnJobConsoleException { if (!isAuthorizationEnabled()) { return; } User user = getUser(userName); List<UserRole> userRoles = user.getUserRoles(); for (UserRole userRole : userRoles) { if (systemAdminRoleKey.equals(userRole.getRoleKey())) { return; } } }
万爽
// 检查用户所传递的 token 是否合法 String<method*start>java.lang.String<method*end> token = getUserToken<method*start>com.xys.demo1.HttpAopAdviseDefine.getUserToken<method*end>(request); if (!token.equalsIgnoreCase<method*start>java.lang.String.equalsIgnoreCase<method*end>("123456")) { return "错误, 权限不合法!"; }
conventional
@Around<method*start>org.aspectj.lang.annotation.Around<method*end>("pointcut()") public Object<method*start>java.lang.Object<method*end> checkAuth(ProceedingJoinPoint<method*start>org.aspectj.lang.ProceedingJoinPoint<method*end> joinPoint) throws Throwable<method*start>java.lang.Throwable<method*end> { HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request = ((ServletRequestAttributes<method*start>org.springframework.web.context.request.ServletRequestAttributes<method*end>) RequestContextHolder.getRequestAttributes<method*start>org.springframework.web.context.request.RequestContextHolder.getRequestAttributes<method*end>()).getRequest<method*start>org.springframework.web.context.request.ServletRequestAttributes.getRequest<method*end>(); return joinPoint.proceed<method*start>org.aspectj.lang.ProceedingJoinPoint.proceed<method*end>(); }
万爽
// 登陆者的权限 if (user.getId() == null) { session.removeAttribute(Globals.USER_SESSION); modelAndView.setView(new RedirectView("loginController.do?login")); }
conventional
@RequestMapping(params = "left") public ModelAndView left(HttpServletRequest request) { TSUser user = ResourceUtil.getSessionUser(); HttpSession session = ContextHolderUtils.getSession(); ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("main/left"); request.setAttribute("menuMap", userService.getFunctionMap(user.getId())); return modelAndView; }
万爽
if (user == null) { throw new UsernameNotFoundException("用户不存在"); } // 如果是管理员则有所有权限 if (user.isIssys()) { auths = staffService.loadAllAuthorities(); }
conventional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>(); // 根据用户名取得一个SysUsers对象,以获取该用户的其他信息。 SysUsers user = staffService.findByUserAccount(username); // 得到用户的权限 auths = staffService.loadUserAuthoritiesByName(username); return new SysUsers(user.getUserId(), user.getUserAccount(), user.getUserDesc(), user.isEnabled(), user.isIssys(), user.getSecurityDigest(), user.getUserDuty(), true, true, true, auths); }
万爽
@RequiresPermissions("permission:insert")
annotation
@ApiOperation(value = "新增权限", httpMethod = "POST", produces = "application/json", response = Result.class) @ResponseBody @RequestMapping(value = "insert", method = RequestMethod.POST) public Result insert(@RequestParam long groupId, @RequestParam String name, @RequestParam String code, @RequestParam String description, @RequestParam(defaultValue = "1") int isFinal) { boolean isExistName = sysPermissionService.isExistName(groupId, name); boolean isExistCode = sysPermissionService.isExistCode(groupId, code); System.out.println(isExistName); System.out.println(isExistCode); if (isExistName) { return Result.error("该分组下名称已存在1"); } if (isExistCode) { return Result.error("该权限分组下编码已存在已存在"); } SysPermission sysPermission = new SysPermission(); sysPermission.setName(name); sysPermission.setCode(code); sysPermission.setDescription(description); sysPermission.setIsFinal(isFinal); sysPermission.setSysPermissionGroupId(groupId); long id = sysPermissionService.insertPermission(sysPermission); return Result.success(id); }
万爽
if (activity.checkCallingOrSelfPermission<method*start>android.app.Activity.checkCallingOrSelfPermission<method*end>(Manifest.permission.INTERNET<method*start>android.Manifest.permission.INTERNET<method*end>) != PackageManager.PERMISSION_GRANTED<method*start>android.content.pm.PackageManager.PERMISSION_GRANTED<method*end>) { CommonUtil.showAlert<method*start>com.baidu.duer.dcs.util.CommonUtil.showAlert<method*end>(activity, "没有权限", "应用需要访问互联网的权限"); }
conventional
private void authorize(Activity<method*start>android.app.Activity<method*end> activity, String<method*start>java.lang.String<method*end>[] permissions, boolean isForceLogin, boolean isConfirmLogin, final BaiduDialogListener<method*start>com.baidu.duer.dcs.oauth.api.BaiduDialog.BaiduDialogListener<method*end> listener, String<method*start>java.lang.String<method*end> redirectUrl, String<method*start>java.lang.String<method*end> responseType) { CookieSyncManager.createInstance<method*start>android.webkit.CookieSyncManager.createInstance<method*end>(activity); Bundle<method*start>android.os.Bundle<method*end> params = new Bundle<method*start>android.os.Bundle<method*end>(); params.putString<method*start>android.os.Bundle.putString<method*end>("client_id", this.cliendId<method*start>com.baidu.duer.dcs.oauth.api.BaiduOauthImplicitGrant.cliendId<method*end>); params.putString<method*start>android.os.Bundle.putString<method*end>("redirect_uri", redirectUrl); params.putString<method*start>android.os.Bundle.putString<method*end>("response_type", responseType); params.putString<method*start>android.os.Bundle.putString<method*end>("display", DISPLAY_STRING); if (isForceLogin) { params.putString<method*start>android.os.Bundle.putString<method*end>("force_login", "1"); } if (isConfirmLogin) { params.putString<method*start>android.os.Bundle.putString<method*end>("confirm_login", "1"); } if (permissions == null) { permissions = DEFAULT_PERMISSIONS; } if (permissions != null && permissions.length<method*start>java.lang.String[].length<method*end> > 0) { String<method*start>java.lang.String<method*end> scope = TextUtils.join<method*start>android.text.TextUtils.join<method*end>(" ", permissions); params.putString<method*start>android.os.Bundle.putString<method*end>("scope", scope); } params.putString<method*start>android.os.Bundle.putString<method*end>("qrcode", "1"); String<method*start>java.lang.String<method*end> url = OAUTHORIZE_URL + "?" + CommonUtil.encodeUrl<method*start>com.baidu.duer.dcs.util.CommonUtil.encodeUrl<method*end>(params); LogUtil.d<method*start>com.baidu.duer.dcs.util.LogUtil.d<method*end>(LOG_TAG, "url:" + url); }
万爽
@RequiresPermissions("配置管理:权限管理:后台用户管理")
annotation
@MetaData(value = "汇总用户关联权限集合") @RequestMapping(value = "/privileges", method = RequestMethod.GET) public String privileges(Model model, User entity) { Set<Long> r2PrivilegeIds = Sets.newHashSet(); List<Privilege> privileges = privilegeService.findAllCached(); List<UserR2Role> userR2Roles = entity.getUserR2Roles(); boolean isAdmin = false; for (UserR2Role r2 : userR2Roles) { if (r2.getRole().getCode().equals(DefaultAuthUserDetails.ROLE_SUPER_USER)) { isAdmin = true; break; } } if (isAdmin) { for (Privilege privilege : privileges) { r2PrivilegeIds.add(privilege.getId()); } } else { for (UserR2Role userR2Role : userR2Roles) { Role role = roleService.findOne(userR2Role.getRole().getId()); List<RoleR2Privilege> roleR2Privileges = role.getRoleR2Privileges(); for (RoleR2Privilege roleR2Privilege : roleR2Privileges) { r2PrivilegeIds.add(roleR2Privilege.getPrivilege().getId()); } } } model.addAttribute("r2PrivilegeIds", StringUtils.join(r2PrivilegeIds, ",")); return "admin/auth/user-privileges"; }
万爽
@RequiresPermissions<method*start>org.apache.shiro.authz.annotation.RequiresPermissions<method*end>("oss:water:setting")
annotation
@Log(value = "修改水印", update<method*start>com.king.common.annotation.Log.update<method*end> = true, serviceClass<method*start>com.king.common.annotation.Log.serviceClass<method*end> = OssDoc2pdfService.class, method<method*start>com.king.common.annotation.Log.method<method*end> = "queryWaterSetting") @ApiOperation<method*start>io.swagger.annotations.ApiOperation<method*end>(value = "修改", notes<method*start>io.swagger.annotations.ApiOperation.notes<method*end> = "权限编码(oss:water:setting)") @PostMapping<method*start>org.springframework.web.bind.annotation.PostMapping<method*end>("/waterSetting") public JsonResponse<method*start>com.king.common.utils.JsonResponse<method*end> saveOrUpdate(@RequestBody<method*start>org.springframework.web.bind.annotation.RequestBody<method*end>(required<method*start>org.springframework.web.bind.annotation.RequestBody.required<method*end> = false) OssWaterSetting<method*start>com.king.dal.gen.model.oss.OssWaterSetting<method*end> ossWaterSetting) { ossWaterSetting.setUserId<method*start>com.king.dal.gen.model.oss.OssWaterSetting.setUserId<method*end>(getUserId<method*start>com.king.utils.AbstractController.getUserId<method*end>()); ossWaterSetting.setCreator<method*start>com.king.dal.gen.model.oss.OssWaterSetting.setCreator<method*end>(getUser<method*start>com.king.utils.AbstractController.getUser<method*end>().getUsername<method*start>com.king.dal.gen.model.smp.SysUser.getUsername<method*end>()); ossWaterSetting.setCreateTime<method*start>com.king.dal.gen.model.oss.OssWaterSetting.setCreateTime<method*end>(new Date<method*start>java.util.Date<method*end>()); ossDoc2pdfService.saveOrUpdate<method*start>com.king.api.oss.OssDoc2pdfService.saveOrUpdate<method*end>(ossWaterSetting); return JsonResponse.success<method*start>com.king.common.utils.JsonResponse.success<method*end>(); }
万爽
// 检查该权限是否已经获取 if (!checkPermission(context, permission)) { noPermission.add<method*start>java.util.List.add<method*end>(permission); }
conventional
@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 String<method*start>java.lang.String<method*end>[] checkPermission(Context<method*start>android.content.Context<method*end> context, @NonNull<method*start>android.support.annotation.NonNull<method*end> String... permissions) { List<method*start>java.util.List<method*end><String> noPermission = new ArrayList<method*start>java.util.ArrayList<method*end><>(); for (String permission : permissions) { } String[] result = new String[noPermission.size<method*start>java.util.List.size<method*end>()]; return noPermission.toArray<method*start>java.util.List.toArray<method*end>(result); }
万爽
@RequiresPermissions("配置管理:权限管理:部门配置")
annotation
@RequestMapping(value = "/tree", method = RequestMethod.GET) @ResponseBody public MappingJacksonValue findTreeData(GroupPropertyFilter filter, Pageable pageable, HttpServletRequest request) { filter.forceAnd(new PropertyFilter(MatchType.NE, "disabled", true)); Object value = departmentService.findByPage(filter, pageable); final MappingJacksonValue jacksonValue = new MappingJacksonValue(value); jacksonValue.setSerializationView(PropertyFilter.parseJsonView(request, JsonViews.Tree.class)); return jacksonValue; }
肖敬先
@RequiresPermissions(value = { "resource:batchDelete", "resource:delete" }, logical = Logical.OR)
annotation
@PostMapping(value = "/remove") @BussinessLog("删除资源") public ResponseVO<com.zyd.blog.framework.object.ResponseVO> remove(Long[] ids) { if (null == ids) { return ResultUtil.error(500, "请至少选择一条记录"); } for (Long id : ids) { resourcesService.removeByPrimaryKey(id); } // 更新权限 shiroService.updatePermission(); return ResultUtil.success("成功删除 [" + ids.length + "] 个资源"); }
肖敬先
if (!TextUtils.isEmpty(wxAuthorizationVo.getErrorMsg())) { return Response.error(wxAuthorizationVo.getErrorCode(), wxAuthorizationVo.getErrorMsg()); }
conventional
@PostMapping(value = "/authentication") public Response authentication(HttpServletRequest request, @RequestBody JSONObject json) { // 邀请者的openId String openId = json.getString("openId"); // 微信授权码 String code = json.getString("code"); AuthorizationVo wxAuthorizationVo = authenticationService.authentication(request, openId, code); return Response.ok().putObject(wxAuthorizationVo); }
万爽
// 无权限 if (exception instanceof UnauthorizedException<method*start>org.apache.shiro.authz.UnauthorizedException<method*end>) { return "/403.jsp"; } // shiro session 过期 if (exception instanceof InvalidSessionException<method*start>org.apache.shiro.session.InvalidSessionException<method*end>) { return "/error.jsp"; }
conventional
@ExceptionHandler<method*start>org.springframework.web.bind.annotation.ExceptionHandler<method*end> public String<method*start>java.lang.String<method*end> exceptionHandler(HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request, HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response, Exception<method*start>java.lang.Exception<method*end> exception) { _log.error<method*start>org.slf4j.Logger.error<method*end>("统一异常处理:", exception); request.setAttribute<method*start>javax.servlet.http.HttpServletRequest.setAttribute<method*end>("ex", exception); if (null != request.getHeader<method*start>javax.servlet.http.HttpServletRequest.getHeader<method*end>("X-Requested-With") && request.getHeader<method*start>javax.servlet.http.HttpServletRequest.getHeader<method*end>("X-Requested-With").equalsIgnoreCase<method*start>java.lang.String.equalsIgnoreCase<method*end>("XMLHttpRequest")) { request.setAttribute<method*start>javax.servlet.http.HttpServletRequest.setAttribute<method*end>("requestHeader", "ajax"); } return "/error.jsp"; }
万爽
@RequiresPermissions("permission:group:insert")
annotation
@ApiOperation(value = "新增权限组", httpMethod = "POST", produces = "application/json", response = Result.class) @ResponseBody @RequestMapping(value = "group/insert", method = RequestMethod.POST) public Result insertGroup(@RequestParam String name, @RequestParam String description) { boolean isExistGroupName = sysPermissionService.isExistGroupName(name); if (isExistGroupName) { return Result.error(ResponseCode.name_already_exist.getMsg()); } SysPermissionGroup sysPermissionGroup = new SysPermissionGroup(); sysPermissionGroup.setName(name); sysPermissionGroup.setDescription(description); sysPermissionGroup.setIsFinal(2); long id = sysPermissionService.insertPermissionGroup(sysPermissionGroup); return Result.success(id); }
万爽
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_USER','ROLE_VISTOR')")
annotation
@PostMapping public ResponseEntity<Response<com.whichard.spring.boot.blog.vo.Response>> createVote(Long blogId) { try { blogService.createVote(blogId); } catch (ConstraintViolationException e) { return ResponseEntity.ok().body(new Response(false, ConstraintViolationExceptionHandler.getMessage(e))); } catch (Exception e) { return ResponseEntity.ok().body(new Response(false, e.getMessage())); } return ResponseEntity.ok().body(new Response(true, "点赞成功", null)); }
万爽
@RequiresPermissions("membership.permission:view")
annotation
@GetMapping(value = "/list") @OpLog(name = "获取权限列表") public Map<String, Object> list(final DataGridPager pager, final Integer id) { final int moduleId = (id == null ? 0 : id); final PageInfo pageInfo = pager.toPageInfo(); final List<Permission> list = this.service.getByPage(pageInfo, moduleId); final Map<String, Object> modelMap = new HashMap<>(2); modelMap.put("total", list.size()); modelMap.put("rows", list); return modelMap; }
万爽
SmsStaff staff = smsStaffService.selectByUserName(username); if (staff != null)
conventional
@Bean public UserDetailsService userDetailsService() { // 获取登录用户信息 return username -> { // 保证了User存在且状态不为0 SmsStaff staff = smsStaffService.selectByUserName(username); if (staff != null) { // 拉取权限 List<SmsPermission> permissionList = smsRoleService.getPermissionList(staff.getId()); return new StaffDetails(staff, permissionList); } throw new UsernameNotFoundException("用户名或密码错误"); }; }
万爽
Boolean status = authService.domainAuth(request, domainId, "r").getStatus(); if (status) { return Hret.error(403, "您没有被授权访问域【" + domainId + "】", null); }
conventional
@RequestMapping(value = "/details", method = RequestMethod.GET) @ApiOperation(value = "查询域的详细信息", notes = "查询某一个指定域的详细定义信息,如果请求的参数为空,则返回用户自己所在域的详细信息") @ApiImplicitParams({ @ApiImplicitParam(required = true, name = "domain_id", value = "域编码") }) public String getDomainDetails(HttpServletRequest request) { String domainId = request.getParameter("domain_id"); if (domainId == null || domainId.isEmpty()) { logger.info("domain id is empty, return null"); return null; } DomainEntity domainEntity = domainService.getDomainDetails(domainId); return new GsonBuilder().create().toJson(domainEntity); }
万爽
authRuleVerify<method*start>com.lmxdawn.api.admin.aspect.AuthorizeAspect.authRuleVerify<method*end>(action.value<method*start>com.lmxdawn.api.admin.annotation.AuthRuleAnnotation.value<method*end>(), adminId);
conventional
@Before<method*start>org.aspectj.lang.annotation.Before<method*end>("adminLoginVerify()") public void doAdminAuthVerify(JoinPoint<method*start>org.aspectj.lang.JoinPoint<method*end> joinPoint) { ServletRequestAttributes<method*start>org.springframework.web.context.request.ServletRequestAttributes<method*end> attributes = (ServletRequestAttributes<method*start>org.springframework.web.context.request.ServletRequestAttributes<method*end>) RequestContextHolder.getRequestAttributes<method*start>org.springframework.web.context.request.RequestContextHolder.getRequestAttributes<method*end>(); if (attributes == null) { throw new JsonException<method*start>com.lmxdawn.api.admin.exception.JsonException<method*end>(ResultEnum.NOT_NETWORK<method*start>com.lmxdawn.api.common.enums.ResultEnum.NOT_NETWORK<method*end>); } HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request = attributes.getRequest<method*start>org.springframework.web.context.request.ServletRequestAttributes.getRequest<method*end>(); String<method*start>java.lang.String<method*end> id = request.getHeader<method*start>javax.servlet.http.HttpServletRequest.getHeader<method*end>("X-Adminid"); Long<method*start>java.lang.Long<method*end> adminId = null; try { adminId = Long.valueOf<method*start>java.lang.Long.valueOf<method*end>(id); } catch (Exception<method*start>java.lang.Exception<method*end> e) { throw new JsonException<method*start>com.lmxdawn.api.admin.exception.JsonException<method*end>(ResultEnum.LOGIN_VERIFY_FALL<method*start>com.lmxdawn.api.common.enums.ResultEnum.LOGIN_VERIFY_FALL<method*end>); } String<method*start>java.lang.String<method*end> token = request.getHeader<method*start>javax.servlet.http.HttpServletRequest.getHeader<method*end>("X-Token"); if (token == null) { throw new JsonException<method*start>com.lmxdawn.api.admin.exception.JsonException<method*end>(ResultEnum.LOGIN_VERIFY_FALL<method*start>com.lmxdawn.api.common.enums.ResultEnum.LOGIN_VERIFY_FALL<method*end>); } // 验证 token Claims<method*start>io.jsonwebtoken.Claims<method*end> claims = JwtUtils.parse<method*start>com.lmxdawn.api.admin.util.JwtUtils.parse<method*end>(token); if (claims == null) { throw new JsonException<method*start>com.lmxdawn.api.admin.exception.JsonException<method*end>(ResultEnum.LOGIN_VERIFY_FALL<method*start>com.lmxdawn.api.common.enums.ResultEnum.LOGIN_VERIFY_FALL<method*end>); } Long<method*start>java.lang.Long<method*end> jwtAdminId = Long.valueOf<method*start>java.lang.Long.valueOf<method*end>(claims.get<method*start>io.jsonwebtoken.Claims.get<method*end>("admin_id").toString<method*start>org.geolatte.geom.V.toString<method*end>()); if (adminId.compareTo<method*start>java.lang.Long.compareTo<method*end>(jwtAdminId) != 0) { throw new JsonException<method*start>com.lmxdawn.api.admin.exception.JsonException<method*end>(ResultEnum.LOGIN_VERIFY_FALL<method*start>com.lmxdawn.api.common.enums.ResultEnum.LOGIN_VERIFY_FALL<method*end>); } // 判断是否进行权限验证 MethodSignature<method*start>org.aspectj.lang.reflect.MethodSignature<method*end> signature = (MethodSignature<method*start>org.aspectj.lang.reflect.MethodSignature<method*end>) joinPoint.getSignature<method*start>org.aspectj.lang.JoinPoint.getSignature<method*end>(); // 从切面中获取当前方法 Method<method*start>java.lang.reflect.Method<method*end> method = signature.getMethod<method*start>org.aspectj.lang.reflect.MethodSignature.getMethod<method*end>(); // 得到了方,提取出他的注解 AuthRuleAnnotation action = method.getAnnotation<method*start>java.lang.reflect.Method.getAnnotation<method*end>(AuthRuleAnnotation.class); }
万爽
if (!isOwner) { return ResponseEntity.ok().body(new Response(false, "没有操作权限")); }
conventional
@DeleteMapping("/{id}") public ResponseEntity<Response<com.whichard.spring.boot.blog.vo.Response>> delete(@PathVariable("id") Long id, Long blogId) { boolean isOwner = false; User user = voteService.getVoteById(id).getUser(); if (SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().isAuthenticated() && !SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString().equals("anonymousUser")) { User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal != null && user.getUsername().equals(principal.getUsername())) { isOwner = true; } } 、 try { blogService.removeVote(blogId, id); voteService.removeVote(id); } catch (ConstraintViolationException e) { return ResponseEntity.ok().body(new Response(false, ConstraintViolationExceptionHandler.getMessage(e))); } catch (Exception e) { return ResponseEntity.ok().body(new Response(false, e.getMessage())); } return ResponseEntity.ok().body(new Response(true, "取消点赞成功", null)); }
万爽
Boolean status = authService.domainAuth(request, domainId, "r").getStatus(); if (status) { return Hret.error(403, "您没有被授权访问域【" + domainId + "】", null); }
conventional
@RequestMapping(value = "/details", method = RequestMethod.GET) @ApiOperation(value = "查询域的详细信息", notes = "查询某一个指定域的详细定义信息,如果请求的参数为空,则返回用户自己所在域的详细信息") @ApiImplicitParams({ @ApiImplicitParam(required = true, name = "domain_id", value = "域编码") }) public String getDomainDetails(HttpServletRequest request) { String domainId = request.getParameter("domain_id"); if (domainId == null || domainId.isEmpty()) { logger.info("domain id is empty, return null"); return null; } DomainEntity domainEntity = domainService.getDomainDetails(domainId); return new GsonBuilder().create().toJson(domainEntity); }
肖敬先
// 查询项目,同时校验用户权限 MetaProjectPO<method*start>com.youran.generate.pojo.po.MetaProjectPO<method*end> project = metaProjectService.getAndCheckProject<method*start>com.youran.generate.service.MetaProjectService.getAndCheckProject<method*end>(metaField.getProjectId<method*start>com.youran.generate.pojo.po.MetaFieldPO.getProjectId<method*end>());
conventional
@Transactional<method*start>org.springframework.transaction.annotation.Transactional<method*end>(rollbackFor<method*start>org.springframework.transaction.annotation.Transactional.rollbackFor<method*end> = RuntimeException<method*start>java.lang.RuntimeException<method*end>.class) @OptimisticLock<method*start>com.youran.common.optimistic.OptimisticLock<method*end> public MetaFieldPO<method*start>com.youran.generate.pojo.po.MetaFieldPO<method*end> update(MetaFieldUpdateDTO<method*start>com.youran.generate.pojo.dto.MetaFieldUpdateDTO<method*end> updateDTO) { Integer<method*start>java.lang.Integer<method*end> fieldId = updateDTO.getFieldId<method*start>com.youran.generate.pojo.dto.MetaFieldUpdateDTO.getFieldId<method*end>(); MetaFieldPO<method*start>com.youran.generate.pojo.po.MetaFieldPO<method*end> metaField = this.getField<method*start>com.youran.generate.service.MetaFieldService.getField<method*end>(fieldId, true); Integer<method*start>java.lang.Integer<method*end> entityId = metaField.getEntityId<method*start>com.youran.generate.pojo.po.MetaFieldPO.getEntityId<method*end>(); MetaProjectPO<method*start>com.youran.generate.pojo.po.MetaProjectPO<method*end> project = metaProjectService.getAndCheckProject<method*start>com.youran.generate.service.MetaProjectService.getAndCheckProject<method*end>(metaField.getProjectId<method*start>com.youran.generate.pojo.po.MetaFieldPO.getProjectId<method*end>()); MetaFieldMapper.INSTANCE.setPO<method*start>com.youran.generate.pojo.mapper.MetaFieldMapper.setPO<method*end>(metaField, updateDTO); // 校验字段名 MetadataUtil.jfieldNameCheck<method*start>com.youran.generate.util.MetadataUtil.jfieldNameCheck<method*end>(updateDTO.getJfieldName<method*start>com.youran.generate.pojo.dto.MetaFieldAddDTO.getJfieldName<method*end>()); metaFieldDAO.update<method*start>com.youran.generate.dao.MetaFieldDAO.update<method*end>(metaField); // 校验字段属性 MetadataUtil.checkFieldPO<method*start>com.youran.generate.util.MetadataUtil.checkFieldPO<method*end>(metaField); metaProjectService.updateProject<method*start>com.youran.generate.service.MetaProjectService.updateProject<method*end>(project); return metaField; }
肖敬先
List<method*start>java.util.List<method*end><GrantType<method*start>com.github.vole.mps.constants.GrantType<method*end>> grantTypes = new ArrayList<method*start>java.util.ArrayList<method*end><GrantType<method*start>com.github.vole.mps.constants.GrantType<method*end>>(); GrantType<method*start>com.github.vole.mps.constants.GrantType<method*end> client = new GrantType<method*start>com.github.vole.mps.constants.GrantType<method*end>("client", "客户端验证"); grantTypes.add<method*start>java.util.List.add<method*end>(client); GrantType<method*start>com.github.vole.mps.constants.GrantType<method*end> password = new GrantType<method*start>com.github.vole.mps.constants.GrantType<method*end>("password", "用户名密码验证"); grantTypes.add<method*start>java.util.List.add<method*end>(password); GrantType<method*start>com.github.vole.mps.constants.GrantType<method*end> refreshToken = new GrantType<method*start>com.github.vole.mps.constants.GrantType<method*end>("refresh_token", "刷新验证"); grantTypes.add<method*start>java.util.List.add<method*end>(refreshToken); GrantType<method*start>com.github.vole.mps.constants.GrantType<method*end> authorizationCode = new GrantType<method*start>com.github.vole.mps.constants.GrantType<method*end>("authorization_code", "授权验证"); grantTypes.add<method*start>java.util.List.add<method*end>(authorizationCode);
conventional
public static List<method*start>java.util.List<method*end><GrantType<method*start>com.github.vole.mps.constants.GrantType<method*end>> list() { return grantTypes; }
肖敬先
@AuthRuleAnnotation("admin/auth/role/auth")
annotation
@PostMapping("/admin/auth/role/auth") public BaseResponse<method*start>com.lmxdawn.api.common.res.BaseResponse<method*end> auth(@RequestBody @Valid AuthRoleAuthRequest authRoleAuthRequest, BindingResult<method*start>org.springframework.validation.BindingResult<method*end> bindingResult) { if (bindingResult.hasErrors<method*start>org.springframework.validation.BindingResult.hasErrors<method*end>()) { return ResultVOUtils.error<method*start>com.lmxdawn.api.common.util.ResultVOUtils.error<method*end>(ResultEnum.PARAM_VERIFY_FALL<method*start>com.lmxdawn.api.common.enums.ResultEnum.PARAM_VERIFY_FALL<method*end>, bindingResult.getFieldError<method*start>org.springframework.validation.BindingResult.getFieldError<method*end>().getDefaultMessage<method*start>org.springframework.validation.FieldError.getDefaultMessage<method*end>()); } List<method*start>java.util.List<method*end><AuthPermission<method*start>com.lmxdawn.api.admin.entity.auth.AuthPermission<method*end>> authPermissionList = authRoleAuthRequest.getAuthRules<method*start>com.lmxdawn.api.admin.req.auth.AuthRoleAuthRequest.getAuthRules<method*end>().stream<method*start>java.util.List.stream<method*end>().map<method*start>java.util.stream.Stream.map<method*end>(aLong -> { AuthPermission<method*start>com.lmxdawn.api.admin.entity.auth.AuthPermission<method*end> authPermission = new AuthPermission<method*start>com.lmxdawn.api.admin.entity.auth.AuthPermission<method*end>(); authPermission.setRoleId<method*start>com.lmxdawn.api.admin.entity.auth.AuthPermission.setRoleId<method*end>(authRoleAuthRequest.getRoleId<method*start>com.lmxdawn.api.admin.req.auth.AuthRoleAuthRequest.getRoleId<method*end>()); authPermission.setPermissionRuleId<method*start>com.lmxdawn.api.admin.entity.auth.AuthPermission.setPermissionRuleId<method*end>(aLong); authPermission.setType<method*start>com.lmxdawn.api.admin.entity.auth.AuthPermission.setType<method*end>("admin"); return authPermission; }).collect(Collectors.toList<method*start>java.util.stream.Collectors.toList<method*end>()); int i = authPermissionService.insertAuthPermissionAll<method*start>com.lmxdawn.api.admin.service.auth.AuthPermissionService.insertAuthPermissionAll<method*end>(authPermissionList); return ResultVOUtils.success<method*start>com.lmxdawn.api.common.util.ResultVOUtils.success<method*end>(); }
肖敬先
if (id == 1) { return data = DataVo.failure("超级管理员组不能删除"); }
conventional
@PostMapping("/group_del") @ResponseBody public DataVo deleteGroup(@RequestParam(value = "id") Long id) { DataVo data = DataVo.failure("操作失败"); if (groupService.deleteGroup(id)) { data = DataVo.success("该权限组已删除"); } else { data = DataVo.failure("删除失败或者不存在!"); } return data; }
肖敬先
if (imMgr.validation(userID, token) != 0) { rsp.setCode(7); rsp.setMessage("请求失败,鉴权失败"); log.error("setCustomInfo失败:鉴权失败:" + "userID:" + userID); return rsp; }
conventional
@Override public GetCustomInfoRsp setCustomInfo(String userID, String token, SetCustomInfoReq req, int type) { GetCustomInfoRsp rsp = new GetCustomInfoRsp(); String roomID = req.getRoomID(); String fieldName = req.getFieldName(); String operation = req.getOperation(); if (userID == null || token == null || roomID == null || fieldName == null || operation == null) { rsp.setCode(2); rsp.setMessage("请求失败,缺少参数"); log.error("setCustomInfo失败:缺少参数:" + "userID:" + userID + ",token: " + token + ", roomID:" + roomID + ", fieldName:" + fieldName + ", operation:" + operation + ",type: " + type); return rsp; } if (!roomMgr.isRoomExist(roomID, type)) { rsp.setCode(3); rsp.setMessage("请求失败,房间不存在"); log.error("setCustomInfo失败:房间成员不存在:" + "userID:" + userID + ", roomID:" + roomID + ",type: " + type); return rsp; } rsp.setCustomInfo(roomMgr.setCustomInfo(roomID, fieldName, operation, type)); return null; }
肖敬先
if (map == null || map.size() == 0 || !map.containsKey(0)) { return "不具有任何权限,\n请找管理员分配权限"; }
conventional
public static String getHplusMultistageTree(Map map) { StringBuffer menuString = new StringBuffer(); List list = map.get(0); int curIndex = 0; for (TSFunction function : list) { menuString.append("<li>"); if (function.getFunctionIconStyle() != null && !function.getFunctionIconStyle().trim().equals("")) { menuString.append("<a href=\"#\" class=\"\" ><i class=\"fa " + function.getFunctionIconStyle() + "\"></i>"); } else { menuString.append("<a href=\"#\" class=\"\" ><i class=\"fa fa-columns\"></i>"); } menuString.append("<span class=\"menu-text\">"); menuString.append(getMutiLang(function.getFunctionName())); menuString.append("</span>"); menuString.append("<span class=\"fa arrow\">"); menuString.append("</span>"); if (!function.hasSubFunction(map)) { menuString.append("</a></li>"); } else { menuString.append("</a><ul class=\"nav nav-second-level\" >"); menuString.append(getHplusSubMenu(function, 1, map)); menuString.append("</ul></li>"); } curIndex++; } return menuString.toString(); }
肖敬先
@RequiresPermissions("oss:pdf:view")
annotation
@ApiOperation(value = "pdf预览", notes = "权限编码(oss:pdf:view)") @GetMapping("/view") public void pdfViewer(HttpServletRequest request, HttpServletResponse response) { // 不进行xss过滤 HttpServletRequest orgRequest = XssHttpServletRequestWrapper.getOrgRequest(request); String urlpath = orgRequest.getParameter("urlpath"); logger.info("urlpath=" + urlpath); try { InputStream fileInputStream = IoUtil.getFileStream(urlpath); response.setHeader("Content-Disposition", "attachment;fileName=test.pdf"); response.setContentType("multipart/form-data"); OutputStream outputStream = response.getOutputStream(); IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream); } catch (Exception e) { System.out.println(e.getMessage()); } }
肖敬先
if (!checkAllow(user, fileId)) { writeFailure(response, "无权删除他人文件"); return; }
conventional
@RequestMapping("delete-files") public void deleteFiles(HttpServletRequest request, HttpServletResponse response) throws IOException { ID user = getRequestUser(request); String[] files = getParameter(request, "ids", "").split(","); Set<ID> willDeletes = new HashSet<>(); for (String file : files) { if (!ID.isId(file)) { continue; } ID fileId = ID.valueOf(file); willDeletes.add(fileId); } Application.getCommonService().delete(willDeletes.toArray(new ID[0])); writeSuccess(response); }
肖敬先
// 未登录,无权上传图片 if (user == null) { log.warn<method*start>org.slf4j.Logger.warn<method*end>("member fck upload warn: not logged in.");
conventional
private UploadResponse<method*start>foo.common.fck.UploadResponse<method*end> validateUpload(HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request, String<method*start>java.lang.String<method*end> commandStr, String<method*start>java.lang.String<method*end> typeStr, String<method*start>java.lang.String<method*end> currentFolderStr) { CmsUser<method*start>foo.cms.entity.main.CmsUser<method*end> user = CmsUtils.getUser<method*start>foo.cms.web.CmsUtils.getUser<method*end>(request); // TODO 是否允许上传 if (!Command.isValidForPost<method*start>foo.common.fck.Command.isValidForPost<method*end>(commandStr)) { return UploadResponse.getInvalidCommandError<method*start>foo.common.fck.UploadResponse.getInvalidCommandError<method*end>(request); } if (!ResourceType.isValidType<method*start>foo.common.fck.ResourceType.isValidType<method*end>(typeStr)) { return UploadResponse.getInvalidResourceTypeError<method*start>foo.common.fck.UploadResponse.getInvalidResourceTypeError<method*end>(request); } if (!UploadUtils.isValidPath<method*start>foo.common.upload.UploadUtils.isValidPath<method*end>(currentFolderStr)) { return UploadResponse.getInvalidCurrentFolderError<method*start>foo.common.fck.UploadResponse.getInvalidCurrentFolderError<method*end>(request); } return UploadResponse.getFileUploadDisabledError<method*start>foo.common.fck.UploadResponse.getFileUploadDisabledError<method*end>(request);; } } return null; }
万爽
if (command.getGmLevel() > gmLevel) { return "你没有权限执行此GM命令"; }
conventional
private String execGmCmd(Session session, String gmStr, int gmLevel) { gmStr = gmStr.substring(1); String[] commandArray = gmStr.split(" "); GMCommand command = GMCommand.getCommand(commandArray[0]); if (command == null) { return "没有对应GM命令"; } Gm gm = GMCommand.getGm(command); String ret = gm.executeGM(session, commandArray); if (ret != null) { return ret; } return "执行成功"; }
万爽
// 检查权限 basicCheck(comment);
conventional
@PostMapping(value = "/revert") @ResponseBody @SystemLog(description = "回滚评论", type = LogTypeEnum.OPERATION) public JsonResult moveToPublish(@RequestParam("id") Long commentId) { User loginUser = getLoginUser(); // 评论 Comment comment = commentService.get(commentId); // 检查权限 basicCheck(comment); Post post = postService.get(comment.getPostId()); Comment result = commentService.updateCommentStatus(commentId, CommentStatusEnum.PUBLISHED.getCode()); // 判断是否启用邮件服务 new NoticeToAuthor(result, post, loginUser, comment.getCommentStatus()).start(); return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.operation-success")); }
肖敬先
if (validate(ctx, perms)) return fc.next(ctx);
conventional
@Override public Object filterRuleMethod(FilterChain fc, RuleServiceFilterContext ctx) throws Throwable { // 获取方法名 String mn = ctx.getMethod().getName(); // 获取授权列表 String[] perms; Map<String, String[]> clazzMap = this.permissionMap.get(ctx.getObject().getClass()); if (clazzMap == null) { perms = null; } else { perms = clazzMap.get(mn); if (perms != null && perms.length == 0) { perms = null; } } // 验证返回 if (validate(ctx, perms)) return fc.next(ctx); else return null; }
肖敬先
if (interfaceRuleDto == null) { return Result.error<method*start>org.jeecgframework.jwt.util.Result.error<method*end>("您没有该接口的权限!"); }
conventional
@ApiOperation<method*start>io.swagger.annotations.ApiOperation<method*end>(value<method*start>org.springframework.context.annotation.Scope.value<method*end> = "黑名单列表数据", produces<method*start>io.swagger.annotations.ApiOperation.produces<method*end> = "application/json", httpMethod<method*start>io.swagger.annotations.ApiOperation.httpMethod<method*end> = "GET") @RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>(method<method*start>org.springframework.web.bind.annotation.RequestMapping.method<method*end> = RequestMethod.GET<method*start>org.springframework.web.bind.annotation.RequestMethod.GET<method*end>) @ResponseBody public ResponseMessage<method*start>org.jeecgframework.jwt.util.ResponseMessage<method*end><List<method*start>java.util.List<method*end><TsBlackListEntity<method*start>org.jeecgframework.web.black.entity.TsBlackListEntity<method*end>>> list(HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request, HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response) { InterfaceRuleDto<method*start>org.jeecgframework.web.system.pojo.base.InterfaceRuleDto<method*end> interfaceRuleDto = InterfaceUtil.getInterfaceRuleDto<method*start>org.jeecgframework.web.system.util.InterfaceUtil.getInterfaceRuleDto<method*end>(request, InterfaceEnum.blacklist_list<method*start>org.jeecgframework.web.system.enums.InterfaceEnum.blacklist_list<method*end>); CriteriaQuery query = new CriteriaQuery(TsBlackListEntity<method*start>org.jeecgframework.web.black.entity.TsBlackListEntity<method*end>.class); InterfaceUtil.installCriteriaQuery<method*start>org.jeecgframework.web.system.util.InterfaceUtil.installCriteriaQuery<method*end>(query, interfaceRuleDto, InterfaceEnum.blacklist_list<method*start>org.jeecgframework.web.system.enums.InterfaceEnum.blacklist_list<method*end>); query.add<method*start>org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery.add<method*end>(); List<method*start>java.util.List<method*end><TsBlackListEntity<method*start>org.jeecgframework.web.black.entity.TsBlackListEntity<method*end>> listTsBlackLists = this.tsBlackListService.getListByCriteriaQuery<method*start>org.jeecgframework.web.black.service.TsBlackListServiceI.getListByCriteriaQuery<method*end>(query, false); return Result.success<method*start>org.jeecgframework.jwt.util.Result.success<method*end>(listTsBlackLists); }
万爽
if (auth == null || auth.equals("") || (!jwtUtil.getValueFromToken(auth, "role").equals("admin") && !jwtUtil.getValueFromToken(auth, "role").equals("release"))) { k8sConfs.get(i).getItems().get(j).setValue("******"); k8sConfs.get(i).getCurrencyRecord().setConfData("没有权限查看"); for (int h = 0; h < k8sConfs.get(i).getRecords().size(); h++) { k8sConfs.get(i).getRecords().get(h).setConfData("没有权限查看");
annotation
@GetMapping(value = "/list") public JsonResult<K8sConf<com.mokn.istio.api.model.db.K8sConf>> list(@RequestParam(value = "pageNo", required = false) Integer pageNo, @RequestParam(value = "pageSize", required = false) Integer pageSize, @RequestParam(value = "namespace", required = false) String namespace, @RequestParam(value = "name", required = false) String name, @RequestHeader(value = "Authorization", required = false) String auth) { JsonResult<K8sConf<com.mokn.istio.api.model.db.K8sConf>> result = new JsonResult<>(); K8sConf<com.mokn.istio.api.model.db.K8sConf> condition = new K8sConf<>(); if (namespace != null && !namespace.equals("")) { condition.setNamespace(namespace); } if (name != null && !name.equals("")) { condition.setNamespace(name); } PageHelper.startPage(pageNo, pageSize); PageInfo<K8sConf<com.mokn.istio.api.model.db.K8sConf>> pageInfo = new PageInfo<>(confService.listConf(condition)); List<K8sConf<com.mokn.istio.api.model.db.K8sConf>> k8sConfs = pageInfo.getList(); for (int i = 0; i < k8sConfs.size(); i++) { for (int j = 0; j < k8sConfs.get(i).getItems().size(); j++) { } } } return result.success(k8sConfs, pageInfo.getTotal()); }
万爽
// 检查是否忽略权限验证 if (method == null || CheckPermissionUtil.checkIgnore(method)) { return super.preHandle(request, response, handler); } // 检查权限 if (CheckPermissionUtil.isNoPermission(authResult.getToken(), request, response, handler, urlPerm))
conventional
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 放行options请求 if (request.getMethod().toUpperCase().equals("OPTIONS")) { CheckPermissionUtil.passOptions(response); return false; } Method method = null; if (handler instanceof HandlerMethod) { method = ((HandlerMethod) handler).getMethod(); } // 获取token String access_token = CheckPermissionUtil.takeToken(request); if (access_token == null || access_token.trim().isEmpty()) { throw new ErrorTokenException("Token不能为空"); } if (authCenterUrl == null) { throw new RuntimeException("请配置authCenterUrl"); } String url = authCenterUrl + "/authentication?access_token=" + access_token; AuthResult authResult = new RestTemplate().getForObject(url, AuthResult.class); if (authResult == null) { throw new RuntimeException("'" + authCenterUrl + "/authentication' return null"); } else if (AuthResult.CODE_EXPIRED == authResult.getCode()) { throw new ExpiredTokenException(); } else if (AuthResult.CODE_OK != authResult.getCode()) { throw new ErrorTokenException(); } { throw new UnauthorizedException(); } request.setAttribute(SubjectUtil.REQUEST_TOKEN_NAME, authResult.getToken()); return super.preHandle(request, response, handler); }
万爽
if (!BaseUtil.getUserId().equals(BaseConstant.SUPER_ADMIN_USER_ID) && !AuthUtil.isRwAuth(Integer.parseInt(businessId), "business")) { return R.error("无权限转移"); }
conventional
public R transfer(CrmBusiness crmBusiness) { String[] businessIdsArr = crmBusiness.getBusinessIds().split(","); for (String businessId : businessIdsArr) { if (!BaseUtil.getUserId().equals(BaseConstant.SUPER_ADMIN_USER_ID) && !AuthUtil.isRwAuth(Integer.parseInt(businessId), "business")) { return R.error("无权限转移"); } String memberId = "," + crmBusiness.getNewOwnerUserId() + ","; Db.update(Db.getSql("crm.business.deleteMember"), memberId, memberId, Integer.valueOf(businessId)); CrmBusiness oldBusiness = CrmBusiness.dao.findById(Integer.valueOf(businessId)); if (2 == crmBusiness.getTransferType()) { if (1 == crmBusiness.getPower()) { crmBusiness.setRoUserId(oldBusiness.getRoUserId() + oldBusiness.getOwnerUserId() + ","); } if (2 == crmBusiness.getPower()) { crmBusiness.setRwUserId(oldBusiness.getRwUserId() + oldBusiness.getOwnerUserId() + ","); } } crmBusiness.setBusinessId(Integer.valueOf(businessId)); crmBusiness.setOwnerUserId(crmBusiness.getNewOwnerUserId()); crmBusiness.update(); crmRecordService.addConversionRecord(Integer.valueOf(businessId), CrmEnum.CRM_BUSINESS, crmBusiness.getNewOwnerUserId()); } return R.ok(); }
万爽
Assert.isTrue<method*start>org.springframework.util.Assert.isTrue<method*end>(Application.getSecurityManager<method*start>com.rebuild.server.Application.getSecurityManager<method*end>().allow<method*start>com.rebuild.server.service.bizz.privileges.SecurityManager.allow<method*end>(user, ZeroEntry.AllowBatchUpdate<method*start>com.rebuild.server.service.bizz.privileges.ZeroEntry.AllowBatchUpdate<method*end>), "没有权限");
conventional
@RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>("batch-update/submit") public void submit(@PathVariable String entity, HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request, HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response) throws IOException<method*start>java.io.IOException<method*end> { ID<method*start>cn.devezhao.persist4j.engine.ID<method*end> user = getRequestUser<method*start>com.rebuild.web.BaseControll.getRequestUser<method*end>(request); JSONObject<method*start>com.alibaba.fastjson.JSONObject<method*end> requestData = (JSONObject<method*start>com.alibaba.fastjson.JSONObject<method*end>) ServletUtils.getRequestJson<method*start>cn.devezhao.commons.web.ServletUtils.getRequestJson<method*end>(request); int dataRange = getIntParameter<method*start>com.rebuild.web.BaseControll.getIntParameter<method*end>(request, "dr", 2); requestData.put<method*start>com.alibaba.fastjson.JSONObject.put<method*end>("_dataRange", dataRange); requestData.put<method*start>com.alibaba.fastjson.JSONObject.put<method*end>("entity", entity); BulkContext bulkContext = new BulkContext(user, BizzPermission.UPDATE<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.UPDATE<method*end>, requestData); Entity<method*start>cn.devezhao.persist4j.Entity<method*end> entityMeta = MetadataHelper.getEntity<method*start>com.rebuild.server.metadata.MetadataHelper.getEntity<method*end>(entity); ServiceSpec<method*start>com.rebuild.server.service.ServiceSpec<method*end> ies = Application.getService<method*start>com.rebuild.server.Application.getService<method*end>(entityMeta.getEntityCode<method*start>cn.devezhao.persist4j.Entity.getEntityCode<method*end>()); String taskid = ((EntityService) ies).bulkAsync<method*start>com.rebuild.server.service.EntityService.bulkAsync<method*end>(bulkContext); writeSuccess<method*start>com.rebuild.web.BaseControll.writeSuccess<method*end>(response, taskid); }
万爽
if (menuIds.contains(sysMenu.getId().toString())) { treeMenuAllowAccess.setAllowAccess(1); } if (sysMenu.getDeep() < 3) { treeMenuAllowAccess.setChildren(selectTreeMenuAllowAccessByMenuIdsAndPid(menuIds, sysMenu.getId().toString())); }
conventional
@Override public List<method*start>java.util.List<method*end><TreeMenuAllowAccess<method*start>com.github.vole.portal.model.vo.TreeMenuAllowAccess<method*end>> selectTreeMenuAllowAccessByMenuIdsAndPid(final List<method*start>java.util.List<method*end><String<method*start>java.lang.String<method*end>> menuIds, String<method*start>java.lang.String<method*end> pid) { QueryWrapper<method*start>com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<method*end><SysMenu<method*start>com.github.vole.portal.model.entity.SysMenu<method*end>> ew = new QueryWrapper<method*start>com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<method*end><SysMenu<method*start>com.github.vole.portal.model.entity.SysMenu<method*end>>(); ew.orderByAsc("sort"); ew.eq("parent_id", pid); List<method*start>java.util.List<method*end><SysMenu<method*start>com.github.vole.portal.model.entity.SysMenu<method*end>> sysMenus = this.list(ew); List<method*start>java.util.List<method*end><TreeMenuAllowAccess<method*start>com.github.vole.portal.model.vo.TreeMenuAllowAccess<method*end>> treeMenuAllowAccesss = new ArrayList<method*start>java.util.ArrayList<method*end><TreeMenuAllowAccess<method*start>com.github.vole.portal.model.vo.TreeMenuAllowAccess<method*end>>(); for (SysMenu<method*start>com.github.vole.portal.model.entity.SysMenu<method*end> sysMenu : sysMenus) { TreeMenuAllowAccess<method*start>com.github.vole.portal.model.vo.TreeMenuAllowAccess<method*end> treeMenuAllowAccess = new TreeMenuAllowAccess<method*start>com.github.vole.portal.model.vo.TreeMenuAllowAccess<method*end>(); treeMenuAllowAccess.setSysMenu(sysMenu); treeMenuAllowAccesss.add(treeMenuAllowAccess); } return treeMenuAllowAccesss; }
万爽
if (parameters.length == 0) { // 什么都没有,无法判断权限 return null; } Object object = parameters[0]; if (!(object instanceof BaseUserContext)) { // 第一个不是,也无法判断权限,通常这样的方法不允许在manager方法出现 return null; }
conventional
protected String targetIdOf(String methodName, Object[] parameters) { if (parameters.length == 1) { // 只有UC,没有其他参数 return null; } // 第一个是UC,而且至少有第二个参数,而且是String,而且方法的名字不是deleteAll和create,都应该是第二个 int index = indexOfTargetId(methodName); if (index < 0) { // 不存在targetId return null; } if (index >= parameters.length) { // 得到的Index超过范围,也不知道是怎么算的 return null; } Object secondParameter = parameters[index]; if (secondParameter instanceof String) { return (String) secondParameter; } return null; }
万爽
if (EntityHelper.hasPrivilegesField(entity)) { Permission[] actions = new Permission[] { BizzPermission.CREATE, BizzPermission.DELETE, BizzPermission.UPDATE, BizzPermission.READ, BizzPermission.ASSIGN, BizzPermission.SHARE }; Map<String, Boolean> actionMap = new HashMap<>(); for (Permission act : actions) { actionMap.put(act.getName(), Application.getSecurityManager().allow(user, record, act)); } mv.getModel().put("entityPrivileges", JSON.toJSONString(actionMap));
conventional
protected ModelAndView createModelAndView(String page, ID record, ID user) { ModelAndView mv = createModelAndView(page); Entity entity = MetadataHelper.getEntity(record.getEntityCode()); putEntityMeta(mv, entity); // 使用主实体权限 if (entity.getMasterEntity() != null) { entity = entity.getMasterEntity(); } } else { mv.getModel().put("entityPrivileges", JSONUtils.EMPTY_OBJECT_STR); } return mv; }
万爽
if (null == aclDO) { throw BizException.fail("待查询的权限不存在"); }
conventional
public AclDetailRes detail(AclReq aclReq) { AclDO aclDO = aclMapper.selectByPrimaryUuid(aclReq.getUuid()); AclDetailRes aclDetailRes = new AclDetailRes(); BeanUtils.copyProperties(aclDO, aclDetailRes); if (aclDO.getSysAclType().equals(AclTypeEnum.system.type)) { int count = aclMapper.checkChildAcl(LevelUtil.calculateLevel(aclDO.getSysAclLevel(), aclDO.getId())); if (count == 0) { aclDetailRes.setDisabledAclSysCode(false); } } aclDetailRes.setIdStr(String.valueOf(aclDO.getId())); aclDetailRes.setSysAclParentIdStr(String.valueOf(aclDO.getSysAclParentId())); return aclDetailRes; }
万爽
for (RoleEntity m : list) { AuthDTO authDTO = authService.domainAuth(request, m.getDomain_id(), "w"); if (!authDTO.getStatus()) { return Hret.error(403, "您没有权限删除域【" + m.getDomain_id() + "】中的角色信息", null); if (!authDTO.getStatus()) { return Hret.error(403, "您没有权限删除域【" + m.getDomain_id() + "】中的角色信息", null); } } }
conventional
@RequestMapping(value = "/delete", method = RequestMethod.POST) public String delete(HttpServletResponse response, HttpServletRequest request) { String json = request.getParameter("JSON"); List<RoleEntity> list = new GsonBuilder().create().fromJson(json, new TypeToken<List<RoleEntity>>() {}.getType()); for (RoleEntity m : list) { AuthDTO authDTO = authService.domainAuth(request, m.getDomain_id(), "w"); } RetMsg retMsg = roleService.delete(list); if (!retMsg.checkCode()) { response.setStatus(retMsg.getCode()); return Hret.error(retMsg); } return Hret.success(retMsg); }
万爽
@Authorize(merge = false) if (!old.hasPermission(RW, R)) { throw new AccessDenyException("没有权限保存此配置"); }
conventional
@PatchMapping("/me/{key}") @ApiOperation("保存当前用户配置") public ResponseMessage save(Authentication authentication, @PathVariable String key, @Validated @RequestBody UserSettingEntity userSettingEntity) { userSettingEntity.setId(null); userSettingEntity.setUserId(authentication.getUser().getId()); userSettingEntity.setKey(key); UserSettingEntity old = userSettingService.selectByUser(authentication.getUser().getId(), key, userSettingEntity.getSettingId()); if (old != null) { userSettingEntity.setId(old.getId()); if (!old.hasPermission(RW, R)) { throw new AccessDenyException("没有权限保存此配置"); } } userSettingEntity.setPermission(RW); String id = userSettingService.saveOrUpdate(userSettingEntity); return ResponseMessage.ok(id); }
肖敬先
AccessibleObject.checkPermission();
conventional
@Override @CallerSensitive public void setAccessible(boolean flag) { // 如果需要开启访问权限 if (flag) { // 获取setAccessible()的调用者所处的类 Class<?> caller = Reflection.getCallerClass(); // 判断caller是否可以访问当前元素(涉及到exports和opens的判断) checkCanSetAccessible(caller); } setAccessible0(flag); }
肖敬先
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)
conventional
public static String getUUID(Context context) { String tmDevice = "", tmSerial = "", tmPhone = "", androidId = ""; { try { final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); tmDevice = "" + tm.getDeviceId(); tmSerial = "" + tm.getSimSerialNumber(); androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); } catch (Exception e) { Log.e("AppUtils", "exception:" + e.getMessage()); } } else { Log.e("AppUtils", "没有 android.permission.READ_PHONE_STATE 权限"); tmDevice = "device"; tmSerial = "serial"; androidId = "androidid"; } UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode()); String uniqueId = deviceUuid.toString(); if (BuildConfig.DEBUG) Log.d(TAG, "uuid=" + uniqueId); return uniqueId; }
肖敬先
if (perms != null)
conventional
public static boolean askForBothPermissions(Activity activity) { boolean askCamera = !HiSettingsHelper.getInstance().isCameraPermAsked() && ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED; boolean askStorage = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED; String[] perms = null; if (askCamera && askStorage) { HiSettingsHelper.getInstance().setCameraPermAsked(true); perms = new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }; } else if (askCamera) { HiSettingsHelper.getInstance().setCameraPermAsked(true); perms = new String[] { Manifest.permission.CAMERA }; } else if (askStorage) { perms = new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }; UIUtils.toast("需要授予 \"存储空间\" 权限"); } { ActivityCompat.requestPermissions(activity, perms, PostActivity.PERMISSIONS_REQUEST_CODE_BOTH); return true; } return false; }
肖敬先
// 访问消息页, 判断登录 if (Views.METHOD_MESSAGES.equals(method)) { // 标记已读 AccountProfile profile = getProfile(); if (null == profile || profile.getId() != userId) { throw new MtonsException("您没有权限访问该页面"); } messageService.readed4Me(profile.getId()); }
conventional
@GetMapping(value = "/{userId}/{method}") public String method(@PathVariable(value = "userId") Long userId, @PathVariable(value = "method") String method, ModelMap model, HttpServletRequest request) { model.put("pageNo", ServletRequestUtils.getIntParameter(request, "pageNo", 1)); initUser(userId, model); return view(String.format(Views.USER_METHOD_TEMPLATE, method)); }
肖敬先
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_USER','ROLE_VISTOR')")
annotation
@PostMapping public ResponseEntity<Response<com.whichard.spring.boot.blog.vo.Response>> createComment(Long blogId, String commentContent) { try { commentContent = sensitiveService.filter(commentContent); blogService.createComment(blogId, commentContent); } catch (ConstraintViolationException e) { return ResponseEntity.ok().body(new Response(false, ConstraintViolationExceptionHandler.getMessage(e))); } catch (Exception e) { return ResponseEntity.ok().body(new Response(false, e.getMessage())); } return ResponseEntity.ok().body(new Response(true, "发表评论成功", null)); }
肖敬先
// 如果设置为所有权限 if (permissionIds.contains("all")) { return "all"; }
conventional
@Override public String getModuleIds(final String permissionIds) { final Map<String, Permission> idMap = new HashMap<>(cache.size()); for (final Permission permission : cache.values()) { idMap.put(permission.getId().toString(), permission); } final String[] idList = StringUtils.split(permissionIds, ','); final List<String> modulePathList = new ArrayList<>(); for (final String id : idList) { final Permission permission = idMap.get(id); if (permission != null) { modulePathList.add(permission.getPath()); } } final String moduleIds = StringUtils.join(modulePathList, ','); return this.distinct(StringUtils.split(moduleIds, ',')); }
肖敬先
if (!hasBizPermission(request, apiDataType.getBizId())) { throw new RuntimeException("您没有相关业务线的权限,请联系管理员开通"); }
conventional
@RequestMapping("/updateDataTypePage") public String updateDataTypePage(HttpServletRequest request, Model model, int dataTypeId) { XxlApiDataType apiDataType = xxlApiDataTypeService.loadDataType(dataTypeId); if (apiDataType == null) { throw new RuntimeException("数据类型ID非法"); } model.addAttribute("apiDataType", apiDataType); // 业务线列表 List<XxlApiBiz> bizList = xxlApiBizDao.loadAll(); model.addAttribute("bizList", bizList); return "datatype/datatype.update"; }
肖敬先
if (interfaceRuleDto == null) { return Result.error("您没有该接口的权限!"); }
conventional
@ApiOperation(value = "删除黑名单") @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseBody public ResponseMessage<?> delete(@PathVariable("id") String id, HttpServletRequest request) { InterfaceRuleDto interfaceRuleDto = InterfaceUtil.getInterfaceRuleDto(request, InterfaceEnum.blacklist_delete); if (interfaceRuleDto == null) { return Result.error("您没有该接口的权限!"); } logger.info("delete[{}]", id); // 验证 if (StringUtils.isEmpty(id)) { return Result.error("ID不能为空"); } try { tsBlackListService.deleteEntityById(TsBlackListEntity.class, id); } catch (Exception e) { e.printStackTrace(); return Result.error("黑名单删除失败"); } return Result.success(); }
肖敬先
if (null != authRoles) { if (0 < authRoles.roles<method*start>org.superboot.base.AuthRoles.roles<method*end>().length<method*start>java.lang.String[].length<method*end>) { String<method*start>java.lang.String<method*end>[] roles<method*start>org.superboot.base.AuthRoles.roles<method*end> = authRoles.roles<method*start>org.superboot.base.AuthRoles.roles<method*end>(); for (String<method*start>java.lang.String<method*end> role : roles<method*start>org.superboot.base.AuthRoles.roles<method*end>) { if (BaseConstants.ALL_USER_NAME.equals<method*start>java.lang.String.equals<method*end>(role)) { return true; } if (BaseConstants.GEN_USER_NAME.equals<method*start>java.lang.String.equals<method*end>(role)) { return true; } if (-1 != token.getUserRole<method*start>org.superboot.base.BaseToken.getUserRole<method*end>().indexOf(role)) { return true; } } } return false; }
conventional
public boolean checkAuthRole(AuthRoles<method*start>org.superboot.base.AuthRoles<method*end> authRoles, BaseToken<method*start>org.superboot.base.BaseToken<method*end> token) { return true; }
万爽
// 登录用户名 model.addAttribute("userName", sessionUser.getAccount()); // 单点退出地址 model.addAttribute("ssologoutUrl", new StringBuilder().append(ssoServerUrl).append("/logout?backUrl=").append(getLocalUrl(request)).toString()); SessionPermission sessionPermission = SessionUtils.getSessionPermission(request); if (sessionPermission != null) { // 登录用户当前应用的菜单 request.setAttribute("userMenus", sessionPermission.getMenuList()); // 登录用户当前应用的权限 request.setAttribute("userPermissions", sessionPermission.getPermissionSet());
conventional
@GetMapping("/") public String index(Model model, HttpServletRequest request) { SessionUser sessionUser = SessionUtils.getSessionUser(request); // 登录用户名 model.addAttribute("userName", sessionUser.getAccount()); // 单点退出地址 model.addAttribute("ssologoutUrl", new StringBuilder().append(ssoServerUrl).append("/logout?backUrl=").append(getLocalUrl(request)).toString()); SessionPermission sessionPermission = SessionUtils.getSessionPermission(request); return "index"; }
万爽
@RequiresPermissions("sys:role:info")
annotation
@ApiOperation(value = "角色信息", response = Response.class, notes = "权限编码(sys:role:info)") @GetMapping("/info/{roleId}") public JsonResponse info(@PathVariable("roleId") Object roleId) { SysRole role = sysRoleService.queryObject(roleId); // 查询角色对应的菜单 List<Long> menuIdList = sysMenuService.queryMenuIdList(roleId); role.setMenuIdList(menuIdList); // 查询角色对应的部门 List<Long> deptIdList = sysDeptService.queryDeptIdListByRoleId(roleId); role.setDeptIdList(deptIdList); JSONArray params = sysMenuService.queryParamsList(roleId); List<Long> userIdList = sysRoleService.queryUserIdList(roleId); role.setParamExt(params); role.setUserIdList(userIdList); return JsonResponse.success(role); }
万爽
if (!granted) { Toast.makeText(this, "请到设置-权限管理中开启", Toast.LENGTH_SHORT).show(); return; }
conventional
@Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); boolean granted = true; for (int i = 0; i < grantResults.length; i++) { if (grantResults[i] != PackageManager.PERMISSION_GRANTED) { granted = false; } } if (requestCode == CAMERA_PERMISSIONS_REQUEST) { Intent intent = new Intent(this, CameraActivity.class); intent.putExtra("dir", getCacheDir().getAbsolutePath()); startActivityForResult(intent, CAPTURE_CAMERA); } else if (requestCode == LOCATION_PERMISSIONS_REQUEST) { startActivityForResult(new Intent(MessageActivity.this, LocationPickerActivity.class), PICK_LOCATION); } else if (requestCode == PHOTO_PERMISSIONS_REQUEST) { getPicture(); } }
万爽
if (url.contains("monitoring") || url.contains("druid")) { try { if (ShiroUtils.getUserId() != Constant.SUPER_ADMIN) { accessDenied(res); } } catch (Exception e) { logger.info("没有权限!"); accessDenied(res); } }
conventional
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 设置跨域 HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); res.setHeader("Access-Control-Max-Age", "0"); res.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, X-Content-Type-Options, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token"); res.setHeader("Access-Control-Allow-Credentials", "true"); res.setHeader("X-XSS-Protection", "1"); res.setHeader("XDomainRequestAllowed", "1"); String url = req.getRequestURI(); // 为第三方插件权限拦截、只允许超级管理员 /* 退出登录跳过monitoring监控的过滤链防止再次获取session与shiro冲突*/ if (url.contains("/sys/logout")) { String servletPath = req.getServletPath(); req.getRequestDispatcher(servletPath).forward(req, res); } else { chain.doFilter(req, res); } }
万爽
if (entity == null) { chain.resume<method*start>org.openwebflow.assign.TaskAssignmentHandlerChain.resume<method*end>(assigneeExpression, ownerExpression, candidateUserExpressions, candidateGroupExpressions, task, execution); return; }
conventional
@Override public void handleAssignment(TaskAssignmentHandlerChain<method*start>org.openwebflow.assign.TaskAssignmentHandlerChain<method*end> chain, Expression<method*start>org.activiti.engine.delegate.Expression<method*end> assigneeExpression, Expression<method*start>org.activiti.engine.delegate.Expression<method*end> ownerExpression, Set<method*start>java.util.Set<method*end><Expression<method*start>org.activiti.engine.delegate.Expression<method*end>> candidateUserExpressions, Set<method*start>java.util.Set<method*end><Expression<method*start>org.activiti.engine.delegate.Expression<method*end>> candidateGroupExpressions, TaskEntity<method*start>org.activiti.engine.impl.persistence.entity.TaskEntity<method*end> task, ActivityExecution<method*start>org.activiti.engine.impl.pvm.delegate.ActivityExecution<method*end> execution) { // 设置assignment信息 String<method*start>java.lang.String<method*end> processDefinitionId = task.getProcessDefinitionId<method*start>org.activiti.engine.impl.persistence.entity.TaskEntity.getProcessDefinitionId<method*end>(); String<method*start>java.lang.String<method*end> taskDefinitionKey = task.getTaskDefinitionKey<method*start>org.activiti.engine.impl.persistence.entity.TaskEntity.getTaskDefinitionKey<method*end>(); ActivityPermissionEntity<method*start>org.openwebflow.assign.permission.ActivityPermissionEntity<method*end> entity; try { entity = _activityPermissionManager.load<method*start>org.openwebflow.assign.permission.ActivityPermissionManager.load<method*end>(processDefinitionId, taskDefinitionKey, true); } catch (Exception<method*start>java.lang.Exception<method*end> e) { throw new OwfException(e); } // 彻底忽略原有规则 task.setAssignee<method*start>org.activiti.engine.impl.persistence.entity.TaskEntity.setAssignee<method*end>(entity.getAssignee<method*start>org.openwebflow.assign.permission.ActivityPermissionEntity.getAssignee<method*end>()); task.addCandidateGroups<method*start>org.activiti.engine.impl.persistence.entity.TaskEntity.addCandidateGroups<method*end>(asList(entity.getGrantedGroupIds<method*start>org.openwebflow.assign.permission.ActivityPermissionEntity.getGrantedGroupIds<method*end>())); task.addCandidateUsers<method*start>org.activiti.engine.impl.persistence.entity.TaskEntity.addCandidateUsers<method*end>(asList(entity.getGrantedUserIds<method*start>org.openwebflow.assign.permission.ActivityPermissionEntity.getGrantedUserIds<method*end>())); }
万爽
if (user != null && (user.isAdmin())) { chain.doFilter(req, resp); } else { // 重定向到 无权限执行操作的页面 HttpServletResponse response = (HttpServletResponse) resp; response.sendRedirect("/?msg=security"); } } else { try { chain.doFilter(req, resp); } catch (ClientAbortException ex) { // Tomcat异常,不做处理 } }
conventional
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; boolean matchAnyRoles = false; for (RequestMatcher anyRequest : ignoredRequests) { if (anyRequest.matches(request)) { matchAnyRoles = true; } } User user = (User) request.getSession().getAttribute(Constants.USER_SESSION_NAME); { }
万爽
Assert.isTrue(Application.getSecurityManager().allow(user, ZeroEntry.AllowCustomNav), "没有权限");
conventional
@RequestMapping(value = "nav-settings", method = RequestMethod.POST) public void sets(HttpServletRequest request, HttpServletResponse response) throws IOException { ID user = getRequestUser(request); JSON config = ServletUtils.getRequestJson(request); ID cfgid = getIdParameter(request, "id"); if (cfgid != null && !ShareToManager.isSelf(user, cfgid)) { cfgid = null; } Record record; if (cfgid == null) { record = EntityHelper.forNew(EntityHelper.LayoutConfig, user); record.setString("belongEntity", "N"); record.setString("applyType", BaseLayoutManager.TYPE_NAV); record.setString("shareTo", BaseLayoutManager.SHARE_SELF); } else { record = EntityHelper.forUpdate(cfgid, user); } record.setString("config", config.toJSONString()); putCommonsFields(request, record); Application.getBean(LayoutConfigService.class).createOrUpdate(record); writeSuccess(response); }
万爽
RedisUser redisUser = this.redisUser(); if (!redisUser.getTenantId().equals(1L)) { throw new BizException("您不是MOMO企业下的VIP,无权操作"); }
conventional
@Override public DataDictLevelRes dataDictTree(DataDictTreeReq dataDictTreeReq) { DataDictLevelRes dataDictLevelRes = new DataDictLevelRes(); List<DataDictDO> dataDiceGetAll = dataDictMapper.dataDiceGetAll(0, dataDictTreeReq.getSysDictCodeParentValue(), dataDictTreeReq.getSysDictCodeParentValue()); if (CollectionUtils.isEmpty(dataDiceGetAll)) { return dataDictLevelRes; } List<DataDictTreeRes> dictTreeResList = Lists.newArrayList(); dataDiceGetAll.forEach(dataDictDO -> { DataDictTreeRes dictTreeRes = DataDictTreeRes.dictTreeRes(dataDictDO); // 状态 0启用 1禁用 if (dictTreeRes.getDisabledFlag().equals(DisabledFlagEnum.start.type)) { dictTreeRes.setDisabled(false); } dictTreeResList.add(dictTreeRes); }); List<DataDictTreeRes> dictListToTree = dictListToTree(dictTreeResList); dataDictLevelRes.setDataDictTreeRes(dictListToTree); return dataDictLevelRes; }
万爽
if (!authDTO.getStatus<method*start>com.asofdate.hauth.dto.AuthDTO.getStatus<method*end>()) { 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>(value<method*start>org.springframework.web.bind.annotation.RequestMapping.value<method*end> = "/delete", 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> delete(HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response, HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request) { String<method*start>java.lang.String<method*end> json = request.getParameter<method*start>javax.servlet.http.HttpServletRequest.getParameter<method*end>("JSON"); List<method*start>java.util.List<method*end><OrgEntity<method*start>com.asofdate.hauth.entity.OrgEntity<method*end>> list = new GsonBuilder<method*start>com.google.gson.GsonBuilder<method*end>().create<method*start>com.google.gson.GsonBuilder.create<method*end>().fromJson<method*start>com.google.gson.GsonBuilder.fromJson<method*end>(json, new TypeToken<method*start>com.google.gson.reflect.TypeToken<method*end><List<method*start>java.util.List<method*end><OrgEntity<method*start>com.asofdate.hauth.entity.OrgEntity<method*end>>>() { }.getType<method*start>com.google.gson.reflect.TypeToken.getType<method*end>()); ; for (OrgEntity<method*start>com.asofdate.hauth.entity.OrgEntity<method*end> m : list) { String<method*start>java.lang.String<method*end> orgId = m.getOrg_id<method*start>com.asofdate.hauth.entity.OrgEntity.getOrg_id<method*end>(); String<method*start>java.lang.String<method*end> domainId = m.getDomain_id<method*start>com.asofdate.hauth.entity.OrgEntity.getDomain_id<method*end>(); AuthDTO<method*start>com.asofdate.hauth.dto.AuthDTO<method*end> authDTO = authService.domainAuth<method*start>com.asofdate.hauth.service.AuthService.domainAuth<method*end>(request, domainId, "w"); } RetMsg<method*start>com.asofdate.utils.RetMsg<method*end> retMsg = orgService.delete<method*start>com.asofdate.hauth.service.OrgService.delete<method*end>(list); if (retMsg.checkCode<method*start>com.asofdate.utils.RetMsg.checkCode<method*end>()) { return Hret.success<method*start>com.asofdate.utils.Hret.success<method*end>(retMsg); } response.setStatus<method*start>javax.servlet.http.HttpServletResponse.setStatus<method*end>(retMsg.getCode<method*start>com.asofdate.utils.RetMsg.getCode<method*end>()); return Hret.error<method*start>com.asofdate.utils.Hret.error<method*end>(retMsg); }
万爽