validation
stringlengths 16
3.54k
| validationType
stringclasses 2
values | function
stringlengths 49
6.38k
| author
stringclasses 5
values | context
stringclasses 5
values |
---|---|---|---|---|
if (interfaceRuleDto == null) {
return Result.error("您没有该接口的权限!");
}
| conventional | @ApiOperation(value = "根据ID获取黑名单信息", notes = "根据ID获取黑名单信息", httpMethod = "GET", produces = "application/json")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public ResponseMessage<?> get(@PathVariable("id") String id, HttpServletRequest request) {
InterfaceRuleDto interfaceRuleDto = InterfaceUtil.getInterfaceRuleDto(request, InterfaceEnum.blacklist_get);
// 验证
if (StringUtils.isEmpty(id)) {
return Result.error("ID不能为空");
}
TsBlackListEntity task = tsBlackListService.get(TsBlackListEntity.class, id);
return Result.success(task);
} | 万爽 | |
ID user = getRequestUser(request);
Assert.isTrue(Application.getSecurityManager().allow(user, ZeroEntry.AllowCustomDataList), "没有权限"); | conventional | @RequestMapping(value = "list-fields", method = RequestMethod.POST)
@Override
public void sets(@PathVariable String entity, HttpServletRequest request, HttpServletResponse response) throws IOException {
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", entity);
record.setString("applyType", BaseLayoutManager.TYPE_DATALIST);
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);
} | 万爽 | |
checkAccess(file, true, false); | conventional | @Override
public List<AclEntry<AclEntry>> getAcl() throws IOException {
/* GetFileSecurity does not follow links so when following links we need the final target */
String path = WindowsLinkSupport.getFinalPath(file, followLinks);
/*
* ALLOW and DENY entries in DACL;
* AUDIT entries in SACL (ignore for now as it requires privileges)
*/
NativeBuffer buffer = getFileSecurity(path, DACL_SECURITY_INFORMATION);
try {
return WindowsSecurityDescriptor.getAcl(buffer.address());
} finally {
buffer.release();
}
} | 肖敬先 | |
if (permission != null) {
needLogin = permission.limit();
needAdminuser = permission.superUser();
}
// if pass
if (needLogin) {
XxlApiUser loginUser = loginService.ifLogin(request);
if (loginUser == null) {
response.sendRedirect(request.getContextPath() + "/toLogin");
return false;
}
if (needAdminuser && loginUser.getType() != 1) {
throw new RuntimeException("权限拦截");
}
request.setAttribute(LoginService.LOGIN_IDENTITY, loginUser);
} | conventional | @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return super.preHandle(request, response, handler);
}
// if need login
boolean needLogin = true;
boolean needAdminuser = false;
HandlerMethod method = (HandlerMethod) handler;
PermessionLimit permission = method.getMethodAnnotation(PermessionLimit.class);
return super.preHandle(request, response, handler);
} | 肖敬先 | |
boolean isAdmin = (Boolean) session.getAttribute("isAdmin");
if (!isAdmin) {
Set<String> actions = (Set<String>) session.getAttribute("allActions");
String aname = hm.getBean().getClass().getName() + "." + hm.getMethod().getName();
if (!actions.contains(aname))
throw new CmsException("没有权限访问该功能");
} | conventional | @SuppressWarnings("unchecked")
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
String sid = request.getParameter("sid");
if (sid != null && !"".equals(sid.trim())) {
session = CmsSessionContext.getSession(sid);
}
HandlerMethod hm = (HandlerMethod) handler;
User user = (User) session.getAttribute("loginUser");
if (user == null) {
response.sendRedirect(request.getContextPath() + "/login");
} else {
return super.preHandle(request, response, handler);
} | 肖敬先 | |
if (tableBlackList != null && !tableBlackList.isEmpty()) {
for (String tn : tableBlackList) {
if (tableUCN.equals(tn.toUpperCase())) {
error("请求的表:" + tableName + "在黑名单中");
return;
}
}
}
if (tableWhiteList != null && !tableWhiteList.isEmpty()) {
for (String tn : tableWhiteList) {
if (tableUCN.equals(tn.toUpperCase())) {
return;
}
}
error("请求的表:" + tableName + "不在白名单中");
} | conventional | private void validateTable(String tableName) {
String tableUCN = tableName.toUpperCase();
return
} | 肖敬先 | |
ValidatorUtils.validateEntity(config);
if (config.getType() == Constant.CloudService.QINIU.getValue()) {
ValidatorUtils.validateEntity(config, QiniuGroup.class);
} else if (config.getType() == Constant.CloudService.ALIYUN.getValue()) {
ValidatorUtils.validateEntity(config, AliyunGroup.class);
} else if (config.getType() == Constant.CloudService.QCLOUD.getValue()) {
ValidatorUtils.validateEntity(config, QcloudGroup.class);
} | conventional | @Log("保存云存储配置信息")
@ApiOperation(value = "保存云存储配置信息", notes = "权限编码(oss:file:config)")
@PostMapping("/saveConfig")
@RequiresPermissions("oss:file:saveConfig")
public JsonResponse saveConfig(@RequestBody(required = false) CloudStorageConfig config) {
sysConfigService.updateValueByKey(KEY, JSON.toJSONString(config));
return JsonResponse.success();
} | 肖敬先 | |
ID roleId = getIdParameterNotNull(request, "role");
if (RoleService.ADMIN_ROLE.equals(roleId)) {
writeFailure(response, "系统内建管理员角色,不允许修改。此角色拥有高级系统权限,请谨慎使用");
return;
} | conventional | @RequestMapping("privileges-list")
public void privilegesList(HttpServletRequest request, HttpServletResponse response) throws IOException {
ID roleId = getIdParameterNotNull(request, "role");
Object[][] array = Application.createQuery("select entity,definition,zeroKey from RolePrivileges where roleId = ?").setParameter(1, roleId).array();
for (Object[] o : array) {
if ((int) o[0] == 0) {
o[0] = o[2];
}
}
JSON retJson = JSONUtils.toJSONObjectArray(new String[] { "name", "definition" }, array);
writeSuccess(response, retJson);
} | 肖敬先 | |
@RequiresPermissions<method*start>org.apache.shiro.authz.annotation.RequiresPermissions<method*end>("user") | annotation | @RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>(value<method*start>org.springframework.web.bind.annotation.RequestMapping.value<method*end> = "treeselect")
public String<method*start>java.lang.String<method*end> treeselect(HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request, Model<method*start>org.springframework.ui.Model<method*end> model) {
// 树结构数据URL
model.addAttribute<method*start>org.springframework.ui.Model.addAttribute<method*end>("url", request.getParameter<method*start>javax.servlet.http.HttpServletRequest.getParameter<method*end>("url"));
// 排除的编号ID
model.addAttribute<method*start>org.springframework.ui.Model.addAttribute<method*end>("extId", request.getParameter<method*start>javax.servlet.http.HttpServletRequest.getParameter<method*end>("extId"));
// 是否可复选
model.addAttribute<method*start>org.springframework.ui.Model.addAttribute<method*end>("checked", request.getParameter<method*start>javax.servlet.http.HttpServletRequest.getParameter<method*end>("checked"));
// 指定默认选中的ID
model.addAttribute<method*start>org.springframework.ui.Model.addAttribute<method*end>("selectIds", request.getParameter<method*start>javax.servlet.http.HttpServletRequest.getParameter<method*end>("selectIds"));
// 是否读取全部数据,不进行权限过滤
model.addAttribute<method*start>org.springframework.ui.Model.addAttribute<method*end>("isAll", request.getParameter<method*start>javax.servlet.http.HttpServletRequest.getParameter<method*end>("isAll"));
// 过滤栏目模型(仅针对CMS的Category树)
model.addAttribute<method*start>org.springframework.ui.Model.addAttribute<method*end>("module", request.getParameter<method*start>javax.servlet.http.HttpServletRequest.getParameter<method*end>("module"));
return "modules/sys/tagTreeselect";
} | 肖敬先 | |
if (!mcfg.isMemberOn()) {
return FrontUtils.showMessage(request, model, "member.memberClose");
}
if (user == null) {
return FrontUtils.showLogin(request, model, site);
}
CmsMessage message = messageMng.findById(id);
// 非发件人无权查看信件
if (!message.getMsgSendUser().equals(user)) {
WebErrors errors = WebErrors.create(request);
errors.addErrorCode("error.noPermissionsView");
return FrontUtils.showError(request, response, model, errors);
} | annotation | @RequestMapping(value = "/member/message_edit.jspx")
public String message_edit(Integer id, HttpServletRequest request, HttpServletResponse response, ModelMap model) {
CmsSite site = CmsUtils.getSite(request);
CmsUser user = CmsUtils.getUser(request);
FrontUtils.frontData(request, model, site);
MemberConfig mcfg = site.getConfig().getMemberConfig();
// 没有开启会员功能
model.addAttribute("message", message);
return FrontUtils.getTplPath(request, site.getSolutionPath(), TPLDIR_MESSAGE, MESSAGE_EDIT);
} | 肖敬先 | |
Boolean<method*start>java.lang.Boolean<method*end> status = authService.domainAuth<method*start>com.asofdate.hauth.service.AuthService.domainAuth<method*end>(request, domainId, "w").getStatus<method*start>com.asofdate.hauth.dto.AuthDTO.getStatus<method*end>();
if (!status) {
return Hret.error<method*start>com.asofdate.utils.Hret.error<method*end>(422, "您没有权限在这个域中创建用户", null);
} | conventional | @RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>(method<method*start>org.springframework.web.bind.annotation.RequestMapping.method<method*end> = RequestMethod.POST<method*start>org.springframework.web.bind.annotation.RequestMethod.POST<method*end>)
public String<method*start>java.lang.String<method*end> add(HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response, HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request) {
UserEntity<method*start>com.asofdate.hauth.entity.UserEntity<method*end> args = parse<method*start>com.asofdate.hauth.controller.UserController.parse<method*end>(request);
if (args == null) {
return Hret.error<method*start>com.asofdate.utils.Hret.error<method*end>(422, "参数解析失败,请按照要求填写表单", null);
}
String<method*start>java.lang.String<method*end> domainId = args.getDomain_id<method*start>com.asofdate.hauth.entity.UserEntity.getDomain_id<method*end>();
Boolean<method*start>java.lang.Boolean<method*end> status = authService.domainAuth<method*start>com.asofdate.hauth.service.AuthService.domainAuth<method*end>(request, domainId, "w").getStatus<method*start>com.asofdate.hauth.dto.AuthDTO.getStatus<method*end>();
if (!status) {
return Hret.error<method*start>com.asofdate.utils.Hret.error<method*end>(422, "您没有权限在这个域中创建用户", null);
}
int size = userService.add<method*start>com.asofdate.hauth.service.UserService.add<method*end>(args);
if (size != 1) {
response.setStatus<method*start>javax.servlet.http.HttpServletResponse.setStatus<method*end>(421);
return Hret.error<method*start>com.asofdate.utils.Hret.error<method*end>(421, "新增用户失败,账号已存在", null);
}
return Hret.success<method*start>com.asofdate.utils.Hret.success<method*end>(200, "success", null);
} | 肖敬先 | |
switch(((HttpException) e).code()) {
case 403:
mErrorMsg = "没有权限访问此链接!";
break; | conventional | @Override
public void onError(Throwable e) {
if (mView == null) {
return;
}
if (e instanceof HttpException) {
switch(((HttpException) e).code()) {
case 403:
mErrorMsg = "没有权限访问此链接!";
break;
case 504:
if (!NetUtil.isConnected(App.getInstance())) {
mErrorMsg = "没有联网哦!";
} else {
mErrorMsg = "网络连接超时!";
}
break;
default:
mErrorMsg = ((HttpException) e).message();
break;
}
} else if (e instanceof UnknownHostException) {
mErrorMsg = "不知名主机!";
} else if (e instanceof SocketTimeoutException) {
mErrorMsg = "网络连接超时!";
} else
{
mErrorMsg = e.getMessage();
}
mView.showErrorMsg(mErrorMsg);
} | 肖敬先 | |
@ApiResponse<method*start>io.swagger.annotations.ApiResponse<method*end>(code<method*start>io.swagger.annotations.ApiResponse.code<method*end> = 401, message<method*start>io.swagger.annotations.ApiResponse.message<method*end> = "没有权限", response<method*start>io.swagger.annotations.ApiOperation.response<method*end> = ErrorResponse.class) | annotation | @RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>("/client/save")
@ApiResponses<method*start>io.swagger.annotations.ApiResponses<method*end>(value<method*start>io.swagger.annotations.ApiResponses.value<method*end> = { @ApiResponse<method*start>io.swagger.annotations.ApiResponse<method*end>(code<method*start>io.swagger.annotations.ApiResponse.code<method*end> = 400, message<method*start>io.swagger.annotations.ApiResponse.message<method*end> = "保存实体信息失败"),
public ResponseEntity<method*start>org.springframework.http.ResponseEntity<method*end><Client<method*start>indi.liudalei.eidea.api.model.Client<method*end>> saveClient(Client<method*start>indi.liudalei.eidea.api.model.Client<method*end> client) {
if (client == null || client.getName<method*start>indi.liudalei.eidea.api.model.Client.getName<method*end>() == null) {
ResponseEntity<method*start>org.springframework.http.ResponseEntity<method*end> responseEntity = new ResponseEntity<method*start>org.springframework.http.ResponseEntity<method*end>("实体信息不能为空", null, HttpStatus.BAD_REQUEST<method*start>org.springframework.http.HttpStatus.BAD_REQUEST<method*end>);
return responseEntity;
}
return new ResponseEntity<method*start>org.springframework.http.ResponseEntity<method*end><Client<method*start>indi.liudalei.eidea.api.model.Client<method*end>>(new Client<method*start>indi.liudalei.eidea.api.model.Client<method*end>(), null, HttpStatus.OK<method*start>org.springframework.http.HttpStatus.OK<method*end>);
} | 肖敬先 | |
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_USER','ROLE_VISTOR')") | annotation | @DeleteMapping("/{id}")
@Transactional
public ResponseEntity<Response<com.whichard.spring.boot.blog.vo.Response>> delete(@PathVariable("id") Long blogId, @RequestParam(value = "voteId", required = true) Long voteId) {
User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
long userId = principal.getId();
try {
likeService.cancelLike(userId, 0, blogId);
voteService.removeVote(voteId);
blogService.removeVote(blogId, voteId);
} 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<method*start>org.apache.shiro.authz.annotation.RequiresPermissions<method*end>("ueboot:role:delete") | annotation | @PostMapping<method*start>org.springframework.web.bind.annotation.PostMapping<method*end>(value<method*start>org.springframework.web.bind.annotation.RequestMapping.value<method*end> = "/delete")
public Response<method*start>com.ueboot.core.http.response.Response<method*end><String<method*start>java.lang.String<method*end>> delete(Long<method*start>java.lang.Long<method*end>[] id) {
if (id == null || id.length<method*start>java.lang.Long[].length<method*end> == 0 || id.length<method*start>java.lang.Long[].length<method*end> != 1) {
throw new BusinessException("请选择需要删除的角色!");
}
Long<method*start>java.lang.Long<method*end> roleId = id[0];
roleService.delete<method*start>com.ueboot.shiro.service.role.RoleService.delete<method*end>(id);
// 删除 角色日志记录
String<method*start>java.lang.String<method*end> optUserName = (String<method*start>java.lang.String<method*end>) SecurityUtils.getSubject<method*start>org.apache.shiro.SecurityUtils.getSubject<method*end>().getPrincipal<method*start>org.apache.shiro.subject.Subject.getPrincipal<method*end>();
this.shiroEventListener.deleteRoleEvent<method*start>com.ueboot.shiro.shiro.ShiroEventListener.deleteRoleEvent<method*end>(optUserName, id);
return new Response<method*start>com.ueboot.core.http.response.Response<method*end><>();
} | 肖敬先 | |
boolean result = userGroupService.checkUuserPower(groupName, user.getUserId());
if (result) {
body.render(env.getOut());
} | conventional | @Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
User user = UserSessionUtils.getLoginMember(request);
// 获取页面的参数
String groupName = null;
// 处理标签变量
Map<String, TemplateModel> paramWrap = new HashMap<>(params);
for (String str : paramWrap.keySet()) {
if ("groupName".equals(str)) {
groupName = paramWrap.get(str).toString();
}
}
// 获取用户所在的权限组
try {
boolean result = userGroupService.checkUuserPower(groupName, user.getUserId());
if (result) {
body.render(env.getOut());
}
} catch (Exception e) {
e.printStackTrace();
}
} | 肖敬先 | |
if (configuration.getTunnelSignatureKey<method*start>com.qcloud.weapp.Configuration.getTunnelSignatureKey<method*end>() == null)
throw new ConfigurationException<method*start>com.qcloud.weapp.ConfigurationException<method*end>("SDK 密钥配置不能为空"); | conventional | public static void setup(Configuration<method*start>com.qcloud.weapp.Configuration<method*end> configuration) throws ConfigurationException<method*start>com.qcloud.weapp.ConfigurationException<method*end> {
currentConfiguration = configuration;
if (configuration == null) {
throw new ConfigurationException<method*start>com.qcloud.weapp.ConfigurationException<method*end>("配置不能为空");
}
if (configuration.getServerHost<method*start>com.qcloud.weapp.Configuration.getServerHost<method*end>() == null)
throw new ConfigurationException<method*start>com.qcloud.weapp.ConfigurationException<method*end>("服务器主机配置不能为空");
if (configuration.getAuthServerUrl<method*start>com.qcloud.weapp.Configuration.getAuthServerUrl<method*end>() == null)
throw new ConfigurationException<method*start>com.qcloud.weapp.ConfigurationException<method*end>("鉴权服务器配置不能为空");
if (configuration.getTunnelServerUrl<method*start>com.qcloud.weapp.Configuration.getTunnelServerUrl<method*end>() == null)
throw new ConfigurationException<method*start>com.qcloud.weapp.ConfigurationException<method*end>("信道服务器配置不能为空");
}
} | 肖敬先 | |
if (!adminUser.getRole().equals("a")) {
return "/admin/login";
}
if (adminUser == null) {
return "/admin/login";
} | conventional | @RequestMapping("/adminLogin")
public String adminLogin(String name, String password, String captcha, HttpSession session) {
User adminUser = userService.findUser(name, password);
session.setAttribute("user", adminUser);
return "/admin/index";
} | 肖敬先 | |
if (!StringUtils.isEmpty(resource.getUrl()) && !StringUtils.isEmpty(resource.getPermission())) {
if (!"".equals(resource.getPermission().trim())) {
if (resource.getVerification()) {
permsList.add(0, new String[] { resource.getUrl() + "/**", "perms[" + resource.getPermission() + ":*]" });
} else {
anonList.add(0, new String[] { resource.getUrl() + "/**", "anon" });
}
}
} | conventional | @Override
public Map<String, String> getFilterChainDefinitionMap() {
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
List<String[]> permsList = new LinkedList<>();
List<String[]> anonList = new LinkedList<>();
List<SysResource> resources = resourceService.list();
if (resources != null) {
for (SysResource resource : resources) {
iterationAllResourceInToFilter(resource, permsList, anonList);
}
}
for (String[] strings : anonList) {
filterChainDefinitionMap.put(strings[0], strings[1]);
}
for (String[] strings : permsList) {
filterChainDefinitionMap.put(strings[0], strings[1]);
}
filterChainDefinitionMap.put("/**", "anon");
return filterChainDefinitionMap;
} | 肖敬先 | |
if (interfaceRuleDto == null) {
return Result.error("您没有该接口的权限!");
} | conventional | @RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "根据ID获取jeecgDemo信息", notes = "根据ID获取jeecgDemo信息", httpMethod = "GET", produces = "application/json")
public ResponseMessage<?> get(@ApiParam(required = true, name = "id", value = "ID") @PathVariable("id") String id, HttpServletRequest request) {
InterfaceRuleDto interfaceRuleDto = InterfaceUtil.getInterfaceRuleDto(request, InterfaceEnum.jeecgdemo_get);
JeecgDemoEntity task = this.jeecgDemoService.get(JeecgDemoEntity.class, id);
if (task == null) {
return Result.error("根据ID获取jeecgDemo信息为空");
}
return Result.success(task);
} | 肖敬先 | |
case "create":
if (!"create".equals<method*start>java.lang.String.equals<method*end>(crudConfig.retrievePermission<method*start>cn.ffast.core.annotations.CrudConfig.retrievePermission<method*end>())) {
AnnotationUtils.setAnnotationValue<method*start>cn.ffast.core.utils.AnnotationUtils.setAnnotationValue<method*end>(methods[i].getAnnotation<method*start>java.lang.reflect.Method.getAnnotation<method*end>(Permission<method*start>cn.ffast.core.annotations.Permission<method*end>.class), "value", crudConfig.createPermission<method*start>cn.ffast.core.annotations.CrudConfig.createPermission<method*end>());
}
break;
case "list":
if (!"list".equals<method*start>java.lang.String.equals<method*end>(crudConfig.retrievePermission<method*start>cn.ffast.core.annotations.CrudConfig.retrievePermission<method*end>())) {
AnnotationUtils.setAnnotationValue<method*start>cn.ffast.core.utils.AnnotationUtils.setAnnotationValue<method*end>(methods[i].getAnnotation<method*start>java.lang.reflect.Method.getAnnotation<method*end>(Permission<method*start>cn.ffast.core.annotations.Permission<method*end>.class), "value", crudConfig.retrievePermission<method*start>cn.ffast.core.annotations.CrudConfig.retrievePermission<method*end>());
}
break;
case "update":
if (!"update".equals<method*start>java.lang.String.equals<method*end>(crudConfig.updatePermission<method*start>cn.ffast.core.annotations.CrudConfig.updatePermission<method*end>())) {
AnnotationUtils.setAnnotationValue<method*start>cn.ffast.core.utils.AnnotationUtils.setAnnotationValue<method*end>(methods[i].getAnnotation<method*start>java.lang.reflect.Method.getAnnotation<method*end>(Permission<method*start>cn.ffast.core.annotations.Permission<method*end>.class), "value", crudConfig.updatePermission<method*start>cn.ffast.core.annotations.CrudConfig.updatePermission<method*end>());
}
break;
case "delete":
if (!"delete".equals<method*start>java.lang.String.equals<method*end>(crudConfig.deletePermission<method*start>cn.ffast.core.annotations.CrudConfig.deletePermission<method*end>())) {
AnnotationUtils.setAnnotationValue<method*start>cn.ffast.core.utils.AnnotationUtils.setAnnotationValue<method*end>(methods[i].getAnnotation<method*start>java.lang.reflect.Method.getAnnotation<method*end>(Permission<method*start>cn.ffast.core.annotations.Permission<method*end>.class), "value", crudConfig.deletePermission<method*start>cn.ffast.core.annotations.CrudConfig.deletePermission<method*end>());
}
break;
default:
break;
}
}
} | conventional | @PostConstruct
private void initCrudController() {
CrudConfig<method*start>cn.ffast.core.annotations.CrudConfig<method*end> crudConfig = getCrudConfig<method*start>cn.ffast.core.support.BaseCrudController.getCrudConfig<method*end>();
if (crudConfig != null) {
Method<method*start>java.lang.reflect.Method<method*end>[] methods = getClass<method*start>cn.ffast.core.support.BaseCrudController.getClass<method*end>().getSuperclass<method*start>java.lang.Class<cn.ffast.core.support.BaseCrudController>.getSuperclass<method*end>().getMethods<method*start>java.lang.Class.getMethods<method*end>();
for (int i = 0; i < methods.length<method*start>java.lang.reflect.Method[].length<method*end>; i++) {
switch(methods[i].getName<method*start>java.lang.reflect.Method.getName<method*end>()) {
} | 肖敬先 | |
if (ReflectUtil.needsPackageAccessCheck<method*start>sun.reflect.misc.ReflectUtil.needsPackageAccessCheck<method*end>(caller.getClassLoader<method*start>java.lang.Class.getClassLoader<method*end>(), ihClass.getClassLoader<method*start>java.lang.Class.getClassLoader<method*end>())) {
ReflectUtil.checkPackageAccess<method*start>sun.reflect.misc.ReflectUtil.checkPackageAccess<method*end>(ihClass);
} | conventional | @CallerSensitive
public static InvocationHandler<method*start>java.lang.reflect.InvocationHandler<method*end> getInvocationHandler(Object<method*start>java.lang.Object<method*end> proxy) throws IllegalArgumentException<method*start>java.lang.IllegalArgumentException<method*end> {
final InvocationHandler<method*start>java.lang.reflect.InvocationHandler<method*end> ih = ((Proxy) proxy).h<method*start>java.lang.reflect.Proxy.h<method*end>;
if (System.getSecurityManager<method*start>java.lang.System.getSecurityManager<method*end>() == null) {
return ih;
}
Class<method*start>java.lang.Class<method*end><?> caller = Reflection.getCallerClass<method*start>jdk.internal.reflect.Reflection.getCallerClass<method*end>();
Class<method*start>java.lang.Class<method*end><?> ihClass = ih.getClass<method*start>java.lang.reflect.InvocationHandler.getClass<method*end>();
return ih;
} | 肖敬先 | |
AccessRequired accessRequired = ((HandlerMethod) handler).getMethodAnnotation(AccessRequired.class);
AdminReqired adminReqired = ((HandlerMethod) handler).getMethodAnnotation(AdminReqired.class);
if (adminReqired != null && adminReqired.validate()) {
User user = (User) httpServletRequest.getSession().getAttribute(Const.CURRENT_USER);
if (user == null) {
throw new UnauthorizedException("未登录");
}
if (user.getRole() != Const.Role.ROLE_ADMIN) {
throw new UnauthorizedException("你不是管理员无权访问");
}
return true;
}
if (accessRequired != null && accessRequired.validate()) {
User user = (User) httpServletRequest.getSession().getAttribute(Const.CURRENT_USER);
if (user == null) {
throw new UnauthorizedException("未登录");
}
return true;
}
return true; | conventional | @Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
return true;
}
return true;
} | 肖敬先 | |
// 校验
if (service.verify<method*start>com.egzosn.pay.union.api.UnionPayService.verify<method*end>(params)) {
// 支付校验通过后的处理
// ......业务逻辑处理块........
} | conventional | @RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>(value<method*start>java.lang.annotation.Retention.value<method*end> = "microPay")
public Map<method*start>java.util.Map<method*end><String<method*start>java.lang.String<method*end>, Object<method*start>java.lang.Object<method*end>> microPay(BigDecimal<method*start>java.math.BigDecimal<method*end> price, String<method*start>java.lang.String<method*end> authCode) {
PayOrder<method*start>com.egzosn.pay.common.bean.PayOrder<method*end> order = new PayOrder<method*start>com.egzosn.pay.common.bean.PayOrder<method*end>("egan order", "egan order", null == price ? new BigDecimal<method*start>java.math.BigDecimal<method*end>(0.01) : price, SignUtils.randomStr<method*start>com.egzosn.pay.common.util.sign.SignUtils.randomStr<method*end>(), UnionTransactionType.CONSUME<method*start>com.egzosn.pay.union.bean.UnionTransactionType.CONSUME<method*end>);
order.setAuthCode<method*start>com.egzosn.pay.common.bean.PayOrder.setAuthCode<method*end>(authCode);
Map<method*start>java.util.Map<method*end><String<method*start>java.lang.String<method*end>, Object<method*start>java.lang.Object<method*end>> params = service.microPay<method*start>com.egzosn.pay.union.api.UnionPayService.microPay<method*end>(order);
return params;
} | 万爽 | |
if (!user.equals(createdBy[0])) {
throw new DataSpecificationException("无权删除他人目录");
} | conventional | @Override
public int delete(ID recordId) {
Object inFolder = Application.createQueryNoFilter("select inFolder from Attachment where inFolder = ?").setParameter(1, recordId).unique();
if (inFolder != null) {
throw new DataSpecificationException("目录内有文件不能删除");
}
Object parent = Application.createQueryNoFilter("select parent from AttachmentFolder where parent = ?").setParameter(1, recordId).unique();
if (parent != null) {
throw new DataSpecificationException("目录内有子目录不能删除");
}
ID user = Application.getCurrentUser();
if (!UserHelper.isAdmin(user)) {
Object[] createdBy = Application.createQueryNoFilter("select createdBy from AttachmentFolder where folderId = ?").setParameter(1, recordId).unique();
}
return super.delete(recordId);
} | 万爽 | |
if (manager != null && manager.getUsername<method*start>com.hibernate.model.Login.getUsername<method*end>().equals<method*start>java.lang.String.equals<method*end>("mr")) | conventional | protected ModelAndView<method*start>org.springframework.web.servlet.ModelAndView<method*end> onSubmit(HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request, HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response, Object<method*start>java.lang.Object<method*end> command, BindException<method*start>org.springframework.validation.BindException<method*end> errors) throws Exception<method*start>java.lang.Exception<method*end> {
HttpSession<method*start>javax.servlet.http.HttpSession<method*end> session = request.getSession<method*start>javax.servlet.http.HttpServletRequest.getSession<method*end>();
Login manager = (Login) session.getAttribute<method*start>javax.servlet.http.HttpSession.getAttribute<method*end>("loginUser");
Map<method*start>java.util.Map<method*end> model = new HashMap<method*start>java.util.HashMap<method*end>();
{
Login newUser = (Login) command;
List<method*start>java.util.List<method*end> list = dao.QueryObject<method*start>com.hibernate.dao.DAOSupport.QueryObject<method*end>("from Login where username='" + newUser.getUsername<method*start>com.hibernate.model.Login.getUsername<method*end>() + "'");
if (list.size<method*start>java.util.List.size<method*end>() > 0)
model.put<method*start>java.util.Map.put<method*end>("message", "登录名称已经存在,请更换用户名。");
else {
dao.InsertOrUpdate<method*start>com.hibernate.dao.DAOSupport.InsertOrUpdate<method*end>(newUser);
model.put<method*start>java.util.Map.put<method*end>("message", "用户\"" + newUser.getName<method*start>com.hibernate.model.Login.getName<method*end>() + "\"添加成功。");
}
} else
model.put<method*start>java.util.Map.put<method*end>("message", "权限不够或未登录,请返回登陆。");
return new ModelAndView<method*start>org.springframework.web.servlet.ModelAndView<method*end>("userManager/addUser", model);
} | 万爽 | |
if (!dir.canWrite()) {
throw new IOException("上传目录没有写权限");
} | conventional | @Override
public String save(MultipartFile file, byte[] bytes, IUploadContext context) throws UploadException, IOException {
if (StringUtils.isBlank(this.dir)) {
throw new UploadException("文件保存路径不存在");
}
if (StringUtils.isBlank(urlPrefix)) {
urlPrefix = String.format("%s://%s/", context.getSchema(), context.getHeader(HttpHeaders.HOST));
}
String newFileName = getNewFileName(file, context);
String additionalPath = getSafePath(StringUtils.stripStart(getAdditionalPath(file, context), SEPARATOR));
String saveDir = getSafePath(this.dir) + additionalPath;
File dir = new File(saveDir);
if (!dir.exists()) {
dir.mkdirs();
}
BufferedOutputStream buffStream = null;
try {
buffStream = new BufferedOutputStream(new FileOutputStream(saveDir + newFileName));
buffStream.write(bytes);
} finally {
if (buffStream != null) {
buffStream.close();
}
}
return getSafePath(this.urlPrefix) + additionalPath + newFileName;
} | 万爽 | |
String noAuthPage = getServiceDegardingPage();
if (StringUtils.isNotEmpty(requestAccept)) {
if (StringUtils.contains(requestAccept, "application/json") || StringUtils.contains(requestAccept, "text/javascript") || StringUtils.contains(requestAccept, "text/json")) {
contentType = "application/json";
}
} | conventional | public void serviceDegardingPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String servletPath = request.getServletPath();
request.setAttribute("currentUrl", servletPath);
String requestAccept = request.getHeader("accept");
String contentType = "text/html";
response.setHeader("Content-Type", contentType + "; charset=UTF-8");
if (contentType.equals("text/html")) {
clientRedirect(response, noAuthPage);
} else if (contentType.equals("application/json")) {
JsonData result = JsonData.error("服务降级,请稍后再试");
response.getWriter().print(JsonMapper.obj2String(result));
} else {
clientRedirect(response, noAuthPage);
}
} | 万爽 | |
if (null == sysRole) {
return Result.error<method*start>my.common.beans.Result.error<method*end>("[0]无效编码!");
} | conventional | @PostMapping({ "delete" })
@ResponseBody
public Result<method*start>my.common.beans.Result<method*end> delete(SysRole<method*start>my.admin.model.SysRole<method*end> row) {
Map<method*start>java.util.Map<method*end><String<method*start>java.lang.String<method*end>, Object> paras = new HashMap<method*start>java.util.HashMap<method*end><>();
Map<method*start>java.util.Map<method*end><String<method*start>java.lang.String<method*end>, Object> paras = new HashMap<method*start>java.util.HashMap<method*end><>();
if (row != null) {
String<method*start>java.lang.String<method*end> pk = row.getRoleCode<method*start>my.admin.model.SysRole.getRoleCode<method*end>();
SysRole<method*start>my.admin.model.SysRole<method*end> sysRole = modelService.single<method*start>my.admin.framework.service.RoleService.single<method*end>(pk);
if ("1".equals<method*start>java.lang.String.equals<method*end>(sysRole.getIsSys<method*start>my.admin.model.SysRole.getIsSys<method*end>())) {
return Result.error<method*start>my.common.beans.Result.error<method*end>("[1]系统内置角色,不可删除!");
}
List<method*start>java.util.List<method*end><Map<method*start>java.util.Map<method*end>> userRoleList = Collections.EMPTY_LIST<method*start>java.util.Collections.EMPTY_LIST<method*end>;
if (StrUtil.isNotBlank<method*start>cn.hutool.core.util.StrUtil.isNotBlank<method*end>(pk)) {
paras.put<method*start>java.util.Map.put<method*end>("roleCode", pk);
userRoleList = modelService.execute<method*start>my.admin.framework.service.RoleService.execute<method*end>("select" + " t1.*" + " from sys_user_role t1" + " where t1.role_code=#roleCode#", Map<method*start>java.util.Map<method*end>.class, paras);
}
if (userRoleList.size<method*start>java.util.List.size<method*end>() > 0) {
return Result.error<method*start>my.common.beans.Result.error<method*end>("该角色下有授权用户,请取消后再删除该角色!");
}
modelService.deleteById<method*start>my.admin.framework.service.RoleService.deleteById<method*end>(pk);
}
return Result.SUCCESS<method*start>my.common.beans.Result.SUCCESS<method*end>;
} | 万爽 | |
// 检查权限
if (ContextCompat<method*start>android.support.v4.content.ContextCompat<method*end>.checkSelfPermission(this, Manifest<method*start>android.Manifest<method*end>.permission.READ_EXTERNAL_STORAGE) != PackageManager<method*start>android.content.pm.PackageManager<method*end>.PERMISSION_GRANTED) {
RxPermissions<method*start>com.tbruyelle.rxpermissions2.RxPermissions<method*end> rxPermissions = new RxPermissions<method*start>com.tbruyelle.rxpermissions2.RxPermissions<method*end>(this);
rxPermissions.requestEach(Manifest<method*start>android.Manifest<method*end>.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<method*start>io.reactivex.functions.Consumer<method*end><Permission<method*start>com.tbruyelle.rxpermissions2.Permission<method*end>>() {
@Override
public void accept(Permission<method*start>com.tbruyelle.rxpermissions2.Permission<method*end> permission) throws Exception<method*start>java.lang.Exception<method*end> {
if (permission.granted) {
// `permission.name` is granted !
T<method*start>com.handsome.library.T<method*end>.info("可以保存妹子到本地啦");
} else if (permission.shouldShowRequestPermissionRationale) {
// Denied permission without ask never again
// 禁止 以后不在询问
T<method*start>com.handsome.library.T<method*end>.info("无法保存妹子啦");
} else {
// Denied permission with ask never again
// Need to go to the settings
// 当前禁止
T<method*start>com.handsome.library.T<method*end>.info("无法保存妹子啦");
}
}
});
} | conventional | private void requestDynamicPermissions() {
} | 万爽 | |
// 先判断登陆用户是否存在
SysUser user = userRepository.findByUserName(userName);
if (user == null) {
throw new UsernameNotFoundException("Cannot find user by username: " + userName);
}
// 登录用户存在的情况加载用户的权限
List<SysAuthority> roleList = authorityRepository.findByUserId(user.getId());
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
if (roleList != null && roleList.size() > 0) {
roleList.forEach(r -> grantedAuthorities.add(new SimpleGrantedAuthority(r.getName())));
} | conventional | @Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
return new User(user.getUserName(), user.getPassword(), grantedAuthorities);
} | 万爽 | |
if (crmBusiness.getOwnerUserId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmBusiness.getOwnerUserId<method*end>() != null) {
Record<method*start>com.jfinal.plugin.activerecord.Record<method*end> ownerUser = Db.findFirst<method*start>com.jfinal.plugin.activerecord.Db.findFirst<method*end>(Db.getSql<method*start>com.jfinal.plugin.activerecord.Db.getSql<method*end>("crm.customer.getMembers"), crmBusiness.getOwnerUserId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmBusiness.getOwnerUserId<method*end>());
recordList.add<method*start>java.util.List.add<method*end>(ownerUser.set<method*start>com.jfinal.plugin.activerecord.Record.set<method*end>("power", "负责人权限").set<method*start>com.jfinal.plugin.activerecord.Record.set<method*end>("groupRole", "负责人"));
} | conventional | public List<method*start>java.util.List<method*end><Record<method*start>com.jfinal.plugin.activerecord.Record<method*end>> getMembers(Integer<method*start>java.lang.Integer<method*end> businessId) {
CrmBusiness<method*start>com.kakarote.crm9.erp.crm.entity.CrmBusiness<method*end> crmBusiness = CrmBusiness.dao.findById<method*start>com.jfinal.plugin.activerecord.Model.findById<method*end>(businessId);
List<method*start>java.util.List<method*end><Record<method*start>com.jfinal.plugin.activerecord.Record<method*end>> recordList = new ArrayList<method*start>java.util.ArrayList<method*end><>();
String<method*start>java.lang.String<method*end> roUserId = crmBusiness.getRoUserId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmBusiness.getRoUserId<method*end>();
String<method*start>java.lang.String<method*end> rwUserId = crmBusiness.getRwUserId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmBusiness.getRwUserId<method*end>();
String<method*start>java.lang.String<method*end> memberIds = roUserId + rwUserId.substring<method*start>java.lang.String.substring<method*end>(1);
if (",".equals<method*start>java.lang.String.equals<method*end>(memberIds)) {
return recordList;
}
String<method*start>java.lang.String<method*end>[] memberIdsArr = memberIds.substring<method*start>java.lang.String.substring<method*end>(1, memberIds.length<method*start>java.lang.String.length<method*end>() - 1).split<method*start>java.lang.String.split<method*end>(",");
Set<method*start>java.util.Set<method*end><String<method*start>java.lang.String<method*end>> memberIdsSet = new HashSet<method*start>java.util.HashSet<method*end><>(Arrays.asList<method*start>java.util.Arrays.asList<method*end>(memberIdsArr));
for (String<method*start>java.lang.String<method*end> memberId : memberIdsSet) {
Record<method*start>com.jfinal.plugin.activerecord.Record<method*end> record = Db.findFirst<method*start>com.jfinal.plugin.activerecord.Db.findFirst<method*end>(Db.getSql<method*start>com.jfinal.plugin.activerecord.Db.getSql<method*end>("crm.customer.getMembers"), memberId);
if (roUserId.contains<method*start>java.lang.String.contains<method*end>(memberId)) {
record.set<method*start>com.jfinal.plugin.activerecord.Record.set<method*end>("power", "只读").set<method*start>com.jfinal.plugin.activerecord.Record.set<method*end>("groupRole", "普通成员");
}
if (rwUserId.contains<method*start>java.lang.String.contains<method*end>(memberId)) {
record.set<method*start>com.jfinal.plugin.activerecord.Record.set<method*end>("power", "读写").set<method*start>com.jfinal.plugin.activerecord.Record.set<method*end>("groupRole", "普通成员");
}
recordList.add<method*start>java.util.List.add<method*end>(record);
}
return recordList;
} | 万爽 | |
@RequiresPermissions("oss:file:upload") | annotation | @ApiOperation(value = "文件上传", notes = "权限编码(oss:file:upload)")
@PostMapping("/upload")
public JsonResponse<com.king.common.utils.JsonResponse> upload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
if (file.isEmpty()) {
throw new RRException("上传文件不能为空");
}
// 上传文件
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
// 初始化获取配置
CloudStorageService cloudStorage = OSSFactory.build();
CloudStorageConfig config = cloudStorage.config;
String url = cloudStorage.uploadSuffix(file.getBytes(), suffix);
String size = new BigDecimal(file.getSize()).divide(new BigDecimal(1024), RoundingMode.HALF_UP) + " KB";
// 保存文件信息
OssFile oss = new OssFile();
oss.setType(config.getType() + "");
oss.setSize(size);
oss.setUrl(url);
oss.setName(file.getOriginalFilename());
oss.setCreator(getUser().getUsername());
oss.setCreateDate(new Date());
ossFileService.save(oss);
return JsonResponse.success(url);
} | 万爽 | |
// 校验操作用户当前的操作是否具有此操作权限
boolean isSuccess = limitService.verify(user, operation, resources, dataDom);
if (isSuccess) {
filterChain.doFilter(request, response);
} else {
output(response, LimitsResult.failure().noPermission());
return;
} | conventional | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
// 获取当前操作用户信息
User user = ParamUtils.getUser(request);
// 解析出当前操作
Operation operation = ParamUtils.getOperation(request);
// 解析出当前操作的资源
List<Resource> resources = ParamUtils.getResources(request);
// 解析出当前操作的数据
DataParam dataDom = ParamUtils.getLimitData(request);
// 校验操作用户当前的操作是否具有此操作权限
filterChain.doFilter(request, response);
} | 肖敬先 | |
// 验证所属俱乐部
if (itemInDb == null || !itemInDb.getClubId<method*start>com.stylefeng.guns.modular.system.model.ClubCoach.getClubId<method*end>().equals(clubId)) {
return ResponseEntity.ok<method*start>org.springframework.http.ResponseEntity.ok<method*end>(new ReturnTip<method*start>com.stylefeng.guns.rest.common.ReturnTip<method*end>(501, "访问受限"));
} | conventional | @SuppressWarnings("unchecked")
@RequestMapping(value<method*start>org.springframework.web.bind.annotation.RequestMapping.value<method*end> = "/detail")
@ResponseBody
public Object<method*start>java.lang.Object<method*end> detail() {
HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request = this.getHttpServletRequest<method*start>com.stylefeng.guns.core.base.controller.BaseController.getHttpServletRequest<method*end>();
Integer<method*start>java.lang.Integer<method*end> id = Convert.toInt<method*start>com.stylefeng.guns.core.util.Convert.toInt<method*end>(request.getParameter<method*start>javax.servlet.http.HttpServletRequest.getParameter<method*end>("id"));
Integer<method*start>java.lang.Integer<method*end> clubId = Convert.toInt<method*start>com.stylefeng.guns.core.util.Convert.toInt<method*end>(request.getParameter<method*start>javax.servlet.http.HttpServletRequest.getParameter<method*end>("clubId"));
if (ToolUtil.isEmpty<method*start>com.stylefeng.guns.core.util.ToolUtil.isEmpty<method*end>(id) || ToolUtil.isEmpty<method*start>com.stylefeng.guns.core.util.ToolUtil.isEmpty<method*end>(clubId)) {
return new ReturnTip<method*start>com.stylefeng.guns.rest.common.ReturnTip<method*end>(500, "参数错误");
}
ClubCoach<method*start>com.stylefeng.guns.modular.system.model.ClubCoach<method*end> itemInDb = clubCoachService.selectById<method*start>com.stylefeng.guns.modular.mch.club.service.IClubCoachService.selectById<method*end>(id);
Map<method*start>java.util.Map<method*end><String<method*start>java.lang.String<method*end>, Object<method*start>java.lang.Object<method*end>> mapRet = null;
try {
mapRet = ToolUtil.convertBean<method*start>com.stylefeng.guns.core.util.ToolUtil.convertBean<method*end>(itemInDb);
} catch (Exception<method*start>java.lang.Exception<method*end> e) {
// TODO Auto-generated catch block
e.printStackTrace<method*start>java.lang.Exception.printStackTrace<method*end>();
}
new ClubCoachWarpper<method*start>com.stylefeng.guns.modular.system.warpper.ClubCoachWarpper<method*end>(null).warpTheMap<method*start>com.stylefeng.guns.modular.system.warpper.ClubCoachWarpper.warpTheMap<method*end>(mapRet);
mapRet.remove<method*start>java.util.Map.remove<method*end>("auth");
return new ReturnTip<method*start>com.stylefeng.guns.rest.common.ReturnTip<method*end>(0, "成功", mapRet);
} | 肖敬先 | |
if (session.getAttribute("UserInfo_session") != null) | conventional | @RequestMapping(value = "app/user/user_info{user_info_id}/edit", produces = { "application/json;charset=UTF-8" })
@ResponseBody
public String user_info_edit(@RequestBody String result, HttpServletRequest request, HttpSession session) {
try {
long user_info_id = Long.valueOf(request.getParameter("user_info_id"));
String name = request.getParameter("name");
String user_email = request.getParameter("user_email");
int exam_year = Integer.valueOf(request.getParameter("exam_year"));
int user_gender = Integer.valueOf(request.getParameter("user_gender"));
String user_home_province = request.getParameter("user_home_province");
String user_home_city = request.getParameter("user_home_city");
String user_ben_school = request.getParameter("user_ben_school");
String user_want_school = request.getParameter("user_want_school");
int updaterow = userService.updateUserInfo(user_info_id, name, user_email, exam_year, user_gender, user_home_province, user_home_city, user_ben_school, user_want_school);
if (updaterow > 0) {
result = "1";
} else {
result = "0";
}
} catch (Exception e) {
System.out.println(e);
}
return result;
} | 肖敬先 | |
if (UserRealm.SUPER_USER.equals(username)) {
return this.resourcesRepository.findAll();
}
permissions.forEach((p) -> {
resourcesMap.put(p.getResource().getId(), p.getResource());
}); | conventional | @Override
public Collection<Resources> getUserResources(String username) {
// root用户返回所有菜单,防止root账户还需要授权才能访问
// 找出用户的角色,根据角色查找用户的菜单
// 直接调用shiroService的实现方式,防止使用框架方需要自定义角色获取方式
Set<String> roleNames = shiroService.getUserRoleNames(username);
List<Permission> permissions = permissionRepository.findByRoleNameIn(roleNames);
Map<Long, Resources> resourcesMap = new HashMap<>();
return resourcesMap.values();
} | 肖敬先 | |
InterfaceRuleDto interfaceRuleDto = InterfaceUtil.getInterfaceRuleDto(request, InterfaceEnum.jeecgdemo_list);
if (interfaceRuleDto == null) {
return Result.error("您没有该接口的权限!");
} | conventional | @RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "jeecgDemo列表信息", produces = "application/json", httpMethod = "GET")
public ResponseMessage<Map<String, Object>> list(@RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize, JeecgDemoEntity entity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
CriteriaQuery query = new CriteriaQuery(JeecgDemoEntity.class, dataGrid);
InterfaceUtil.installCriteriaQuery(query, interfaceRuleDto, InterfaceEnum.jeecgdemo_list);
org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(query, entity, request.getParameterMap());
query.setCurPage(pageNo <= 0 ? 1 : pageNo);
query.setPageSize(pageSize);
query.addOrder("createDate", SortDirection.desc);
query.add();
this.jeecgDemoService.getDataGridReturn(query, true);
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("data", dataGrid.getResults());
resultMap.put("total", dataGrid.getTotal());
return Result.success(resultMap);
} | 肖敬先 | |
// 防止 url 写错
if (!access_token_uri.contains<method*start>java.lang.String.contains<method*end>("token") || !authorization_uri.contains<method*start>java.lang.String.contains<method*end>("authorize"))
throw new RuntimeException<method*start>java.lang.RuntimeException<method*end>("uri is wrong : access_token_uri = " + access_token_uri + " , authorization_uri" + authorization_uri);
| conventional | public OAuth2RestOperations<method*start>org.springframework.security.oauth2.client.OAuth2RestOperations<method*end> authorizationCodeRestTemplate(String<method*start>java.lang.String<method*end> client_id, String<method*start>java.lang.String<method*end> client_secret, String<method*start>java.lang.String<method*end> authorization_uri, String<method*start>java.lang.String<method*end> access_token_uri, String<method*start>java.lang.String<method*end>... scope) {
AuthorizationCodeResourceDetails<method*start>org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails<method*end> details = new AuthorizationCodeResourceDetails<method*start>org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails<method*end>();
details.setId<method*start>org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails.setId<method*end>("1");
details.setClientId<method*start>org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails.setClientId<method*end>(client_id);
if (client_secret != null && !client_secret.isEmpty<method*start>java.lang.String.isEmpty<method*end>())
details.setClientSecret<method*start>org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails.setClientSecret<method*end>(client_secret);
details.setAccessTokenUri<method*start>org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails.setAccessTokenUri<method*end>(access_token_uri);
details.setUserAuthorizationUri<method*start>org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails.setUserAuthorizationUri<method*end>(authorization_uri);
// 将当前请求的 uri 作为参数 redirect_uri 接受返回值。设置为 faslse 是,需要设置 redirect_uri 参数, details.setPreEstablishedRedirectUri("http://anywhere");
details.setUseCurrentUri<method*start>org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails.setUseCurrentUri<method*end>(true);
details.setScope<method*start>org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails.setScope<method*end>(Arrays.asList<method*start>java.util.Arrays.asList<method*end>(scope));
return new OAuth2RestTemplate<method*start>org.springframework.security.oauth2.client.OAuth2RestTemplate<method*end>(details, oAuth2ClientContext);
} | 肖敬先 | |
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>) && !BaseUtil.getUser<method*start>com.kakarote.crm9.utils.BaseUtil.getUser<method*end>().getRoles<method*start>com.kakarote.crm9.erp.admin.entity.AdminUser.getRoles<method*end>().contains<method*start>java.util.List.contains<method*end>(BaseConstant.SUPER_ADMIN_ROLE_ID<method*start>com.kakarote.crm9.common.constant.BaseConstant.SUPER_ADMIN_ROLE_ID<method*end>) && Db.queryInt<method*start>com.jfinal.plugin.activerecord.Db.queryInt<method*end>(Db.getSql<method*start>com.jfinal.plugin.activerecord.Db.getSql<method*end>("crm.customer.queryIsRoUser"), BaseUtil.getUserId<method*start>com.kakarote.crm9.utils.BaseUtil.getUserId<method*end>(), id) > 0) {
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> deleteByIds(String<method*start>java.lang.String<method*end> customerIds) {
String<method*start>java.lang.String<method*end>[] idsArr = customerIds.split<method*start>java.lang.String.split<method*end>(",");
List<method*start>java.util.List<method*end><Record<method*start>com.jfinal.plugin.activerecord.Record<method*end>> idsList = new ArrayList<method*start>java.util.ArrayList<method*end><>();
for (String<method*start>java.lang.String<method*end> id : idsArr) {
}
Record<method*start>com.jfinal.plugin.activerecord.Record<method*end> record = new Record<method*start>com.jfinal.plugin.activerecord.Record<method*end>();
idsList.add<method*start>java.util.List.add<method*end>(record.set<method*start>com.jfinal.plugin.activerecord.Record.set<method*end>("customer_id", Integer.valueOf<method*start>java.lang.Integer.valueOf<method*end>(id)));
}
Integer<method*start>java.lang.Integer<method*end> contactsNum = Db.queryInt<method*start>com.jfinal.plugin.activerecord.Db.queryInt<method*end>(Db.getSql<method*start>com.jfinal.plugin.activerecord.Db.getSql<method*end>("crm.customer.queryContactsNumber"), customerIds);
Integer<method*start>java.lang.Integer<method*end> businessNum = Db.queryInt<method*start>com.jfinal.plugin.activerecord.Db.queryInt<method*end>(Db.getSql<method*start>com.jfinal.plugin.activerecord.Db.getSql<method*end>("crm.customer.queryBusinessNumber"), customerIds);
if (contactsNum > 0 || businessNum > 0) {
return R.error<method*start>com.kakarote.crm9.utils.R.error<method*end>("该条数据与其他数据有必要关联,请勿删除");
}
List<method*start>java.util.List<method*end><Record<method*start>com.jfinal.plugin.activerecord.Record<method*end>> batchIdList = Db.find<method*start>com.jfinal.plugin.activerecord.Db.find<method*end>(Db.getSqlPara<method*start>com.jfinal.plugin.activerecord.Db.getSqlPara<method*end>("crm.customer.queryBatchIdByIds", Kv.by<method*start>com.jfinal.kit.Kv.by<method*end>("ids", idsArr)));
return Db.tx<method*start>com.jfinal.plugin.activerecord.Db.tx<method*end>(() -> {
Db.batch<method*start>com.jfinal.plugin.activerecord.Db.batch<method*end>(Db.getSql<method*start>com.jfinal.plugin.activerecord.Db.getSql<method*end>("crm.customer.deleteByIds"), "customer_id", idsList, 100);
Db.batch<method*start>com.jfinal.plugin.activerecord.Db.batch<method*end>("delete from 72crm_admin_fieldv where batch_id = ?", "batch_id", batchIdList, 100);
return true;
}) ? R.ok<method*start>com.kakarote.crm9.utils.R.ok<method*end>() : R.error<method*start>com.kakarote.crm9.utils.R.error<method*end>();
} | 肖敬先 | |
if (e.getError().getErrorCode() == 48001) {
this.logger.info("该公众号没有获取用户信息权限!");
} | conventional | @Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService weixinService, WxSessionManager sessionManager) throws WxErrorException {
this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());
// 获取微信用户基本信息
try {
WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
if (userWxInfo != null) {
// TODO 可以添加关注用户到本地数据库
}
} catch (WxErrorException e) {
}
WxMpXmlOutMessage responseResult = null;
try {
responseResult = this.handleSpecial(wxMessage);
} catch (Exception e) {
this.logger.error(e.getMessage(), e);
}
if (responseResult != null) {
return responseResult;
}
try {
return new TextBuilder().build("感谢关注", wxMessage, weixinService);
} catch (Exception e) {
this.logger.error(e.getMessage(), e);
}
return null;
} | 肖敬先 | |
if (cellVal.toString<method*start>java.lang.Object.toString<method*end>().equals<method*start>java.lang.String.equals<method*end>(DataListWrapper.NO_READ_PRIVILEGES<method*start>com.rebuild.server.helper.datalist.DataListWrapper.NO_READ_PRIVILEGES<method*end>)) {
cellVal = "[无权限]";
} | conventional | protected List<method*start>java.util.List<method*end><List<method*start>java.util.List<method*end><Object<method*start>java.lang.Object<method*end>>> buildData(DefaultDataListControl<method*start>com.rebuild.server.helper.datalist.DefaultDataListControl<method*end> control) {
JSONArray<method*start>com.alibaba.fastjson.JSONArray<method*end> data = ((JSONObject<method*start>com.alibaba.fastjson.JSONObject<method*end>) control.getJSONResult<method*start>com.rebuild.server.helper.datalist.DefaultDataListControl.getJSONResult<method*end>()).getJSONArray<method*start>com.alibaba.fastjson.JSONObject.getJSONArray<method*end>("data");
List<method*start>java.util.List<method*end><List<method*start>java.util.List<method*end><Object<method*start>java.lang.Object<method*end>>> into = new ArrayList<method*start>java.util.ArrayList<method*end><>();
for (Object<method*start>java.lang.Object<method*end> row : data) {
JSONArray<method*start>com.alibaba.fastjson.JSONArray<method*end> rowJson = (JSONArray<method*start>com.alibaba.fastjson.JSONArray<method*end>) row;
int cellIndex = 0;
List<method*start>java.util.List<method*end><Object<method*start>java.lang.Object<method*end>> cellVals = new ArrayList<method*start>java.util.ArrayList<method*end><>();
for (Object<method*start>java.lang.Object<method*end> cellVal : rowJson) {
// 详情可见 QueryParser#doParseIfNeed (L171)
if (cellIndex >= headFields.size<method*start>java.util.List.size<method*end>()) {
break;
}
Field<method*start>cn.devezhao.persist4j.Field<method*end> field = headFields.get<method*start>java.util.List.get<method*end>(cellIndex++);
DisplayType<method*start>com.rebuild.server.metadata.entity.DisplayType<method*end> dt = EasyMeta.getDisplayType<method*start>com.rebuild.server.metadata.entity.EasyMeta.getDisplayType<method*end>(field);
if (cellVal == null) {
cellVal = StringUtils.EMPTY<method*start>org.apache.commons.lang.StringUtils.EMPTY<method*end>;
} else if (dt == DisplayType.FILE<method*start>com.rebuild.server.metadata.entity.DisplayType.FILE<method*end> || dt == DisplayType.IMAGE<method*start>com.rebuild.server.metadata.entity.DisplayType.IMAGE<method*end> || dt == DisplayType.AVATAR<method*start>com.rebuild.server.metadata.entity.DisplayType.AVATAR<method*end> || dt == DisplayType.ANYREFERENCE<method*start>com.rebuild.server.metadata.entity.DisplayType.ANYREFERENCE<method*end>) {
cellVal = "[暂不支持" + dt.getDisplayName<method*start>com.rebuild.server.metadata.entity.DisplayType.getDisplayName<method*end>() + "字段]";
} else if (dt == DisplayType.DECIMAL<method*start>com.rebuild.server.metadata.entity.DisplayType.DECIMAL<method*end> || dt == DisplayType.NUMBER<method*start>com.rebuild.server.metadata.entity.DisplayType.NUMBER<method*end>) {
// 移除千分位
cellVal = cellVal.toString<method*start>java.lang.Object.toString<method*end>().replace<method*start>java.lang.String.replace<method*end>(",", "");
}
if (cellVal instanceof JSONObject<method*start>com.alibaba.fastjson.JSONObject<method*end>) {
cellVal = ((JSONObject<method*start>com.alibaba.fastjson.JSONObject<method*end>) cellVal).getString<method*start>com.alibaba.fastjson.JSONObject.getString<method*end>("text");
} else
cellVals.add<method*start>java.util.List.add<method*end>(cellVal);
}
into.add<method*start>java.util.List.add<method*end>(cellVals);
}
return into;
} | 肖敬先 | |
Authentication authentication = authenticationManager.authenticate(new PlainTextUsernamePasswordAuthenticationRequest(username, password));
| conventional | @SneakyThrows
protected ResponseMessage<org.hswebframework.web.controller.message.ResponseMessage<Map<String, Object>>> doLogin(String username, String password, Map<String, ?> parameter) {
Assert.hasLength(username, "用户名不能为空");
Assert.hasLength(password, "密码不能为空");
AuthorizationFailedEvent.Reason reason = AuthorizationFailedEvent.Reason.OTHER;
Function<String, Object> parameterGetter = parameter::get;
try {
AuthorizationDecodeEvent decodeEvent = new AuthorizationDecodeEvent(username, password, parameterGetter);
eventPublisher.publishEvent(decodeEvent);
username = decodeEvent.getUsername();
password = decodeEvent.getPassword();
AuthorizationBeforeEvent beforeEvent = new AuthorizationBeforeEvent(username, password, parameterGetter);
eventPublisher.publishEvent(beforeEvent);
// 验证通过
// 触发授权成功事件
AuthorizationSuccessEvent event = new AuthorizationSuccessEvent(authentication, parameterGetter);
event.getResult().put("userId", authentication.getUser().getId());
eventPublisher.publishEvent(event);
return ok(event.getResult());
} catch (Exception e) {
AuthorizationFailedEvent failedEvent = new AuthorizationFailedEvent(username, password, parameterGetter, reason);
failedEvent.setException(e);
eventPublisher.publishEvent(failedEvent);
throw failedEvent.getException();
}
} | 肖敬先 | |
if (currentUser.hasRole<method*start>org.apache.shiro.subject.Subject.hasRole<method*end>("role2")) {
System.out.println<method*start>java.io.PrintStream.println<method*end>("有role2这个角色");
} else {
System.out.println<method*start>java.io.PrintStream.println<method*end>("没有role2这个角色");
} | conventional | @Test
public void hasRoleTest() {
Subject<method*start>org.apache.shiro.subject.Subject<method*end> currentUser = ShiroUtil.login<method*start>authorization.ShiroUtil.login<method*end>("classpath:shiro_role.ini", "jack", "123456");
boolean[] results = currentUser.hasRoles<method*start>org.apache.shiro.subject.Subject.hasRoles<method*end>(Arrays.asList<method*start>java.util.Arrays.asList<method*end>("role1", "role2"));
System.out.println<method*start>java.io.PrintStream.println<method*end>(results[0] ? "有role1这个角色" : "没有role1这个角色");
System.out.println<method*start>java.io.PrintStream.println<method*end>(results[1] ? "有role2这个角色" : "没有role2这个角色");
System.out.println<method*start>java.io.PrintStream.println<method*end>(currentUser.hasAllRoles<method*start>org.apache.shiro.subject.Subject.hasAllRoles<method*end>(Arrays.asList<method*start>java.util.Arrays.asList<method*end>("role1", "role2")) ? "role1,role2这两个角色都有" : "role1,role2这两个角色不全有");
currentUser.logout<method*start>org.apache.shiro.subject.Subject.logout<method*end>();
} | 肖敬先 | |
boolean canGet = EfoApplication.settings.getBooleanUseEval(ConfigConsts.ANONYMOUS_VISIBLE_OF_SETTING) || (Checker.isNotNull(user) && user.getIsVisible() == 1);
if (canGet){
} else {
jsonObject.put("error", "权限被限制,无法获取资源,请联系管理员");
return jsonObject.toString();
} | conventional | @ApiOperation(value = "获取文件记录")
@ApiImplicitParams({ @ApiImplicitParam(name = "offset", value = "偏移量", required = true), @ApiImplicitParam(name = "categoryId", value = "分类ID", required = true), @ApiImplicitParam(name = "orderBy", value = "排序方式", required = true, example = "id desc"), @ApiImplicitParam(name = "search", value = "记录匹配(允许为空)") })
@RequestMapping(value = "/all", method = RequestMethod.GET)
public String getAll(int offset, int categoryId, String orderBy, String search) {
User user = (User) request.getSession().getAttribute(ValueConsts.USER_STRING);
{
int userId = Checker.isNull(user) ? 0 : user.getId();
return Formatter.listToJson(fileService.listAll(userId, offset, categoryId, orderBy, search));
} | 肖敬先 | |
if (authorization == null || "".equals<method*start>java.lang.String.equals<method*end>(authorization.trim<method*start>java.lang.String.trim<method*end>())) {
throw RequestException.fail<method*start>cn.licoy.wdog.common.exception.RequestException.fail<method*end>("未含授权标示,禁止访问");
}
if (e.getMessage<method*start>org.apache.shiro.authc.DisabledAccountException.getMessage<method*end>().equals<method*start>java.lang.String.equals<method*end>("verifyFail")) {
throw new RequestException(ResponseCode.NOT_SING_IN.code<method*start>cn.licoy.wdog.common.bean.ResponseCode.code<method*end>, "身份已过期,请重新登录", e);
} | conventional | public static boolean executeLogin(ServletRequest<method*start>javax.servlet.ServletRequest<method*end> request) {
HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> httpServletRequest = (HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end>) request;
String<method*start>java.lang.String<method*end> authorization = httpServletRequest.getHeader<method*start>javax.servlet.http.HttpServletRequest.getHeader<method*end>("Authorization");
JwtToken<method*start>cn.licoy.wdog.core.config.jwt.JwtToken<method*end> token = new JwtToken<method*start>cn.licoy.wdog.core.config.jwt.JwtToken<method*end>(authorization, null, null);
// 提交给realm进行登入,如果错误他会抛出异常并被捕获
Subject<method*start>org.apache.shiro.subject.Subject<method*end> subject = SecurityUtils.getSubject<method*start>org.apache.shiro.SecurityUtils.getSubject<method*end>();
try {
subject.login<method*start>org.apache.shiro.subject.Subject.login<method*end>(token);
} catch (DisabledAccountException<method*start>org.apache.shiro.authc.DisabledAccountException<method*end> e) {
throw new RequestException(ResponseCode.SIGN_IN_INPUT_FAIL.code<method*start>cn.licoy.wdog.common.bean.ResponseCode.code<method*end>, e.getMessage<method*start>org.apache.shiro.authc.DisabledAccountException.getMessage<method*end>(), e);
} catch (Exception<method*start>java.lang.Exception<method*end> e) {
e.printStackTrace<method*start>java.lang.Exception.printStackTrace<method*end>();
throw new RequestException(ResponseCode.SIGN_IN_FAIL<method*start>cn.licoy.wdog.common.bean.ResponseCode.SIGN_IN_FAIL<method*end>, e);
}
// 如果没有抛出异常则代表登入成功,返回true
return true;
} | 肖敬先 | |
if (user != null || (menu != null && menu.access()) || handlerMethod.getBean() instanceof BasicErrorController) {
filter = true;
if (user != null && StringUtils.isNotBlank(user.getId())) {
getUserProxy().attachOrgansPropertiesForUser(user);
getUserProxy().attachRolesMap(user);
request.getSession(true).setAttribute(Constants.USER_SESSION_NAME, user);
}
} | conventional | @Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, Object handler) throws Exception {
boolean filter = false;
User user = (User) request.getSession(true).getAttribute(Constants.USER_SESSION_NAME);
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Menu menu = handlerMethod.getMethod().getAnnotation(Menu.class);
if (!filter) {
if (StringUtils.isNotBlank(request.getParameter("msg"))) {
response.sendRedirect("/login.html?msg=" + request.getParameter("msg"));
} else {
response.sendRedirect("/login.html");
}
}
} else {
filter = true;
}
return filter;
} | 肖敬先 | |
if (oConvertUtils.isEmpty(token)) {
return Result.error("退出登录失败!");
} | conventional | @RequestMapping(value = "/logout")
public Result logout(HttpServletRequest request, HttpServletResponse response) {
// 用户退出逻辑
String token = request.getHeader(DefContants.X_ACCESS_TOKEN);
String username = JwtUtil.getUsername(token);
LoginUser sysUser = sysBaseAPI.getUserByName(username);
if (sysUser != null) {
sysBaseAPI.addLog("用户名: " + sysUser.getRealname() + ",退出成功!", CommonConstant.LOG_TYPE_1, null);
log.info(" 用户名: " + sysUser.getRealname() + ",退出成功! ");
// 清空用户登录Token缓存
redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
// 清空用户登录Shiro权限缓存
redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
// 清空用户的缓存信息(包括部门信息),例如sys:cache:user::<username>
redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, sysUser.getUsername()));
// 调用shiro的logout
SecurityUtils.getSubject().logout();
return Result.ok("退出登录成功!");
} else {
return Result.error("Token无效!");
}
} | 肖敬先 | |
if (interfaceRuleDto == null) {
return Result.error<method*start>org.jeecgframework.jwt.util.Result.error<method*end>("您没有该接口的权限!");
} | conventional | @RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>(method<method*start>org.springframework.web.bind.annotation.RequestMapping.method<method*end> = RequestMethod.PUT<method*start>org.springframework.web.bind.annotation.RequestMethod.PUT<method*end>, consumes<method*start>org.springframework.web.bind.annotation.RequestMapping.consumes<method*end> = MediaType.APPLICATION_JSON_VALUE<method*start>org.springframework.http.MediaType.APPLICATION_JSON_VALUE<method*end>)
@ResponseBody
@ApiOperation<method*start>io.swagger.annotations.ApiOperation<method*end>(value<method*start>io.swagger.annotations.Api.value<method*end> = "更新jeecgDemo", notes<method*start>io.swagger.annotations.ApiOperation.notes<method*end> = "更新jeecgDemo")
public ResponseMessage<method*start>org.jeecgframework.jwt.util.ResponseMessage<method*end><?> update(@RequestBody JeecgDemoEntity jeecgDemo, HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request) {
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.jeecgdemo_edit<method*start>org.jeecgframework.web.system.enums.InterfaceEnum.jeecgdemo_edit<method*end>);
if (interfaceRuleDto == null) {
return Result.error<method*start>org.jeecgframework.jwt.util.Result.error<method*end>("您没有该接口的权限!");
}
logger.info<method*start>org.slf4j.Logger.info<method*end>("update[{}]", GsonUtil.toJson<method*start>org.jeecgframework.jwt.util.GsonUtil.toJson<method*end>(jeecgDemo));
// 调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息.
Set<method*start>java.util.Set<method*end><ConstraintViolation<method*start>javax.validation.ConstraintViolation<method*end><JeecgDemoEntity>> failures = validator.validate<method*start>javax.validation.Validator.validate<method*end>(jeecgDemo);
if (!failures.isEmpty<method*start>java.util.Set.isEmpty<method*end>()) {
return Result.error<method*start>org.jeecgframework.jwt.util.Result.error<method*end>(JSONArray.toJSONString<method*start>com.alibaba.fastjson.JSONArray.toJSONString<method*end>(BeanValidators.extractPropertyAndMessage<method*start>org.jeecgframework.core.beanvalidator.BeanValidators.extractPropertyAndMessage<method*end>(failures)));
}
// 保存
try {
this.jeecgDemoService.saveOrUpdate<method*start>com.jeecg.demo.service.JeecgDemoServiceI.saveOrUpdate<method*end>(jeecgDemo);
} catch (Exception<method*start>java.lang.Exception<method*end> e) {
e.printStackTrace<method*start>java.lang.Exception.printStackTrace<method*end>();
return Result.error<method*start>org.jeecgframework.jwt.util.Result.error<method*end>("更新jeecgDemo信息失败");
}
// 按Restful约定,返回204状态码, 无内容. 也可以返回200状态码.
return Result.success<method*start>org.jeecgframework.jwt.util.Result.success<method*end>("更新jeecgDemo信息成功");
} | 肖敬先 | |
// 判断账号是否超过停用时间
if (StrUtil.isNotBlank<method*start>com.xiaoleilu.hutool.util.StrUtil.isNotBlank<method*end>(user.getEndTime<method*start>org.superboot.entity.jpa.SuperbootUser.getEndTime<method*end>())) {
long num = DateUtils.getSecondDiffer<method*start>org.superboot.utils.DateUtils.getSecondDiffer<method*end>(DateUtils.getCurrentDateTime<method*start>org.superboot.utils.DateUtils.getCurrentDateTime<method*end>(), user.getEndTime<method*start>org.superboot.entity.jpa.SuperbootUser.getEndTime<method*end>());
if (0 < num) {
throw new BaseException<method*start>org.superboot.base.BaseException<method*end>(StatusCode.ACCOUNT_EXPIRED<method*start>org.superboot.base.StatusCode.ACCOUNT_EXPIRED<method*end>);
}
}
// 数据封存
if (BaseConstants.DATA_STATUS_CLOSE<method*start>org.superboot.base.BaseConstants.DATA_STATUS_CLOSE<method*end> == user.getDr<method*start>org.superboot.entity.jpa.SuperbootUser.getDr<method*end>()) {
throw new BaseException<method*start>org.superboot.base.BaseException<method*end>(StatusCode.ACCOUNT_DISABLED<method*start>org.superboot.base.StatusCode.ACCOUNT_DISABLED<method*end>);
}
// 账户锁定
if (1 == user.getUserStatus<method*start>org.superboot.entity.jpa.SuperbootUser.getUserStatus<method*end>()) {
throw new BaseException<method*start>org.superboot.base.BaseException<method*end>(StatusCode.ACCOUNT_LOCKED<method*start>org.superboot.base.StatusCode.ACCOUNT_LOCKED<method*end>);
}
// 验证密码
if (!user.getUserPassword<method*start>org.superboot.entity.jpa.SuperbootUser.getUserPassword<method*end>().equals<method*start>java.lang.String.equals<method*end>(genPassWord(loginUser.getUserPassword<method*start>org.superboot.entity.request.LoginUser.getUserPassword<method*end>(), user.getEnKey<method*start>org.superboot.entity.jpa.SuperbootUser.getEnKey<method*end>()))) {
throw new BaseException<method*start>org.superboot.base.BaseException<method*end>(StatusCode.PASSWORD_ERROR<method*start>org.superboot.base.StatusCode.PASSWORD_ERROR<method*end>);
} | conventional | @Override
public BaseResponse<method*start>org.superboot.base.BaseResponse<method*end> login(LoginUser<method*start>org.superboot.entity.request.LoginUser<method*end> loginUser) throws BaseException<method*start>org.superboot.base.BaseException<method*end> {
String<method*start>java.lang.String<method*end> usercode = loginUser.getUserCode<method*start>org.superboot.entity.request.LoginUser.getUserCode<method*end>();
if (null == usercode) {
throw new BaseException<method*start>org.superboot.base.BaseException<method*end>(StatusCode.USERNAME_NOT_FIND<method*start>org.superboot.base.StatusCode.USERNAME_NOT_FIND<method*end>);
}
String<method*start>java.lang.String<method*end> rawPassword = loginUser.getUserPassword<method*start>org.superboot.entity.request.LoginUser.getUserPassword<method*end>();
if (null == rawPassword) {
throw new BaseException<method*start>org.superboot.base.BaseException<method*end>(StatusCode.PASSWORD_NOT_FIND<method*start>org.superboot.base.StatusCode.PASSWORD_NOT_FIND<method*end>);
}
// 使用DSL语法
QSuperbootUser<method*start>org.superboot.entity.jpa.QSuperbootUser<method*end> qSuperbootUser = QSuperbootUser.superbootUser<method*start>QSuperbootUser.superbootUser<method*end>;
SuperbootUser<method*start>org.superboot.entity.jpa.SuperbootUser<method*end> user = getQueryFactory<method*start>org.superboot.base.BaseService.getQueryFactory<method*end>().selectFrom<method*start>com.querydsl.jpa.impl.JPAQueryFactory.selectFrom<method*end>(qSuperbootUser).where(qSuperbootUser.userCode<method*start>QSuperbootUser.userCode<method*end>.eq(usercode)).fetchOne();
// 数据不存在或者数据删除
if (null == user || BaseConstants.DATA_STATUS_DEL<method*start>org.superboot.base.BaseConstants.DATA_STATUS_DEL<method*end> == user.getDr<method*start>org.superboot.entity.jpa.SuperbootUser.getDr<method*end>()) {
throw new BaseException<method*start>org.superboot.base.BaseException<method*end>(StatusCode.ACCOUNT_NOT_FIND<method*start>org.superboot.base.StatusCode.ACCOUNT_NOT_FIND<method*end>);
}
// 刷新用户的权限信息
authUtils.reloadByPkUser<method*start>org.superboot.common.pub.Pub_AuthUtils.reloadByPkUser<method*end>(user.getPkUser<method*start>org.superboot.entity.jpa.SuperbootUser.getPkUser<method*end>());
return new BaseResponse<method*start>org.superboot.base.BaseResponse<method*end>(setBaseTokenBySuperbootUser<method*start>org.superboot.service.impl.UserServiceImpl.setBaseTokenBySuperbootUser<method*end>(user));
} | 肖敬先 | |
@RequiresPermissions("oss:pdf:upload") | annotation | @ApiOperation(value = "文件上传", notes = "权限编码(oss:pdf:upload)")
@PostMapping("/upload")
public JsonResponse upload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
if (file.isEmpty()) {
return JsonResponse.error("上传文件不能为空");
} else if (file.getOriginalFilename().endsWith("doc") || file.getOriginalFilename().endsWith("docx") || file.getOriginalFilename().endsWith("xls") || file.getOriginalFilename().endsWith("xlsx") || file.getOriginalFilename().endsWith("ppt") || file.getOriginalFilename().endsWith("pptx") || file.getOriginalFilename().endsWith("png") || file.getOriginalFilename().endsWith("svg") || file.getOriginalFilename().endsWith("rtf")) {
} else {
return JsonResponse.error("只支持office或png格式!");
}
String dest = IoUtil.getFile("gen").getPath() + File.separator + file.getOriginalFilename();
IoUtil.writeByteToFile(file.getBytes(), dest);
HashMap<Object, Object> map = new HashMap<>();
map.put("filePath", dest);
queue.offer(map, 2, TimeUnit.SECONDS);
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(new Consumer(file, dest));
return JsonResponse.success();
} | 肖敬先 | |
if (StringUtil.isBlank(openId) || "undefined".equals(openId)) {
retData.setCode(ResultCodeMessage.PARMS_ERROR);
retData.setMessage("未授权,请退出再试");
return retData;
} | conventional | @RequestMapping("getMeeting")
public RetData<com.cn.xmf.base.model.RetData> getMeeting(HttpServletRequest request) {
RetData<com.cn.xmf.base.model.RetData> retData = new RetData<com.cn.xmf.base.model.RetData>();
Meeting retmeeting = null;
String openId = request.getParameter("openId");
String key = ConstantUtil.CACHE_SYS_BASE_DATA_ + "meeting_" + openId;
String cache = sysCommonService.getCache(key);
if (StringUtil.isNotBlank(cache)) {
retmeeting = JSONObject.parseObject(cache, Meeting.class);
}
if (retmeeting != null) {
retData.setData(retmeeting);
retData.setCode(ResultCodeMessage.SUCCESS);
retData.setMessage(ResultCodeMessage.SUCCESS_MESSAGE);
return retData;
}
String userName = request.getParameter("userName");
String phone = request.getParameter("phone");
Meeting meeting = new Meeting();
meeting.setUserName(userName);
meeting.setPhone(phone);
meeting.setOpenId(openId);
logger.info("getMeeting:(查询参会人员信息登记单条数据接口) 开始 meeting={}", meeting);
retmeeting = meetingService.getMeeting(meeting);
if (retmeeting != null) {
sysCommonService.save(key, JSON.toJSONString(retmeeting), 60 * 5);
}
retData.setData(retmeeting);
retData.setCode(ResultCodeMessage.SUCCESS);
retData.setMessage(ResultCodeMessage.SUCCESS_MESSAGE);
logger.info("getMeeting:(查询参会人员信息登记单条数据接口) 结束");
return retData;
} | 肖敬先 | |
UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Message message = new Message();
if (!userInfo.getAuthorities().toString().contains("ROLE_ADMIN")) {
message.setResult("权限错误!");
message.setMessageInfo("只有管理员才可以添加管理员!");
return message;
} | conventional | @RequestMapping(value = { "/admin/add-admin" }, method = RequestMethod.POST)
@ResponseBody
public Message addUser(@RequestBody User user) {
UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Message message = new Message();
user.setCreateTime(new Date());
String password = user.getPassword() + "{" + user.getUserName().toLowerCase() + "}";
PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
String resultPassword = passwordEncoder.encode(password);
user.setPassword(resultPassword);
user.setEnabled(true);
user.setCreateBy(userInfo.getUserid());
user.setUserName(user.getUserName().toLowerCase());
try {
userService.addUser(user, "ROLE_ADMIN", -1, userInfo.getRoleMap());
} catch (Exception e) {
if (e.getMessage().contains(user.getUserName())) {
message.setResult("duplicate-username");
message.setMessageInfo("重复的用户名");
} else if (e.getMessage().contains(user.getNationalId())) {
message.setResult("duplicate-national-id");
message.setMessageInfo("重复的身份证");
} else if (e.getMessage().contains(user.getEmail())) {
message.setResult("duplicate-email");
message.setMessageInfo("重复的邮箱");
} else if (e.getMessage().contains(user.getPhoneNum())) {
message.setResult("duplicate-phone");
message.setMessageInfo("重复的电话");
} else {
message.setResult(e.getCause().getMessage());
e.printStackTrace();
}
}
return message;
} | 肖敬先 | |
if (user == null || !Application.getSecurityManager<method*start>com.rebuild.server.Application.getSecurityManager<method*end>().allowRead<method*start>com.rebuild.server.service.bizz.privileges.SecurityManager.allowRead<method*end>(user, entity.getEntityCode<method*start>cn.devezhao.persist4j.Entity.getEntityCode<method*end>())) {
throw new ChartsException<method*start>com.rebuild.server.business.charts.ChartsException<method*end>("没有读取 [" + EasyMeta.getLabel<method*start>com.rebuild.server.metadata.entity.EasyMeta.getLabel<method*end>(entity) + "] 的权限");
}
String<method*start>java.lang.String<method*end> type = config.getString<method*start>com.alibaba.fastjson.JSONObject.getString<method*end>("type");
if ("INDEX".equalsIgnoreCase<method*start>java.lang.String.equalsIgnoreCase<method*end>(type)) { | conventional | public static ChartData<method*start>com.rebuild.server.business.charts.ChartData<method*end> create(JSONObject<method*start>com.alibaba.fastjson.JSONObject<method*end> config, ID<method*start>cn.devezhao.persist4j.engine.ID<method*end> user) throws ChartsException<method*start>com.rebuild.server.business.charts.ChartsException<method*end> {
String<method*start>java.lang.String<method*end> e = config.getString<method*start>com.alibaba.fastjson.JSONObject.getString<method*end>("entity");
if (!MetadataHelper.containsEntity<method*start>com.rebuild.server.metadata.MetadataHelper.containsEntity<method*end>(e)) {
throw new ChartsException<method*start>com.rebuild.server.business.charts.ChartsException<method*end>("源实体 [" + e + "] 不存在");
}
Entity<method*start>cn.devezhao.persist4j.Entity<method*end> entity = MetadataHelper.getEntity<method*start>com.rebuild.server.metadata.MetadataHelper.getEntity<method*end>(e); | 肖敬先 | |
boolean isok = user_serv.canFindPass(u, key);
if (null == vcode || vcode.isEmpty()) {
// 点邮件过来或者直接非法访问的
if (isok) {
mav.addObject("key", key);
mav.addObject("u", u);
} else {
rep.sendError(500, msg_50X);
} | conventional | @RequestMapping("/findpass.do")
public ModelAndView findpass(HttpServletRequest req, HttpServletResponse rep, String u, String key, String vcode, String password1, String password2, RedirectAttributes attr) {
ModelAndView mav = new ModelAndView("/admin/pub/findpass");
String msg_50X = "授权码过期或者非法操作!";
try {
{
// 提交过来的
if (null == vcode || !vcode.equals(req.getSession().getAttribute("vcode"))) {
mav.addObject("msg", "验证码错误");
} else if (!isok) {
mav.addObject("msg", msg_50X);
} else if (!password1.equals(password2)) {
mav.addObject("msg", "两次密码不一致!");
} else {
UserVo vo = user_serv.resetPass(password1, u);
user_serv.userLogin(vo.getUserName(), vo.getUserPsw(), false, req, rep);
rep.sendRedirect(String.format("http://%s/admin/main.do", user_serv.getHost()));
}
}
} catch (Exception e) {
e.printStackTrace();
mav.addObject("msg", "系统出错!");
log.error("找回密码", e);
}
return mav;
} | 肖敬先 | |
// 如果存在安全管理器,则需要检查删除权限
file.checkDelete(); | conventional | @Override
boolean implDelete(Path path, boolean failIfNotExists) throws IOException {
// 将Path强制转换为WindowsPath
WindowsPath file = WindowsPath.toWindowsPath(path);
WindowsFileAttributes attrs = null;
try {
attrs = WindowsFileAttributes.get(file, false);
if (attrs.isDirectory() || attrs.isDirectoryLink()) {
RemoveDirectory(file.getPathForWin32Calls());
} else {
DeleteFile(file.getPathForWin32Calls());
}
return true;
} catch (WindowsException x) {
if (!failIfNotExists && (x.lastError() == ERROR_FILE_NOT_FOUND || x.lastError() == ERROR_PATH_NOT_FOUND)) {
return false;
}
if (attrs != null && attrs.isDirectory()) {
if (x.lastError() == ERROR_DIR_NOT_EMPTY || x.lastError() == ERROR_ALREADY_EXISTS) {
throw new DirectoryNotEmptyException(file.getPathForExceptionMessage());
}
}
x.rethrowAsIOException(file);
return false;
}
} | 肖敬先 | |
if (!hasBizPermission(request, apiDataType.getBizId<method*start>com.xxl.api.admin.core.model.XxlApiDataType.getBizId<method*end>())) {
return new ReturnT<method*start>com.xxl.api.admin.core.model.ReturnT<method*end><String<method*start>java.lang.String<method*end>>(ReturnT.FAIL_CODE<method*start>com.xxl.api.admin.core.model.ReturnT.FAIL_CODE<method*end>, "您没有相关业务线的权限,请联系管理员开通");
} | conventional | @RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>("/deleteDataType")
@ResponseBody<method*start>org.springframework.web.bind.annotation.ResponseBody<method*end>
public ReturnT<method*start>com.xxl.api.admin.core.model.ReturnT<method*end><String<method*start>java.lang.String<method*end>> deleteDataType(HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request, int id) {
XxlApiDataType<method*start>com.xxl.api.admin.core.model.XxlApiDataType<method*end> apiDataType = xxlApiDataTypeDao.load<method*start>com.xxl.api.admin.dao.IXxlApiDataTypeDao.load<method*end>(id);
if (apiDataType == null) {
return new ReturnT<method*start>com.xxl.api.admin.core.model.ReturnT<method*end><String<method*start>java.lang.String<method*end>>(ReturnT.FAIL_CODE<method*start>com.xxl.api.admin.core.model.ReturnT.FAIL_CODE<method*end>, "数据类型ID非法");
}
// 被其他数据类型引用,拒绝删除
List<method*start>java.util.List<method*end><XxlApiDataTypeField<method*start>com.xxl.api.admin.core.model.XxlApiDataTypeField<method*end>> list = xxlApiDataTypeFieldDao.findByFieldDatatypeId<method*start>com.xxl.api.admin.dao.IXxlApiDataTypeFieldDao.findByFieldDatatypeId<method*end>(id);
if (list != null && list.size<method*start>java.util.List.size<method*end>() > 0) {
return new ReturnT<method*start>com.xxl.api.admin.core.model.ReturnT<method*end><String<method*start>java.lang.String<method*end>>(ReturnT.FAIL_CODE<method*start>com.xxl.api.admin.core.model.ReturnT.FAIL_CODE<method*end>, "该数据类型被引用中,拒绝删除");
}
// 该数据类型被API引用,拒绝删除
List<method*start>java.util.List<method*end><XxlApiDocument<method*start>com.xxl.api.admin.core.model.XxlApiDocument<method*end>> apiList = xxlApiDocumentDao.findByResponseDataTypeId<method*start>com.xxl.api.admin.dao.IXxlApiDocumentDao.findByResponseDataTypeId<method*end>(id);
if (apiList != null && apiList.size<method*start>java.util.List.size<method*end>() > 0) {
return new ReturnT<method*start>com.xxl.api.admin.core.model.ReturnT<method*end><String<method*start>java.lang.String<method*end>>(ReturnT.FAIL_CODE<method*start>com.xxl.api.admin.core.model.ReturnT.FAIL_CODE<method*end>, "该数据类型被API引用,拒绝删除");
}
// delete
int ret = xxlApiDataTypeDao.delete<method*start>com.xxl.api.admin.dao.IXxlApiDataTypeDao.delete<method*end>(id);
xxlApiDataTypeFieldDao.deleteByParentDatatypeId<method*start>com.xxl.api.admin.dao.IXxlApiDataTypeFieldDao.deleteByParentDatatypeId<method*end>(id);
return ret > 0 ? ReturnT.SUCCESS<method*start>com.xxl.api.admin.core.model.ReturnT.SUCCESS<method*end> : ReturnT.FAIL<method*start>com.xxl.api.admin.core.model.ReturnT.FAIL<method*end>;
} | 肖敬先 | |
if (!isValidApp(request)) {
return renderInvalidApp(response);
} | conventional | @RequestMapping(value = "/register-step1-post")
public String registerStep1(HttpServletRequest request, HttpServletResponse response) {
boolean result;
String message;
Map<String, Object> data = Maps.newHashMap();
String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
data.put("userLoginName", username);
if (ValidateUtils.isMobile(username)) {
result = true;
message = "";
} else {
result = false;
message = ValidateUtils.getErrMsg();
}
User user = userService.getByLoginName2(username);
if (user != null && StringUtils.isNotBlank(user.getId())) {
result = false;
message = "电话号码已存在";
} else {
// 发送手机验证码
SmsUtils.sendRegisterCode(username);
}
return renderString(response, result, message, data);
} | 肖敬先 | |
@RequiresPermissions("sys:user:edit")
if (Global.isDemoMode()) {
addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/user/list?repage";
} | annotation | @RequestMapping(value = "save")
public String save(User user, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
// 修正引用赋值问题,不知道为何,Company和Office引用的一个实例地址,修改了一个,另外一个跟着修改。
user.setCompany(new Office(request.getParameter("company.id")));
user.setOffice(new Office(request.getParameter("office.id")));
// 如果新密码为空,则不更换密码
if (StringUtils.isNotBlank(user.getNewPassword())) {
user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
}
if (!beanValidator(model, user)) {
return form(user, model);
}
if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))) {
addMessage(model, "保存用户'" + user.getLoginName() + "'失败,登录名已存在");
return form(user, model);
}
// 角色数据有效性验证,过滤不在授权内的角色
List<Role> roleList = Lists.newArrayList();
List<String> roleIdList = user.getRoleIdList();
for (Role r : systemService.findAllRole()) {
if (roleIdList.contains(r.getId())) {
roleList.add(r);
}
}
user.setRoleList(roleList);
// 保存用户信息
systemService.saveUser(user);
// 清除当前用户缓存
if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
UserUtils.clearCache();
// UserUtils.getCacheMap().clear();
}
addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");
return "redirect:" + adminPath + "/sys/user/list?repage";
} | 肖敬先 | |
@Validated(UserLoginValidGroup.class)
if (userDtoTemp == null) {
throw new CustomUnauthorizedException("该帐号不存在(The account does not exist.)");
} | annotation | @PostMapping("/login")
public ResponseBean login(@Validated(UserLoginValidGroup.class) @RequestBody UserDto userDto, HttpServletResponse httpServletResponse) {
UserDto userDtoTemp = new UserDto();
userDtoTemp.setAccount(userDto.getAccount());
userDtoTemp = userService.selectOne(userDtoTemp);
String key = AesCipherUtil.deCrypto(userDtoTemp.getPassword());
if (key.equals(userDto.getAccount() + userDto.getPassword())) {
if (JedisUtil.exists(Constant.PREFIX_SHIRO_CACHE + userDto.getAccount())) {
JedisUtil.delKey(Constant.PREFIX_SHIRO_CACHE + userDto.getAccount());
}
String currentTimeMillis = String.valueOf(System.currentTimeMillis());
JedisUtil.setObject(Constant.PREFIX_SHIRO_REFRESH_TOKEN + userDto.getAccount(), currentTimeMillis, Integer.parseInt(refreshTokenExpireTime));
String token = JwtUtil.sign(userDto.getAccount(), currentTimeMillis);
httpServletResponse.setHeader("Authorization", token);
httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
return new ResponseBean(HttpStatus.OK.value(), "登录成功(Login Success.)", null);
} else {
throw new CustomUnauthorizedException("帐号或密码错误(Account or Password Error.)");
}
} | 肖敬先 | |
// 防止横向越权
shipping.setUserId<method*start>com.kay.pojo.Shipping.setUserId<method*end>(userId);
int count = shippingMapper.updateByIdAndUserId<method*start>com.kay.dao.ShippingMapper.updateByIdAndUserId<method*end>(shipping);
if (count > 0) {
return ServerResponse.createBySuccessMessage<method*start>com.kay.common.ServerResponse.createBySuccessMessage<method*end>("更新地址成功");
} | conventional | @Override
public ServerResponse<method*start>com.kay.common.ServerResponse<method*end> update(Integer<method*start>java.lang.Integer<method*end> userId, Shipping<method*start>com.kay.pojo.Shipping<method*end> shipping) {
if (shipping == null) {
return ServerResponse.createByErrorCodeMessage<method*start>com.kay.common.ServerResponse.createByErrorCodeMessage<method*end>(ResponseCode.ILLEGAL_ARGUMENT.getCode<method*start>com.kay.common.ResponseCode.getCode<method*end>(), ResponseCode.ILLEGAL_ARGUMENT.getDescription<method*start>com.kay.common.ResponseCode.getDescription<method*end>());
}
shipping.setUserId<method*start>com.kay.pojo.Shipping.setUserId<method*end>(userId);
int count = shippingMapper.updateByIdAndUserId<method*start>com.kay.dao.ShippingMapper.updateByIdAndUserId<method*end>(shipping);
if (count > 0) {
return ServerResponse.createBySuccessMessage<method*start>com.kay.common.ServerResponse.createBySuccessMessage<method*end>("更新地址成功");
}
return ServerResponse.createByErrorMessage<method*start>com.kay.common.ServerResponse.createByErrorMessage<method*end>("更新地址失败");
} | 肖敬先 | |
checkRole(user); | conventional | @Override
@Transactional
public void updateUserRole(SysUser user) {
if (StringUtils.isBlank(user.getPassword())) {
user.setPassword(null);
} else {
user.setPassword(passwordEncoder.encode(user.getPassword()));
}
baseMapper.updateById(user);
sysUserRoleMapper.delete(Wrappers.<SysUserRole>update().lambda().eq(SysUserRole::getUserId, user.getUserId()));
saveUserRoleList(user);
} | 肖敬先 | |
// 防止横向越权,要校验用户的旧密码
int resCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
if (resCount == 0) {
return ServerResponse.createByError("旧密码错误");
} | conventional | @Override
public ServerResponse<String> resetPassword(String passwordNew, String passwordOld, User user) {
user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
int updateCount = userMapper.updateByPrimaryKeySelective(user);
if (updateCount > 0) {
return ServerResponse.createBySuccessMessage("密码更新成功");
} else {
return ServerResponse.createByError("密码更新失败");
}
} | 肖敬先 | |
if (loginUser.isCanWriteUser()) {
logger.info("用户{}更新用户权限,用户名:{}", loginUser.getUsername(), user.getUsername());
userService.updateUserPermissionByUsername(user);
} else {
logger.error("根据用户名更新用户权限错误,用户{}没有权限", loginUser.getUsername());
responseVo.setStatus(false);
responseVo.setMessage("根据用户名更新用户权限错误,没有权限");
} | conventional | @RequestMapping(value = { "/updateUserPermissionByUsername" })
@ResponseBody
public ResponseVo<String> updateUserPermissionByUsername(HttpServletRequest request, @RequestBody UserPo user) {
ResponseVo<String> responseVo = new ResponseVo<>();
try {
UserPo loginUser = (UserPo) request.getSession().getAttribute(RtConstant.KEY_USER_PO);
} catch (Exception e) {
logger.error("根据用户名更新用户权限错误", e);
responseVo.setStatus(false);
responseVo.setMessage(e.getMessage());
}
return responseVo;
} | 肖敬先 | |
// 是否有某个权限
currentUser.checkRole<method*start>org.apache.shiro.subject.Subject.checkRole<method*end>("role1");
// 是否有某些权限,集合
currentUser.checkRoles<method*start>org.apache.shiro.subject.Subject.checkRoles<method*end>(Arrays.asList<method*start>java.util.Arrays.asList<method*end>("role1", "role2"));
// 是否有某些权限,多参数
currentUser.checkRoles<method*start>org.apache.shiro.subject.Subject.checkRoles<method*end>("role1", "role2", "role3"); | conventional | @Test
public void testCheckRole() {
Subject<method*start>org.apache.shiro.subject.Subject<method*end> currentUser = ShiroUtil.login<method*start>authorization.ShiroUtil.login<method*end>("classpath:shiro_role.ini", "java1234", "123456");
currentUser.logout<method*start>org.apache.shiro.subject.Subject.logout<method*end>();
} | 肖敬先 | |
// 防止横向越权,要校验一下这个用户的旧密码,一定要指定是这个用户.因为我们会查询一个count(1),如果不指定id,那么结果就是true啦count>0;
int resultCount = userMapper.checkPassword<method*start>com.mmall.dao.UserMapper.checkPassword<method*end>(MD5Util.MD5EncodeUtf8<method*start>com.mmall.util.MD5Util.MD5EncodeUtf8<method*end>(passwordOld), user.getId<method*start>com.mmall.pojo.User.getId<method*end>());
if (resultCount == 0) {
return ServerResponse.createByErrorMessage<method*start>com.mmall.common.ServerResponse.createByErrorMessage<method*end>("旧密码错误");
} | conventional | public ServerResponse<method*start>com.mmall.common.ServerResponse<method*end><String<method*start>java.lang.String<method*end>> resetPassword(String<method*start>java.lang.String<method*end> passwordOld, String<method*start>java.lang.String<method*end> passwordNew, User<method*start>com.mmall.pojo.User<method*end> user) {
int resultCount = userMapper.checkPassword<method*start>com.mmall.dao.UserMapper.checkPassword<method*end>(MD5Util.MD5EncodeUtf8<method*start>com.mmall.util.MD5Util.MD5EncodeUtf8<method*end>(passwordOld), user.getId<method*start>com.mmall.pojo.User.getId<method*end>());
if (resultCount == 0) {
return ServerResponse.createByErrorMessage<method*start>com.mmall.common.ServerResponse.createByErrorMessage<method*end>("旧密码错误");
}
user.setPassword<method*start>com.mmall.pojo.User.setPassword<method*end>(MD5Util.MD5EncodeUtf8<method*start>com.mmall.util.MD5Util.MD5EncodeUtf8<method*end>(passwordNew));
int updateCount = userMapper.updateByPrimaryKeySelective<method*start>com.mmall.dao.UserMapper.updateByPrimaryKeySelective<method*end>(user);
if (updateCount > 0) {
return ServerResponse.createBySuccessMessage<method*start>com.mmall.common.ServerResponse.createBySuccessMessage<method*end>("密码更新成功");
}
return ServerResponse.createByErrorMessage<method*start>com.mmall.common.ServerResponse.createByErrorMessage<method*end>("密码更新失败");
} | 肖敬先 | |
if (handleEvent<method*start>org.hswebframework.web.authorization.basic.handler.DefaultAuthorizingHandler.handleEvent<method*end>(context, HandleType.RBAC<method*start>org.hswebframework.web.authorization.define.HandleType.RBAC<method*end>)) {
return;
} | conventional | @Override
public void handRBAC(AuthorizingContext<method*start>org.hswebframework.web.authorization.define.AuthorizingContext<method*end> context) {
// 进行rdac权限控制
handleRBAC<method*start>org.hswebframework.web.authorization.basic.handler.DefaultAuthorizingHandler.handleRBAC<method*end>(context.getAuthentication<method*start>org.hswebframework.web.authorization.define.AuthorizingContext.getAuthentication<method*end>(), context.getDefinition<method*start>org.hswebframework.web.authorization.define.AuthorizingContext.getDefinition<method*end>());
// 表达式权限控制
handleExpression<method*start>org.hswebframework.web.authorization.basic.handler.DefaultAuthorizingHandler.handleExpression<method*end>(context.getAuthentication<method*start>org.hswebframework.web.authorization.define.AuthorizingContext.getAuthentication<method*end>(), context.getDefinition<method*start>org.hswebframework.web.authorization.define.AuthorizingContext.getDefinition<method*end>(), context.getParamContext<method*start>org.hswebframework.web.authorization.define.AuthorizingContext.getParamContext<method*end>());
} | 肖敬先 | |
if (resultCode == Activity.RESULT_OK) {
HMSAgentLog.d("用户已经授权");
SignInResult result = HuaweiId.HuaweiIdApi.getSignInResultFromIntent(data);
if (result == null) {
SignInApi.INST.onSignInActivityResult(HMSAgent.AgentResultCode.RESULT_IS_NULL, null, false);
} else if (result.isSuccess()) {
// 授权成功,result.getSignInHuaweiId()获取华为帐号信息
SignInApi.INST.onSignInActivityResult(result.getStatus().getStatusCode(), result.getSignInHuaweiId(), false);
} else {
// 授权失败,result.getStatus()获取错误原因
HMSAgentLog.e("授权失败 失败原因:" + result.getStatus().toString());
| annotation | @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_SIGN_IN_UNLOGIN || requestCode == REQUEST_SIGN_IN_CHECK_PASSWORD) {
// 当返回值是-1的时候表明用户登录成功,需要CP再次调用signIn
if (resultCode == Activity.RESULT_OK) {
SignInApi.INST.onSignInActivityResult(resultCode, null, true);
} else {
SignInApi.INST.onSignInActivityResult(HMSAgent.AgentResultCode.ON_ACTIVITY_RESULT_ERROR, null, false);
}
finish();
} else if (requestCode == REQUEST_SIGN_IN_AUTH) {
// 当返回值是-1的时候表明用户确认授权,
i SignInApi.INST.onSignInActivityResult(result.getStatus().getStatusCode(), null, false);
}
} else {
// 当resultCode 为0的时候表明用户未授权,则CP可以处理用户未授权事件
HMSAgentLog.e("用户未授权");
SignInApi.INST.onSignInActivityResult(HMSAgent.AgentResultCode.ON_ACTIVITY_RESULT_ERROR, null, false);
}
finish();
}
} | 肖敬先 | |
Boolean status = authService.domainAuth(request, domainId, "w").getStatus();
if (!status) {
response.setStatus(403);
return Hret.error(403, "您没有权限修改域[" + domainId + "]的授权信息", null);
}
| conventional | @RequestMapping(org.springframework.web.bind.annotation.RequestMapping = RequestMethod.PUT)
@Override
protected void updateActivityDomain(int requestCode, int resultCode, Intent data) {
ShareDomainEntity arg = parse(request);
if (arg == null) {
return Hret.error(421, "解析参数失败", null);
}
String domainId = arg.getDomain_id();
int size = shareDomainService.update(arg);
if (size == 1) {
return Hret.success(200, "success", null);
}
response.setStatus(421);
return Hret.error(421, "更新域权限信息失败,请联系管理员", null);
} | 肖敬先 | |
@RequiresPermissions("sys:users:role") | annotation | @ApiOperation(value = "角色授权用户列表", response = Response.class, notes = "权限编码(sys:users:role)")
@GetMapping("/list/{roleId}")
public JsonResponse usersByRole(@PathVariable("roleId") Object roleId, @RequestParam Map<String, Object> params) {
params.put("roleId", roleId.equals("null") == true ? null : roleId);
Query query = new Query(params, SysUser.class);
Page page = null;
page = sysUserService.getPage(query);
return JsonResponse.success(page);
} | 肖敬先 | |
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>()) { | conventional | 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>);
// 0->10000->100000
return iCategoryService.selectCategoryAndChildrenById<method*start>com.mmall.service.ICategoryService.selectCategoryAndChildrenById<method*end>(categoryId); | 肖敬先 | |
if (!UserUtils.getUser().isAdmin() && role.getSysData().equals(Global.YES)) {
addMessage(redirectAttributes, "越权操作,只有超级管理员才能修改此数据!");
return "redirect:" + adminPath + "/sys/role/?repage";
}
| conventional | @RequestMapping(value = "save")
public String save(Role role, Model model, RedirectAttributes redirectAttributes) {
if (Global.isDemoMode()) {
addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/role/?repage";
}
if (!beanValidator(model, role)) {
return form(role, model);
}
if (!"true".equals(checkName(role.getOldName(), role.getName()))) {
addMessage(model, "保存角色'" + role.getName() + "'失败, 角色名已存在");
return form(role, model);
}
if (!"true".equals(checkEnname(role.getOldEnname(), role.getEnname()))) {
addMessage(model, "保存角色'" + role.getName() + "'失败, 英文名已存在");
return form(role, model);
}
systemService.saveRole(role);
addMessage(redirectAttributes, "保存角色'" + role.getName() + "'成功");
return "redirect:" + adminPath + "/sys/role/?repage";
} | 肖敬先 | |
// 拥有的权限
List<java.util.List<String>> perms = getAdmin().getPerms();
boolean hasPerm = false;
// 目标匹配权限
String[] permissions = permission.split(":");
outer: for (String item : perms) {
// 拥有的权限点
String[] hasPer = item.split(":");
inner: for (int i = 0; i < permissions.length; i++) {
if ("*".equals(hasPer[i])) {
hasPerm = true;
break outer;
} else if (hasPer[i].equals(permissions[i])) {
// 此层合格
if (i == permissions.length - 1) {
// 若是目标层的最后一层。则表示所有层校验通过
hasPerm = true;
} | conventional | public static boolean hasPerm(String permission) throws ServiceException {
return hasPerm;
} | 肖敬先 | |
UserDO userDO = userMapper.uuid(sysEnterpriseUserReq.getUuid());
if (null == userDO) {
throw BizException.fail("待授权的用户不存在");
}
| conventional | @Override
public String rolesToUser(SysEnterpriseUserReq sysEnterpriseUserReq) {
UserGroupDO uuid = userGroupMapper.uuid(sysEnterpriseUserReq.getEnterpriseUuid());
if (uuid == null) {
throw BizException.fail("用户所在的企业不存在");
}
List<Long> originAclIdList = authorityMapper.rolesByUserId(userDO.getId());
if (originAclIdList.size() == roles.size()) {
Set<Long> originAclIdSet = Sets.newHashSet(originAclIdList);
Set<Long> aclIdSet = Sets.newHashSet(roles);
originAclIdSet.removeAll(aclIdSet);
if (CollectionUtils.isEmpty(originAclIdSet)) {
return "为企业用户授权角色成功";
}
}
} | 肖敬先 | |
// validation code starts here
if (user == null) {
return;
}
if (!user.isAdmin()) {
return;
}
// validation code ends here | conventional | public class ExampleController {
// function code starts here
System.out.println("This is the function code.");
// function code ends here
} | 肖敬先 | |
if (perms != null && perms.length > 0) {
if (perms.length == 1) {
if (!subject.isPermitted(perms[0])) {
log.debug("授权认证:未通过");
isPermitted = false;
}
} else {
if (!subject.isPermittedAll(perms)) {
log.debug("授权认证:未通过");
isPermitted = false;
}
}
} | conventional | @Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
Subject subject = getSubject(request, response);
String[] perms = (String[]) mappedValue;
boolean isPermitted = true;
return isPermitted;
} | 肖敬先 | |
if (isRootUser<method*start>com.app.mvc.acl.service.SysCoreService.isRootUser<method*end>()) {
// root用户拥有所有权限点
return sysAclDao.getAll<method*start>com.app.mvc.acl.dao.SysAclDao.getAll<method*end>();
} | conventional | public List<method*start>java.util.List<method*end><SysAcl<method*start>com.app.mvc.acl.domain.SysAcl<method*end>> getUserAclList(int userId) {
List<method*start>java.util.List<method*end><Integer<method*start>java.lang.Integer<method*end>> userRoleIdList = sysRoleUserDao.getRoleIdListByUserId<method*start>com.app.mvc.acl.dao.SysRoleUserDao.getRoleIdListByUserId<method*end>(userId);
if (CollectionUtils.isEmpty<method*start>org.apache.commons.collections.CollectionUtils.isEmpty<method*end>(userRoleIdList)) {
return Lists.newArrayList<method*start>com.google.common.collect.Lists.newArrayList<method*end>();
}
List<method*start>java.util.List<method*end><Integer<method*start>java.lang.Integer<method*end>> userAclIdList = sysRoleAclDao.getAclIdListByRoleIdList<method*start>com.app.mvc.acl.dao.SysRoleAclDao.getAclIdListByRoleIdList<method*end>(userRoleIdList);
if (CollectionUtils.isEmpty<method*start>org.apache.commons.collections.CollectionUtils.isEmpty<method*end>(userAclIdList)) {
return Lists.newArrayList<method*start>com.google.common.collect.Lists.newArrayList<method*end>();
}
return sysAclDao.getByIdList<method*start>com.app.mvc.acl.dao.SysAclDao.getByIdList<method*end>(userAclIdList);
} | 肖敬先 | |
if (is_root<method*start>dump_dex.root.rootActivity.is_root<method*end>()) {
// Toast.makeText(this, "已经具有ROOT权限!", Toast.LENGTH_LONG).show();
} else {
try {
// ProgressDialog.show(this, "ROOT", "正在获取ROOT权限...", true, false);
Runtime<method*start>java.lang.Runtime<method*end>.getRuntime().exec("su");
} catch (Exception<method*start>java.lang.Exception<method*end> e) {
Toast<method*start>android.widget.Toast<method*end>.makeText(this, "获取ROOT权限时出错!", Toast<method*start>android.widget.Toast<method*end>.LENGTH_LONG).show();
}
} | conventional | private void j() {
// 判断busybox存在与否
File<method*start>java.io.File<method*end> f1 = new File<method*start>java.io.File<method*end>("/system/xbin/busybox");
if (f1.exists()) {
// 存在
Toast<method*start>android.widget.Toast<method*end>.makeText(rootActivity.this, "检测busybox:已安装", Toast<method*start>android.widget.Toast<method*end>.LENGTH_LONG).show();
} else {
File<method*start>java.io.File<method*end> f2 = new File<method*start>java.io.File<method*end>("/system/bin/busybox");
if (f2.exists()) {
// 存在
Toast<method*start>android.widget.Toast<method*end>.makeText(rootActivity.this, "检测busybox:已安装", Toast<method*start>android.widget.Toast<method*end>.LENGTH_LONG).show();
} else {
Toast<method*start>android.widget.Toast<method*end>.makeText(rootActivity.this, "检测busybox:未安装", Toast<method*start>android.widget.Toast<method*end>.LENGTH_LONG).show();
}
}
} | 肖敬先 | |
if (StringUtils.isEmpty(loginToken)) {
return ServerResponse.createByErrorMessage("用户未登录");
} | conventional | @RequestMapping(value = "update_information.do", method = RequestMethod.POST)
@ResponseBody
public ServerResponse updateInformation(HttpServletRequest request, User user) {
String loginToken = CookieUtil.readLoginToken(request);
User currentUser = JsonUtil.string2obj(RedisShardedPoolUtil.get(loginToken), User.class);
user.setId(currentUser.getId());
user.setUsername(currentUser.getUsername());
ServerResponse response = iUserService.updateUserInfo(user);
if (response.isSuccess()) {
RedisShardedPoolUtil.setEx(loginToken, JsonUtil.obj2string(response.getData()), Const.RedisCacheExTime.REDIS_SESSION_EXTIME);
return ServerResponse.createBySuccessMessage("更新成功");
}
return response;
} | 肖敬先 | |
// 使用主实体权限
if (entity.getMasterEntity<method*start>cn.devezhao.persist4j.Entity.getMasterEntity<method*end>() != null) {
entity = entity.getMasterEntity<method*start>cn.devezhao.persist4j.Entity.getMasterEntity<method*end>();
}
if (EntityHelper.hasPrivilegesField<method*start>com.rebuild.server.metadata.EntityHelper.hasPrivilegesField<method*end>(entity)) {
Permission<method*start>cn.devezhao.bizz.privileges.Permission<method*end>[] actions = new Permission<method*start>cn.devezhao.bizz.privileges.Permission<method*end>[] { BizzPermission.CREATE<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.CREATE<method*end>, BizzPermission.DELETE<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.DELETE<method*end>, BizzPermission.UPDATE<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.UPDATE<method*end>, BizzPermission.READ<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.READ<method*end>, BizzPermission.ASSIGN<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.ASSIGN<method*end>, BizzPermission.SHARE<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.SHARE<method*end> };
Map<method*start>java.util.Map<method*end><String<method*start>java.lang.String<method*end>, Boolean> actionMap = new HashMap<method*start>java.util.HashMap<method*end><>();
for (Permission<method*start>cn.devezhao.bizz.privileges.Permission<method*end> act : actions) {
actionMap.put<method*start>java.util.Map.put<method*end>(act.getName<method*start>cn.devezhao.bizz.privileges.Permission.getName<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, record, act));
}
mv.getModel<method*start>org.springframework.web.servlet.ModelAndView.getModel<method*end>().put<method*start>java.util.Map.put<method*end>("entityPrivileges", JSON.toJSONString<method*start>com.alibaba.fastjson.JSON.toJSONString<method*end>(actionMap));
} else {
mv.getModel<method*start>org.springframework.web.servlet.ModelAndView.getModel<method*end>().put<method*start>java.util.Map.put<method*end>("entityPrivileges", JSONUtils.EMPTY_OBJECT_STR<method*start>com.rebuild.utils.JSONUtils.EMPTY_OBJECT_STR<method*end>);
} | conventional | protected ModelAndView<method*start>org.springframework.web.servlet.ModelAndView<method*end> createModelAndView(String<method*start>java.lang.String<method*end> page, ID<method*start>cn.devezhao.persist4j.engine.ID<method*end> record, ID<method*start>cn.devezhao.persist4j.engine.ID<method*end> user) {
ModelAndView<method*start>org.springframework.web.servlet.ModelAndView<method*end> mv = createModelAndView(page);
Entity<method*start>cn.devezhao.persist4j.Entity<method*end> entity = MetadataHelper.getEntity<method*start>com.rebuild.server.metadata.MetadataHelper.getEntity<method*end>(record.getEntityCode<method*start>cn.devezhao.persist4j.engine.ID.getEntityCode<method*end>());
putEntityMeta<method*start>com.rebuild.web.BaseEntityControll.putEntityMeta<method*end>(mv, entity);
// 使用主实体权限
if (entity.getMasterEntity<method*start>cn.devezhao.persist4j.Entity.getMasterEntity<method*end>() != null) {
entity = entity.getMasterEntity<method*start>cn.devezhao.persist4j.Entity.getMasterEntity<method*end>();
}
if (EntityHelper.hasPrivilegesField<method*start>com.rebuild.server.metadata.EntityHelper.hasPrivilegesField<method*end>(entity)) {
Permission<method*start>cn.devezhao.bizz.privileges.Permission<method*end>[] actions = new Permission<method*start>cn.devezhao.bizz.privileges.Permission<method*end>[] { BizzPermission.CREATE<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.CREATE<method*end>, BizzPermission.DELETE<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.DELETE<method*end>, BizzPermission.UPDATE<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.UPDATE<method*end>, BizzPermission.READ<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.READ<method*end>, BizzPermission.ASSIGN<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.ASSIGN<method*end>, BizzPermission.SHARE<method*start>cn.devezhao.bizz.privileges.impl.BizzPermission.SHARE<method*end> };
Map<method*start>java.util.Map<method*end><String<method*start>java.lang.String<method*end>, Boolean> actionMap = new HashMap<method*start>java.util.HashMap<method*end><>();
for (Permission<method*start>cn.devezhao.bizz.privileges.Permission<method*end> act : actions) {
actionMap.put<method*start>java.util.Map.put<method*end>(act.getName<method*start>cn.devezhao.bizz.privileges.Permission.getName<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, record, act));
}
mv.getModel<method*start>org.springframework.web.servlet.ModelAndView.getModel<method*end>().put<method*start>java.util.Map.put<method*end>("entityPrivileges", JSON.toJSONString<method*start>com.alibaba.fastjson.JSON.toJSONString<method*end>(actionMap));
} else {
mv.getModel<method*start>org.springframework.web.servlet.ModelAndView.getModel<method*end>().put<method*start>java.util.Map.put<method*end>("entityPrivileges", JSONUtils.EMPTY_OBJECT_STR<method*start>com.rebuild.utils.JSONUtils.EMPTY_OBJECT_STR<method*end>);
}
return mv;
} | 万爽 | |
if (null == aclDO) {
throw BizException.fail<method*start>com.momo.common.core.error.BizException.fail<method*end>("待查询的权限不存在");
}
| conventional | public AclDetailRes<method*start>com.momo.mapper.res.authority.AclDetailRes<method*end> detail(AclReq<method*start>com.momo.mapper.req.authority.AclReq<method*end> aclReq) {
AclDO<method*start>com.momo.mapper.dataobject.AclDO<method*end> aclDO = aclMapper.selectByPrimaryUuid<method*start>com.momo.mapper.mapper.manual.AclMapper.selectByPrimaryUuid<method*end>(aclReq.getUuid<method*start>com.momo.mapper.req.authority.AclReq.getUuid<method*end>());
AclDetailRes<method*start>com.momo.mapper.res.authority.AclDetailRes<method*end> aclDetailRes = new AclDetailRes<method*start>com.momo.mapper.res.authority.AclDetailRes<method*end>();
BeanUtils.copyProperties<method*start>org.springframework.beans.BeanUtils.copyProperties<method*end>(aclDO, aclDetailRes);
// 类型,-1系统 0:目录 1:菜单,2:按钮,3:其他
if (aclDO.getSysAclType<method*start>com.momo.mapper.dataobject.AclDO.getSysAclType<method*end>().equals<method*start>java.lang.Integer.equals<method*end>(AclTypeEnum.system.type<method*start>com.momo.mapper.enums.AclTypeEnum.type<method*end>)) {
// 是否有孩子
int count = aclMapper.checkChildAcl<method*start>com.momo.mapper.mapper.manual.AclMapper.checkChildAcl<method*end>(LevelUtil.calculateLevel<method*start>com.momo.common.core.util.LevelUtil.calculateLevel<method*end>(aclDO.getSysAclLevel<method*start>com.momo.mapper.dataobject.AclDO.getSysAclLevel<method*end>(), aclDO.getId<method*start>com.momo.mapper.dataobject.AclDO.getId<method*end>()));
if (count == 0) {
aclDetailRes.setDisabledAclSysCode<method*start>com.momo.mapper.res.authority.AclDetailRes.setDisabledAclSysCode<method*end>(false);
}
}
aclDetailRes.setIdStr<method*start>com.momo.mapper.res.authority.AclDetailRes.setIdStr<method*end>(String.valueOf<method*start>java.lang.String.valueOf<method*end>(aclDO.getId<method*start>com.momo.mapper.dataobject.AclDO.getId<method*end>()));
aclDetailRes.setSysAclParentIdStr<method*start>com.momo.mapper.res.authority.AclDetailRes.setSysAclParentIdStr<method*end>(String.valueOf<method*start>java.lang.String.valueOf<method*end>(aclDO.getSysAclParentId<method*start>com.momo.mapper.dataobject.AclDO.getSysAclParentId<method*end>()));
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);
}
} | 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());
RetMsg retMsg = roleService.delete(list);
if (!retMsg.checkCode()) {
response.setStatus(retMsg.getCode());
return Hret.error(retMsg);
}
return Hret.success(retMsg);
} | 万爽 | |
@Authorize(merge = false)
| annotation | @PatchMapping("/me/{key}")
@ApiOperation("保存当前用户配置")
public ResponseMessage<String> 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);
} | 万爽 | |
if (ActivityCompat.checkSelfPermission<method*start>android.support.v4.app.ActivityCompat.checkSelfPermission<method*end>(context, Manifest.permission.READ_PHONE_STATE<method*start>android.Manifest.permission.READ_PHONE_STATE<method*end>) == PackageManager.PERMISSION_GRANTED<method*start>android.content.pm.PackageManager.PERMISSION_GRANTED<method*end>) {
try {
final TelephonyManager<method*start>android.telephony.TelephonyManager<method*end> tm = (TelephonyManager<method*start>android.telephony.TelephonyManager<method*end>) context.getSystemService<method*start>android.content.Context.getSystemService<method*end>(Context.TELEPHONY_SERVICE<method*start>android.content.Context.TELEPHONY_SERVICE<method*end>);
tmDevice = "" + tm.getDeviceId<method*start>android.telephony.TelephonyManager.getDeviceId<method*end>();
tmSerial = "" + tm.getSimSerialNumber<method*start>android.telephony.TelephonyManager.getSimSerialNumber<method*end>();
androidId = "" + android.provider.Settings.Secure.getString<method*start>android.provider.Settings.Secure.getString<method*end>(context.getContentResolver<method*start>android.content.Context.getContentResolver<method*end>(), android.provider.Settings.Secure.ANDROID_ID<method*start>android.provider.Settings.Secure.ANDROID_ID<method*end>);
} catch (Exception<method*start>java.lang.Exception<method*end> e) {
Log.e<method*start>android.util.Log.e<method*end>("AppUtils", "exception:" + e.getMessage<method*start>java.lang.Exception.getMessage<method*end>());
}
} else {
Log.e<method*start>android.util.Log.e<method*end>("AppUtils", "没有 android.permission.READ_PHONE_STATE 权限");
tmDevice = "device";
tmSerial = "serial";
androidId = "androidid";
} | conventional | public static String<method*start>java.lang.String<method*end> getUUID(Context<method*start>android.content.Context<method*end> context) {
String<method*start>java.lang.String<method*end> tmDevice = "", tmSerial = "", tmPhone = "", androidId = "";
return uniqueId;
} | 万爽 | |
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>(), "用户未登录,请登录管理员");
} | conventional | @RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>("list.do")
@ResponseBody
public ServerResponse<method*start>com.mmall.common.ServerResponse<method*end><PageInfo<method*start>com.github.pagehelper.PageInfo<method*end>> orderList(HttpSession<method*start>javax.servlet.http.HttpSession<method*end> session, @RequestParam<method*start>org.springframework.web.bind.annotation.RequestParam<method*end>(value<method*start>org.springframework.web.bind.annotation.RequestParam.value<method*end> = "pageNum", defaultValue<method*start>org.springframework.web.bind.annotation.RequestParam.defaultValue<method*end> = "1") int pageNum, @RequestParam<method*start>org.springframework.web.bind.annotation.RequestParam<method*end>(value<method*start>org.springframework.web.bind.annotation.RequestParam.value<method*end> = "pageSize", defaultValue<method*start>org.springframework.web.bind.annotation.RequestParam.defaultValue<method*end> = "10") int pageSize) {
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>);
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.manageList<method*start>com.mmall.service.IOrderService.manageList<method*end>(pageNum, pageSize);
} else {
return ServerResponse.createByErrorMessage<method*start>com.mmall.common.ServerResponse.createByErrorMessage<method*end>("无权限操作");
}
} | 万爽 | |
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 (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;
} | 万爽 | |
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>) && !BaseUtil.getUser<method*start>com.kakarote.crm9.utils.BaseUtil.getUser<method*end>().getRoles<method*start>com.kakarote.crm9.erp.admin.entity.AdminUser.getRoles<method*end>().contains<method*start>java.util.List.contains<method*end>(BaseConstant.SUPER_ADMIN_ROLE_ID<method*start>com.kakarote.crm9.common.constant.BaseConstant.SUPER_ADMIN_ROLE_ID<method*end>) && Db.queryInt<method*start>com.jfinal.plugin.activerecord.Db.queryInt<method*end>(Db.getSql<method*start>com.jfinal.plugin.activerecord.Db.getSql<method*end>("crm.customer.queryIsRoUser"), BaseUtil.getUserId<method*start>com.kakarote.crm9.utils.BaseUtil.getUserId<method*end>(), id) > 0) {
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> setDealStatus(String<method*start>java.lang.String<method*end> ids, Integer<method*start>java.lang.Integer<method*end> dealStatus) {
String<method*start>java.lang.String<method*end>[] idsArr = ids.split<method*start>java.lang.String.split<method*end>(",");
for (String<method*start>java.lang.String<method*end> id : idsArr) {
CrmCustomer customer = CrmCustomer.dao.findById<method*start>com.jfinal.plugin.activerecord.Model.findById<method*end>(id);
if (0 == dealStatus && 1 == customer.getDealStatus<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmCustomer.getDealStatus<method*end>()) {
if (!queryCustomerSettingNum<method*start>com.kakarote.crm9.erp.crm.service.CrmCustomerService.queryCustomerSettingNum<method*end>(1, Long.valueOf<method*start>java.lang.Long.valueOf<method*end>(customer.getOwnerUserId<method*start>com.kakarote.crm9.erp.crm.entity.base.BaseCrmCustomer.getOwnerUserId<method*end>()))) {
return R.error<method*start>com.kakarote.crm9.utils.R.error<method*end>("所选客户中有负责人拥有客户数已达上限");
}
}
}
Db.update<method*start>com.jfinal.plugin.activerecord.Db.update<method*end>(Db.getSqlPara<method*start>com.jfinal.plugin.activerecord.Db.getSqlPara<method*end>("crm.customer.setDealStatus", Kv.by<method*start>com.jfinal.kit.Kv.by<method*end>("ids", idsArr).set<method*start>com.jfinal.kit.Kv.set<method*end>("dealStatus", dealStatus)));
return R.ok<method*start>com.kakarote.crm9.utils.R.ok<method*end>();
} | 万爽 | |
@RequiresPermissions<method*start>org.apache.shiro.authz.annotation.RequiresPermissions<method*end>("sys:role:info") | 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:role:info)")
@GetMapping<method*start>org.springframework.web.bind.annotation.GetMapping<method*end>("/info/{roleId}")
public JsonResponse<method*start>com.king.common.utils.JsonResponse<method*end> info(@PathVariable<method*start>org.springframework.web.bind.annotation.PathVariable<method*end>("roleId") Object<method*start>java.lang.Object<method*end> roleId) {
SysRole<method*start>com.king.dal.gen.model.smp.SysRole<method*end> role = sysRoleService.queryObject<method*start>com.king.api.smp.SysRoleService.queryObject<method*end>(roleId);
// 查询角色对应的菜单
List<method*start>java.util.List<method*end><Long<method*start>java.lang.Long<method*end>> menuIdList = sysMenuService.queryMenuIdList<method*start>com.king.api.smp.SysMenuService.queryMenuIdList<method*end>(roleId);
role.setMenuIdList<method*start>com.king.dal.gen.model.smp.SysRole.setMenuIdList<method*end>(menuIdList);
// 查询角色对应的部门
List<method*start>java.util.List<method*end><Long<method*start>java.lang.Long<method*end>> deptIdList = sysDeptService.queryDeptIdListByRoleId<method*start>com.king.api.smp.SysDeptService.queryDeptIdListByRoleId<method*end>(roleId);
role.setDeptIdList<method*start>com.king.dal.gen.model.smp.SysRole.setDeptIdList<method*end>(deptIdList);
JSONArray<method*start>com.alibaba.fastjson.JSONArray<method*end> params = sysMenuService.queryParamsList<method*start>com.king.api.smp.SysMenuService.queryParamsList<method*end>(roleId);
List<method*start>java.util.List<method*end><Long<method*start>java.lang.Long<method*end>> userIdList = sysRoleService.queryUserIdList<method*start>com.king.api.smp.SysRoleService.queryUserIdList<method*end>(roleId);
role.setParamExt<method*start>com.king.dal.gen.model.smp.SysRole.setParamExt<method*end>(params);
role.setUserIdList<method*start>com.king.dal.gen.model.smp.SysRole.setUserIdList<method*end>(userIdList);
return JsonResponse.success<method*start>com.king.common.utils.JsonResponse.success<method*end>(role);
} | 万爽 | |
@RequiresPermissions<method*start>org.apache.shiro.authz.annotation.RequiresPermissions<method*end>("sys:users:offline") | 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:users:offline)")
@PostMapping<method*start>org.springframework.web.bind.annotation.PostMapping<method*end>("/offline")
public JsonResponse<method*start>com.king.common.utils.JsonResponse<method*end> offline(@RequestBody<method*start>org.springframework.web.bind.annotation.RequestBody<method*end>(required<method*start>org.springframework.web.bind.annotation.RequestBody.required<method*end> = false) String<method*start>java.lang.String<method*end>[] tokens) {
String<method*start>java.lang.String<method*end> t = getUser<method*start>com.king.utils.AbstractController.getUser<method*end>().getToken<method*start>com.king.dal.gen.model.smp.SysUser.getToken<method*end>();
if (ArrayUtils.contains<method*start>org.apache.commons.lang.ArrayUtils.contains<method*end>(tokens, t)) {
return JsonResponse.error<method*start>com.king.common.utils.JsonResponse.error<method*end>("当前用户不能注销!");
}
if (getUser<method*start>com.king.utils.AbstractController.getUser<method*end>().getUserId<method*start>com.king.dal.gen.model.smp.SysUser.getUserId<method*end>() == Constant.SUPER_ADMIN<method*start>com.king.common.utils.constant.Constant.SUPER_ADMIN<method*end>) {
return JsonResponse.error<method*start>com.king.common.utils.JsonResponse.error<method*end>("系统管理员不能注销!");
}
for (String<method*start>java.lang.String<method*end> token : tokens) {
redisUtils.delete<method*start>com.king.common.utils.redis.RedisUtils.delete<method*end>(RedisKeys.getTokenKey<method*start>com.king.common.utils.redis.RedisKeys.getTokenKey<method*end>(token));
}
return JsonResponse.success<method*start>com.king.common.utils.JsonResponse.success<method*end>();
} | 万爽 | |
@AuthInterceptor(InterceptorLevel.USER)
if (Checker.isNull(user)) | annotation | @ApiOperation(value = "删除指定文件")
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String removeFile(@PathVariable("id") long id) {
User user = (User) request.getSession().getAttribute(ValueConsts.USER_STRING);
jsonObject.put("status", "error");
jsonObject.put("message", "请先登录");
else if (id < 1) {
jsonObject.put("message", "格式不合法");
} else if (fileService.removeFile(user, id)) {
jsonObject.put("status", "success");
} else {
jsonObject.put("message", "删除失败,权限不够,请联系管理员");
}
return jsonObject.toString();
} | 万爽 | |
if (!isSuperuser) {
resp.addProperty(RestUtils.RESP_KEY_RC, RestUtils.RESP_RC_SUCC);
resp.addProperty(RestUtils.RESP_KEY_ERROR, "您不具有访问该资源的权限。");
return resp;
} | conventional | private JsonObject vacant(final JsonObject j, String orgi, boolean isSuperuser) {
JsonObject resp = new JsonObject();
List<SNSAccount> records = snsAccountRes.findBySnstypeAndOrgi(Constants.CHANNEL_TYPE_WEBIM, orgi);
JsonArray ja = new JsonArray();
for (SNSAccount r : records) {
if (!chatbotRes.existsBySnsAccountIdentifierAndOrgi(r.getSnsid(), orgi)) {
JsonObject o = new JsonObject();
o.addProperty("id", r.getId());
o.addProperty("snsid", r.getSnsid());
o.addProperty("snsType", r.getSnstype());
o.addProperty("snsurl", r.getBaseURL());
ja.add(o);
}
}
resp.add("data", ja);
resp.addProperty(RestUtils.RESP_KEY_RC, RestUtils.RESP_RC_SUCC);
return resp;
} | 万爽 | |
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>(), "用户未登录,请登录管理员");
} | conventional | @RequestMapping("upload.do")
public ServerResponse<method*start>com.mmall.common.ServerResponse<method*end> upload(HttpSession<method*start>javax.servlet.http.HttpSession<method*end> session, @RequestParam<method*start>org.springframework.web.bind.annotation.RequestParam<method*end>(value<method*start>org.springframework.web.bind.annotation.RequestParam.value<method*end> = "upload_file", required<method*start>org.springframework.web.bind.annotation.RequestParam.required<method*end> = false) MultipartFile<method*start>org.springframework.web.multipart.MultipartFile<method*end> file, HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request) {
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>);
if (iUserService.checkAdminRole<method*start>com.mmall.service.IUserService.checkAdminRole<method*end>(user).isSuccess<method*start>com.mmall.common.ServerResponse.isSuccess<method*end>()) {
String<method*start>java.lang.String<method*end> path = request.getSession<method*start>javax.servlet.http.HttpServletRequest.getSession<method*end>().getServletContext<method*start>javax.servlet.http.HttpSession.getServletContext<method*end>().getRealPath<method*start>javax.servlet.ServletContext.getRealPath<method*end>("upload");
String<method*start>java.lang.String<method*end> targetFileName = iFileService.upload<method*start>com.mmall.service.IFileService.upload<method*end>(file, path);
String<method*start>java.lang.String<method*end> url = PropertiesUtil.getProperty<method*start>com.mmall.util.PropertiesUtil.getProperty<method*end>("ftp.server.http.prefix") + targetFileName;
Map<method*start>java.util.Map<method*end> fileMap = Maps.newHashMap<method*start>com.google.common.collect.Maps.newHashMap<method*end>();
fileMap.put<method*start>java.util.Map.put<method*end>("uri", targetFileName);
fileMap.put<method*start>java.util.Map.put<method*end>("url", url);
return ServerResponse.createBySuccess<method*start>com.mmall.common.ServerResponse.createBySuccess<method*end>(fileMap);
} else {
return ServerResponse.createByErrorMessage<method*start>com.mmall.common.ServerResponse.createByErrorMessage<method*end>("无权限操作");
}
} | 万爽 | |
if (sessionPermission != null) {
// 登录用户当前应用的菜单
request.setAttribute("userMenus", sessionPermission.getMenuList());
// 登录用户当前应用的权限
request.setAttribute("userPermissions", sessionPermission.getPermissionSet());
} | conventional | @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
SessionUser sessionUser = SessionUtils.getSessionUser(request);
// 登录用户名
request.setAttribute("userName", sessionUser.getAccount());
// 单点退出地址
request.setAttribute("ssologoutUrl", new StringBuilder().append(getSsoServerUrl(request)).append("/logout?backUrl=").append(getLocalUrl(request)).toString());
SessionPermission sessionPermission = SessionUtils.getSessionPermission(request);
request.getRequestDispatcher("/index.jsp").forward(request, response);
} | 万爽 | |
if (matchAnyRoles) {
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);
} | 万爽 | |
if (!redisUser.getTenantId().equals(1L)) {
throw new BizException("您不是MOMO企业下的VIP,无权操作");
} | conventional | @Override
public DataDictLevelRes<com.momo.mapper.res.systemconfig.DataDictLevelRes> dataDictTree(DataDictTreeReq<com.momo.mapper.req.systemconfig.DataDictTreeReq> dataDictTreeReq) {
RedisUser<com.momo.common.core.entity.RedisUser> redisUser = this.redisUser();
DataDictLevelRes<com.momo.mapper.res.systemconfig.DataDictLevelRes> dataDictLevelRes = new DataDictLevelRes<com.momo.mapper.res.systemconfig.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);
} | 万爽 | |
Assert.isTrue(topic.getUserId().equals(getUser().getId()), "谁给你的权限修改别人的话题的?"); | conventional | @GetMapping("/edit/{id}")
public String edit(@PathVariable Integer id, Model model) {
Topic topic = topicService.selectById(id);
// 查询话题的标签
List<Tag> tagList = tagService.selectByTopicId(id);
// 将标签集合转成逗号隔开的字符串
String tags = StringUtils.collectionToCommaDelimitedString(tagList.stream().map(Tag::getName).collect(Collectors.toList()));
model.addAttribute("topic", topic);
model.addAttribute("tags", tags);
return render("topic/edit");
} | 万爽 | |
if (!hasBizPermission(request, xxlApiProject.getBizId())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通");
} | conventional | @RequestMapping("/add")
@ResponseBody
public ReturnT<String> add(HttpServletRequest request, XxlApiProject xxlApiProject) {
if (StringTool.isBlank(xxlApiProject.getName())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "请输入项目名称");
}
if (StringTool.isBlank(xxlApiProject.getBaseUrlProduct())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "请输入根地址(线上)");
}
int ret = xxlApiProjectDao.add(xxlApiProject);
return (ret > 0) ? ReturnT.SUCCESS : ReturnT.FAIL;
} | 万爽 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.