validation
stringlengths 16
3.54k
| validationType
stringclasses 2
values | function
stringlengths 49
6.38k
| author
stringclasses 5
values | context
stringclasses 5
values |
|---|---|---|---|---|
// 设置securityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 登录的url
shiroFilterFactoryBean.setLoginUrl("/login");
// 登录成功后跳转的url
shiroFilterFactoryBean.setSuccessUrl("/index");
// 未授权url
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
LinkedHashMap<method*start>java.util.LinkedHashMap<method*end><String<method*start>java.lang.String<method*end>, String<method*start>java.lang.String<method*end>> filterChainDefinitionMap = new LinkedHashMap<method*start>java.util.LinkedHashMap<method*end><>();
// 定义filterChain,静态资源不拦截
filterChainDefinitionMap.put("/css/**", "anon");
filterChainDefinitionMap.put("/js/**", "anon");
filterChainDefinitionMap.put("/fonts/**", "anon");
filterChainDefinitionMap.put("/img/**", "anon");
// druid数据源监控页面不拦截
filterChainDefinitionMap.put("/druid/**", "anon");
// 配置退出过滤器,其中具体的退出代码Shiro已经替我们实现了
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/", "anon");
// 除上以外所有url都必须认证通过才可以访问,未通过认证自动访问LoginUrl
filterChainDefinitionMap.put("/**", "user");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
|
conventional
|
@Bean
public ShiroFilterFactoryBean<method*start>org.apache.shiro.spring.web.ShiroFilterFactoryBean<method*end> shiroFilterFactoryBean(SecurityManager<method*start>org.apache.shiro.mgt.SecurityManager<method*end> securityManager) {
ShiroFilterFactoryBean<method*start>org.apache.shiro.spring.web.ShiroFilterFactoryBean<method*end> shiroFilterFactoryBean = new ShiroFilterFactoryBean<method*start>org.apache.shiro.spring.web.ShiroFilterFactoryBean<method*end>();
return shiroFilterFactoryBean;
}
|
万爽
| |
if (!filter) {
if (StringUtils.isNotBlank(request.getParameter("msg"))) {
response.sendRedirect("/login.html?msg=" + request.getParameter("msg"));
} else {
response.sendRedirect("/login.html");
}
}
|
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 (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);
}
}
} else {
filter = true;
}
return filter;
}
|
万爽
| |
// 如果verifiers为empty,或者传入的weId为空,或者weId不在指定列表中,则无权限获取秘钥数据
if (CollectionUtils.isEmpty(verifiers) || StringUtils.isBlank(weId) || !verifiers.contains(weId)) {
logger.error("[getEncryptKey] no access to get the data, this weid is {}.", weId);
throw new EncodeSuiteException(ErrorCode.ENCRYPT_KEY_NO_PERMISSION);
}
return (String) keyMap.get(ParamKeyConstant.KEY_DATA);
} catch (DataTypeCastException e) {
logger.error("[getEncryptKey] deserialize the data error, you should upgrade SDK.", e);
throw new EncodeSuiteException(ErrorCode.ENCRYPT_KEY_INVALID);
}
|
conventional
|
private String getEncryptKey(EncodeData encodeData, String value) {
if (encodeData.getWeIdAuthentication() == null) {
logger.info("[getEncryptKey] the weid Authentication is null.");
throw new EncodeSuiteException(ErrorCode.ENCRYPT_KEY_NO_PERMISSION);
}
try {
Map<String, Object> keyMap = DataToolUtils.deserialize(value, new HashMap<String, Object>().getClass());
String weId = encodeData.getWeIdAuthentication().getWeId();
List<String> verifiers = (ArrayList<String>) keyMap.get(ParamKeyConstant.KEY_VERIFIERS);
}
|
万爽
| |
if (loginFlag) {
pjp.proceed<method*start>org.aspectj.lang.ProceedingJoinPoint.proceed<method*end>();
} else {
response.sendRedirect<method*start>javax.servlet.http.HttpServletResponse.sendRedirect<method*end>("/infoManager/login.html");
}
}
|
conventional
|
@Around<method*start>org.aspectj.lang.annotation.Around<method*end>("anyMethod()")
public Object<method*start>java.lang.Object<method*end> appsActionMethod(ProceedingJoinPoint<method*start>org.aspectj.lang.ProceedingJoinPoint<method*end> pjp) throws Throwable<method*start>java.lang.Throwable<method*end> {
Object<method*start>java.lang.Object<method*end>[] obs = pjp.getArgs<method*start>org.aspectj.lang.ProceedingJoinPoint.getArgs<method*end>();
HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request = null;
HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response = null;
Boolean<method*start>java.lang.Boolean<method*end> loginFlag = false;
if (obs != null) {
for (int i = 0; i < obs.length<method*start>java.lang.Object[].length<method*end>; i++) {
Object<method*start>java.lang.Object<method*end> obj = obs[i];
if (obj instanceof HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end>) {
request = (HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end>) obj;
}
if (obj instanceof HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end>) {
response = (HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end>) obj;
}
}
if (!(pjp.getThis<method*start>org.aspectj.lang.ProceedingJoinPoint.getThis<method*end>() instanceof LoginAopSkip<method*start>indi.xiao.ext.aop.LoginAopSkip<method*end>)) {
Cookie<method*start>javax.servlet.http.Cookie<method*end>[] cookies = request.getCookies<method*start>javax.servlet.http.HttpServletRequest.getCookies<method*end>();
if (cookies != null && cookies.length<method*start>javax.servlet.http.Cookie[].length<method*end> > 0) {
for (Cookie<method*start>javax.servlet.http.Cookie<method*end> ck : cookies) {
if ("login".equals<method*start>java.lang.String.equals<method*end>(ck.getName<method*start>javax.servlet.http.Cookie.getName<method*end>()) && ck.getValue<method*start>javax.servlet.http.Cookie.getValue<method*end>() != null) {
loginFlag = true;
}
}
}
} else {
loginFlag = true;
}
return "";
}
|
万爽
| |
AccessibleObject.checkPermission();
|
conventional
|
@Override
@CallerSensitive
public void setAccessible(boolean flag) {
// 如果需要开启访问权限
if (flag) {
// 获取setAccessible()的调用者所处的类
Class<?> caller = Reflection.getCallerClass();
// 判断caller是否可以访问当前元素(涉及到exports和opens的判断)
checkCanSetAccessible(caller);
}
setAccessible0(flag);
}
|
万爽
| |
@AuthInterceptor(InterceptorLevel.USER)
|
annotation
|
@ApiOperation(value = "更新文件属性")
@ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "文件名", required = true), @ApiImplicitParam(name = "category", value = "分类名称", required = true), @ApiImplicitParam(name = "tag", value = "文件标签", required = true), @ApiImplicitParam(name = "description", value = "文件描述", required = true) })
@AuthInterceptor(InterceptorLevel.USER)
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public String updateFileInfo(@PathVariable("id") long id, String name, String category, String tag, String description) {
User user = (User) request.getSession().getAttribute(ValueConsts.USER_STRING);
jsonObject.put("status", "error");
if (fileService.updateFileInfo(id, user, name, category, tag, description)) {
jsonObject.put("status", "success");
} else {
jsonObject.put("message", "格式不正确或权限不够,更新失败,请联系管理员");
}
return jsonObject.toString();
}
|
万爽
| |
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);
// 验证通过
Authentication authentication = authenticationManager.authenticate(new PlainTextUsernamePasswordAuthenticationRequest(username, password));
// 触发授权成功事件
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();
}
|
annotation
|
@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;
}
|
万爽
| |
// root用户返回所有菜单,防止root账户还需要授权才能访问
if (UserRealm.SUPER_USER.equals(username)) {
return this.resourcesRepository.findAll();
}
|
conventional
|
@Override
public Collection<Resources> getUserResources(String username) {
// 找出用户的角色,根据角色查找用户的菜单
// 直接调用shiroService的实现方式,防止使用框架方需要自定义角色获取方式
Set<String> roleNames = shiroService.getUserRoleNames(username);
List<Permission> permissions = permissionRepository.findByRoleNameIn(roleNames);
Map<Long, Resources> resourcesMap = new HashMap<>();
permissions.forEach((p) -> {
resourcesMap.put(p.getResource().getId(), p.getResource());
});
return resourcesMap.values();
}
|
万爽
| |
DefaultWebSecurityManager<method*start>org.apache.shiro.web.mgt.DefaultWebSecurityManager<method*end> securityManager = (DefaultWebSecurityManager<method*start>org.apache.shiro.web.mgt.DefaultWebSecurityManager<method*end>) SecurityUtils.getSecurityManager<method*start>org.apache.shiro.SecurityUtils.getSecurityManager<method*end>();
Authenticator<method*start>org.apache.shiro.authc.Authenticator<method*end> authc = securityManager.getAuthenticator<method*start>org.apache.shiro.web.mgt.DefaultWebSecurityManager.getAuthenticator<method*end>();
((LogoutAware<method*start>org.apache.shiro.authc.LogoutAware<method*end>) authc).onLogout<method*start>org.apache.shiro.authc.LogoutAware.onLogout<method*end>((SimplePrincipalCollection<method*start>org.apache.shiro.subject.SimplePrincipalCollection<method*end>) attribute);
|
conventional
|
public static void deleteCache(String<method*start>java.lang.String<method*end> username, boolean isRemoveSession) {
// 从缓存中获取Session
Session<method*start>org.apache.shiro.session.Session<method*end> session = null;
Collection<method*start>java.util.Collection<method*end><Session<method*start>org.apache.shiro.session.Session<method*end>> sessions = redisSessionDAO.getActiveSessions<method*start>org.crazycake.shiro.RedisSessionDAO.getActiveSessions<method*end>();
SysUserEntity<method*start>com.sans.core.entity.SysUserEntity<method*end> sysUserEntity;
Object<method*start>java.lang.Object<method*end> attribute = null;
for (Session<method*start>org.apache.shiro.session.Session<method*end> sessionInfo : sessions) {
// 遍历Session,找到该用户名称对应的Session
attribute = sessionInfo.getAttribute<method*start>org.apache.shiro.session.Session.getAttribute<method*end>(DefaultSubjectContext.PRINCIPALS_SESSION_KEY<method*start>org.apache.shiro.subject.support.DefaultSubjectContext.PRINCIPALS_SESSION_KEY<method*end>);
if (attribute == null) {
continue;
}
sysUserEntity = (SysUserEntity<method*start>com.sans.core.entity.SysUserEntity<method*end>) ((SimplePrincipalCollection<method*start>org.apache.shiro.subject.SimplePrincipalCollection<method*end>) attribute).getPrimaryPrincipal<method*start>org.apache.shiro.subject.SimplePrincipalCollection.getPrimaryPrincipal<method*end>();
if (sysUserEntity == null) {
continue;
}
if (Objects.equals<method*start>java.util.Objects.equals<method*end>(sysUserEntity.getUsername<method*start>com.sh.demo.core.entity.SysUserEntity.getUsername<method*end>(), username)) {
session = sessionInfo;
break;
}
}
if (session == null || attribute == null) {
return;
}
// 删除session
if (isRemoveSession) {
redisSessionDAO.delete<method*start>org.crazycake.shiro.RedisSessionDAO.delete<method*end>(session);
}
// 删除Cache,在访问受限接口时会重新授权
}
|
万爽
| |
if (user == null) {
resultMap.put("success", false);
resultMap.put("msg", "请登录管理员");
return resultMap;
}
|
conventional
|
@RequestMapping("richtext_img_upload.do")
public Map richtextImgUpload(HttpSession session, @RequestParam(value = "upload_file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
Map resultMap = Maps.newHashMap();
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (iUserService.checkAdminRole(user).isSuccess()) {
String path = request.getSession().getServletContext().getRealPath("upload");
String targetFileName = iFileService.upload(file, path);
if (StringUtils.isBlank(targetFileName)) {
resultMap.put("success", false);
resultMap.put("msg", "上传失败");
return resultMap;
}
String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
resultMap.put("success", true);
resultMap.put("msg", "上传成功");
resultMap.put("file_path", url);
response.addHeader("Access-Control-Allow-Headers", "X-File-Name");
return resultMap;
} else {
resultMap.put("success", false);
resultMap.put("msg", "无权限操作");
return resultMap;
}
}
|
万爽
| |
@RequiresPermissions("oss:file:upload")
|
annotation
|
@ApiOperation(value = "文件上传", notes = "权限编码(oss:file:upload)")
@PostMapping("/upload")
public 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);
}
|
万爽
| |
if (client != null && client.getUser() != null) {
Client ret = new Client();
ret.setIp(client.getIp());
ret.setLogindatetime(client.getLogindatetime());
TSUser t = new TSUser();
t.setUserName(client.getUser().getUserName());
t.setRealName(client.getUser().getRealName());
ret.setUser(t);
addClientToCachedMap(sessionId, ret);
}
|
conventional
|
public void addClinet(String sessionId, Client client) {
// 当前session会话,保存登录用户信息
ContextHolderUtils.getSession().setAttribute(sessionId, client);
}
|
万爽
| |
// 拦截器.
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
// 配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/static/**", "anon");
// 配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
filterChainDefinitionMap.put("/logout", "logout");
// <!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
// <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
// filterChainDefinitionMap.put("/**", "authc");
filterChainDefinitionMap.put("/**", "anon");
// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
shiroFilterFactoryBean.setLoginUrl("/login");
// 登录成功后要跳转的链接
shiroFilterFactoryBean.setSuccessUrl("/index");
// 未授权界面;
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
|
conventional
|
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
System.out.println("ShiroConfiguration.shirFilter()");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 权限控制map.
// 从数据库获取
// List<SysPermission> list = sysPermissionInitRepository.findAll();
//
// logger.info("ssssss",Arrays.asList(list));
// for (SysPermission sysPermissionInit : list) {
// filterChainDefinitionMap.put(sysPermissionInit.getUrl(),
// sysPermissionInit.getPermission());
// }
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
System.out.println("Shiro拦截器工厂类注入成功");
return shiroFilterFactoryBean;
}
|
万爽
| |
try {
final Object[] args = new Object[] {};
InvocationContext mfc = new InvocationContext(path, cont, method, args);
WebCtrlFilterManager.INSTANCE.executeWithFilter(mfc, new IMethodCallback() {
public Object run() throws Throwable {
return RuleProxyHelper.invokeWithRule(cont, method, args);
}
});
// res.getWriter().print(result.getJson());
} catch (MethodIllegleAccessException e1) {
// 无权限,返回空内容
} catch (InvocationTargetException e) {
throw ((InvocationTargetException) e).getTargetException();
}
|
conventional
|
public void dohttp(String path, HttpServletRequest req, HttpServletResponse res, String innerPath) throws Throwable {
final AbstractExController cont = object;
cont._init(req, res);
// String mname = req.getParameter(WebDriver.OPERATION_KEY);
String mname = innerPath;
if (StringKit.isNull(mname))
mname = "index";
final Method method = this.define.getClazz().getMethod(mname, para);
if (!method.getReturnType().equals(void.class)) {
throw new RuntimeException("Rule must return void");
}
}
|
万爽
| |
if (StringTool.isBlank(xxlApiProject.getName())) {
return new ReturnT(ReturnT.FAIL_CODE, "请输入项目名称");
}
if (StringTool.isBlank(xxlApiProject.getBaseUrlProduct())) {
return new ReturnT(ReturnT.FAIL_CODE, "请输入根地址(线上)");
}
if (!hasBizPermission(request, xxlApiProject.getBizId())) {
return new ReturnT(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通");
}
|
conventional
|
@RequestMapping("/update")
@ResponseBody
public ReturnT update(HttpServletRequest request, XxlApiProject xxlApiProject) {
XxlApiProject existProkect = xxlApiProjectDao.load(xxlApiProject.getId());
if (existProkect == null) {
return new ReturnT(ReturnT.FAIL_CODE, "更新失败,项目ID非法");
}
int ret = xxlApiProjectDao.update(xxlApiProject);
return (ret > 0) ? ReturnT.SUCCESS : ReturnT.FAIL;
}
|
万爽
| |
if (user == null) {
throw new UsernameNotFoundException("Cannot find user by username: " + userName);
}
|
conventional
|
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
// 先判断登陆用户是否存在
SysUser user = userRepository.findByUserName(userName);
List<SysAuthority> roleList = authorityRepository.findByUserId(user.getId());
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
if (roleList != null && roleList.size() > 0) {
roleList.forEach(r -> grantedAuthorities.add(new SimpleGrantedAuthority(r.getName())));
}
return new User(user.getUserName(), user.getPassword(), grantedAuthorities);
}
|
万爽
| |
Boolean<method*start>java.lang.Boolean<method*end> status = authService.domainAuth<method*start>com.asofdate.hauth.service.AuthService.domainAuth<method*end>(request, domainEntity.getDomain_id<method*start>com.asofdate.hauth.entity.DomainEntity.getDomain_id<method*end>(), "w").getStatus<method*start>com.asofdate.hauth.dto.AuthDTO.getStatus<method*end>();
if (!status) {
response.setStatus<method*start>javax.servlet.http.HttpServletResponse.setStatus<method*end>(403);
return Hret.error<method*start>com.asofdate.utils.Hret.error<method*end>(403, "你没有权限编辑域 [ " + domainEntity.getDomain_desc<method*start>com.asofdate.hauth.entity.DomainEntity.getDomain_desc<method*end>() + " ]", domainEntity);
}
|
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>)
@ResponseBody<method*start>org.springframework.web.bind.annotation.ResponseBody<method*end>
@ApiOperation<method*start>io.swagger.annotations.ApiOperation<method*end>(value<method*start>org.springframework.web.bind.annotation.RequestMapping.value<method*end> = "更新域定义信息", notes<method*start>io.swagger.annotations.ApiOperation.notes<method*end> = "更新域的详细信息,如:域名称,域状态")
@ApiImplicitParams<method*start>io.swagger.annotations.ApiImplicitParams<method*end>({ @ApiImplicitParam<method*start>io.swagger.annotations.ApiImplicitParam<method*end>(required<method*start>io.swagger.annotations.ApiImplicitParam.required<method*end> = true, name<method*start>io.swagger.annotations.ApiImplicitParam.name<method*end> = "domain_id", value<method*start>org.springframework.web.bind.annotation.RequestMapping.value<method*end> = "域编码"), @ApiImplicitParam<method*start>io.swagger.annotations.ApiImplicitParam<method*end>(required<method*start>io.swagger.annotations.ApiImplicitParam.required<method*end> = true, name<method*start>io.swagger.annotations.ApiImplicitParam.name<method*end> = "domain_desc", value<method*start>org.springframework.web.bind.annotation.RequestMapping.value<method*end> = "域描述信息") })
public String<method*start>java.lang.String<method*end> update(HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response, HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request) {
DomainEntity<method*start>com.asofdate.hauth.entity.DomainEntity<method*end> domainEntity = parse<method*start>com.asofdate.hauth.controller.DomainController.parse<method*end>(request);
RetMsg<method*start>com.asofdate.utils.RetMsg<method*end> retMsg = domainService.update<method*start>com.asofdate.hauth.service.DomainService.update<method*end>(domainEntity);
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);
}
|
万爽
| |
@RequiresPermissions<method*start>org.apache.shiro.authz.annotation.RequiresPermissions<method*end>("permission:update")
|
annotation
|
@ApiOperation<method*start>io.swagger.annotations.ApiOperation<method*end>(value<method*start>io.swagger.annotations.Api.value<method*end> = "更新权限", httpMethod<method*start>io.swagger.annotations.ApiOperation.httpMethod<method*end> = "POST", produces<method*start>io.swagger.annotations.ApiOperation.produces<method*end> = "application/json", response<method*start>io.swagger.annotations.ApiOperation.response<method*end> = Result.class)
@ResponseBody<method*start>org.springframework.web.bind.annotation.ResponseBody<method*end>
@RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>(value<method*start>io.swagger.annotations.Api.value<method*end> = "update", 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 Result<method*start>com.hunt.util.Result<method*end> update(@RequestParam<method*start>org.springframework.web.bind.annotation.RequestParam<method*end> long id, @RequestParam<method*start>org.springframework.web.bind.annotation.RequestParam<method*end> long groupId, @RequestParam<method*start>org.springframework.web.bind.annotation.RequestParam<method*end> String name, @RequestParam<method*start>org.springframework.web.bind.annotation.RequestParam<method*end> String code, @RequestParam<method*start>org.springframework.web.bind.annotation.RequestParam<method*end> String description) {
SysPermission<method*start>com.hunt.model.entity.SysPermission<method*end> sysPermission = sysPermissionService.selectById<method*start>com.hunt.service.SysPermissionService.selectById<method*end>(id);
if (sysPermission == null) {
return Result.error<method*start>com.hunt.util.Result.error<method*end>(ResponseCode.data_not_exist.getMsg<method*start>com.hunt.util.ResponseCode.getMsg<method*end>());
}
if (sysPermission.getIsFinal<method*start>com.hunt.model.entity.SysPermission.getIsFinal<method*end>() == 2) {
return Result.error<method*start>com.hunt.util.Result.error<method*end>(ResponseCode.can_not_edit.getMsg<method*start>com.hunt.util.ResponseCode.getMsg<method*end>());
}
boolean isExistName = sysPermissionService.isExistNameExcludeId<method*start>com.hunt.service.SysPermissionService.isExistNameExcludeId<method*end>(id, groupId, name);
if (isExistName) {
return Result.error<method*start>com.hunt.util.Result.error<method*end>(ResponseCode.name_already_exist.getMsg<method*start>com.hunt.util.ResponseCode.getMsg<method*end>());
}
boolean isExistCode = sysPermissionService.isExistCodeExcludeId<method*start>com.hunt.service.SysPermissionService.isExistCodeExcludeId<method*end>(id, groupId, code);
if (isExistCode) {
return Result.error<method*start>com.hunt.util.Result.error<method*end>(ResponseCode.code_already_exist.getMsg<method*start>com.hunt.util.ResponseCode.getMsg<method*end>());
}
sysPermission.setName<method*start>com.hunt.model.entity.SysPermission.setName<method*end>(name);
sysPermission.setCode<method*start>com.hunt.model.entity.SysPermission.setCode<method*end>(code);
sysPermission.setDescription<method*start>com.hunt.model.entity.SysPermission.setDescription<method*end>(description);
sysPermission.setSysPermissionGroupId<method*start>com.hunt.model.entity.SysPermission.setSysPermissionGroupId<method*end>(groupId);
sysPermissionService.update<method*start>com.hunt.service.SysPermissionService.update<method*end>(sysPermission);
return Result.success<method*start>com.hunt.util.Result.success<method*end>();
}
|
万爽
| |
if (StrUtil.isEmpty(authorizeToken)) {
return;
}
if (authorizeToken.length() < 6) {
DefaultSystemLog.getLog().error("", new JpomRuntimeException("配置的授权token长度小于六位不生效"));
System.exit(-1);
}
int password = CheckPassword.checkPassword(authorizeToken);
if (password != 2) {
DefaultSystemLog.getLog().error("", new JpomRuntimeException("配置的授权token 需要包含数字,字母,符号的组合"));
System.exit(-1);
}
|
conventional
|
@PreLoadMethod
private static void check() {
String authorizeToken = ServerExtConfigBean.getInstance().getAuthorizeToken();
}
|
肖敬先
| |
badzk.addAuthInfo(authentication_type, badAuthentication.getBytes());
if (stat != null)
|
conventional
|
static void deleteNodeByBadAuthentication() throws Exception {
String prefix = "[使用错误的授权信息]";
try {
System.out.println(prefix + "删除节点:" + PATH_DEL);
ZooKeeper badzk = new ZooKeeper(CONNECT_ADDR, 2000, null);
Thread.sleep(2000);
Stat stat = badzk.exists(PATH_DEL, false);
badzk.delete(PATH_DEL, -1);
System.out.println(prefix + "删除成功");
} catch (Exception e) {
System.err.println(prefix + "删除失败,原因是:" + e.getMessage());
}
}
|
肖敬先
| |
if (!isStatAccessPermissionSet<method*start>experment.zju.statistics.MainActivity.isStatAccessPermissionSet<method*end>(MainActivity.this)) {
// 查看是否为应用设置了权限
startActivity<method*start>android.support.v7.app.AppCompatActivity.startActivity<method*end>(new Intent<method*start>android.content.Intent<method*end>(Settings.ACTION_USAGE_ACCESS_SETTINGS<method*start>android.provider.Settings.ACTION_USAGE_ACCESS_SETTINGS<method*end>));
// 显示toast信息
Toast<method*start>android.widget.Toast<method*end> toast = Toast.makeText<method*start>android.widget.Toast.makeText<method*end>(getApplicationContext<method*start>android.support.v7.app.AppCompatActivity.getApplicationContext<method*end>(), "请开启应用统计的使用权限", Toast.LENGTH_SHORT<method*start>android.widget.Toast.LENGTH_SHORT<method*end>);
toast.show<method*start>android.widget.Toast.show<method*end>();
}
|
conventional
|
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.OpenButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
if (!isStatAccessPermissionSet(MainActivity.this)) {
// 查看是否为应用设置了权限
startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
// 显示toast信息
Toast toast = Toast.makeText(getApplicationContext(), "请开启应用统计的使用权限", Toast.LENGTH_SHORT);
toast.show();
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
});
}
|
肖敬先
| |
if (adminId.equals(1L)) {
authRules.add("admin");
return authRules;
}
|
conventional
|
@Override
public List<String> listRuleByAdminId(Long adminId) {
List<String> authRules = new ArrayList<>();
// 如果存在,先从缓存中获取权限
String aarKey = String.format(CacheConstant.ADMIN_AUTH_RULES, adminId);
if (CacheUtils.hasKey(aarKey)) {
return new ArrayList<>(CacheUtils.sGetMembers(aarKey));
}
log.info("开始获取数据库中的用户的权限规则列表");
// 获取角色ids
List<AuthRoleAdmin> authRoleAdmins = authRoleAdminService.listByAdminId(adminId);
List<Long> roleIds = authRoleAdmins.stream().map(AuthRoleAdmin::getRoleId).collect(Collectors.toList());
// 角色授权列表
List<AuthPermission> authPermissions = authPermissionService.listByRoleIdIn(roleIds);
List<Long> permissionRuleIds = authPermissions.stream().map(AuthPermission::getPermissionRuleId).collect(Collectors.toList());
// 获取授权的规则
List<AuthPermissionRule> authPermissionRules = authPermissionRuleService.listByIdIn(permissionRuleIds);
// 获取权限列表
authRules = authPermissionRules.stream().map(AuthPermissionRule::getName).collect(Collectors.toList());
// 如果为空,则添加一个空值
if (authRules.isEmpty()) {
authRules.add("");
}
String[] strings = authRules.toArray(new String[0]);
CacheUtils.sAdd(aarKey, strings);
// 两小时后过期
CacheUtils.expire(aarKey, 7200L);
return authRules;
}
|
肖敬先
| |
if (isVerification(request, handler, token)) {
return true;
}
|
conventional
|
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (handler instanceof HandlerMethod) {
SSOToken token = SSOHelper.attrToken(request);
if (token == null) {
return true;
}
try {
return unauthorizedAccess(request, response);
} catch (Exception e) {
throw AoomsExceptions.create(e.getMessage(), e);
}
}
return true;
}
|
肖敬先
| |
@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);
}
|
肖敬先
| |
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (iUserService.checkRole(user)) {
// 更新categoryName
return Service.updateCategoryName(categoryId, categoryName);
} else {
return Response.createByErrorMessage("无权限操作,需要管理员权限");
}
|
conventional
|
@RequestMapping("set_category_name.do")
public ServerResponse setCategoryName(HttpSession session, Integer categoryId, String categoryName) {
// 更新categoryName
return iCategoryService.updateCategoryName(categoryId, categoryName);
}
|
肖敬先
| |
if (SSOConfig.getInstance().isPermissionUri()) {
String uri = request.getRequestURI();
if (uri == null || this.getAuthorization().isPermitted(token, uri)) {
return true;
}
}
if (pm != null) {
if (pm.action() == Action.Skip) {
return true;
} else if (!"".equals(pm.value()) && this.getAuthorization().isPermitted(token, pm.value())) {
return true;
}
} else if (this.isNothingAnnotationPass()) {
return true;
}
return false;
|
conventional
|
protected boolean isVerification(HttpServletRequest request, Object handler, SSOToken token) {
if (SSOConfig.getInstance().isPermissionUri()) {
String uri = request.getRequestURI();
if (uri == null || this.getAuthorization().isPermitted(token, uri)) {
return true;
}
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
Permission pm = method.getAnnotation(Permission.class);
if (pm != null) {
if (pm.action() == Action.Skip) {
return true;
} else if (!"".equals(pm.value()) && this.getAuthorization().isPermitted(token, pm.value())) {
return true;
}
} else if (this.isNothingAnnotationPass()) {
return true;
}
return false;
}
|
肖敬先
| |
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 "为企业用户授权角色成功";
}
}
|
conventional
|
@Override
public String rolesToUser(SysEnterpriseUserReq sysEnterpriseUserReq) {
UserGroupDO uuid = userGroupMapper.uuid(sysEnterpriseUserReq.getEnterpriseUuid());
if (uuid == null) {
throw BizException.fail("用户所在的企业不存在");
}
UserDO userDO = userMapper.uuid(sysEnterpriseUserReq.getUuid());
if (null == userDO) {
throw BizException.fail("待授权的用户不存在");
}
List<Long> roles = sysEnterpriseUserReq.getRoleIds();
List<Long> originAclIdList = authorityMapper.rolesByUserId(userDO.getId());
RedisUser redisUser = this.redisUser();
updateUserRoles(userDO.getId(), roles, redisUser, userDO.getTenantId());
return "为企业用户授权角色成功";
}
|
肖敬先
| |
if (mForbidDialog == null) {
mForbidDialog = new AlertDialog.Builder(this).setTitle("权限被禁止").setMessage("需要获取权限,否则无法正常使用功能;设置路径:设置-应用-权限").setPositiveButton("确定", null).setNegativeButton("取消", null).setCancelable(false).create();
|
conventional
|
protected void showForbidPermissionDialog() {
if (mForbidDialog == null) {
mForbidDialog = new AlertDialog.Builder(this).setTitle("权限被禁止").setMessage("需要获取权限,否则无法正常使用功能;设置路径:设置-应用-权限").setPositiveButton("确定", null).setNegativeButton("取消", null).setCancelable(false).create();
mForbidDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button positionButton = mForbidDialog.getButton(AlertDialog.BUTTON_POSITIVE);
Button negativeButton = mForbidDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
positionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
IntentUtils.openActivityApplyCenter(PermissionActivity.this);
}
});
negativeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mForbidDialog.dismiss();
finish();
}
});
}
});
mForbidDialog.show();
} else if (!mForbidDialog.isShowing()) {
mForbidDialog.show();
}
}
|
肖敬先
| |
@AuthRuleAnnotation("admin/auth/role/delete")
|
annotation
|
@PostMapping("/admin/auth/role/delete")
public BaseResponse<method*start>com.lmxdawn.api.common.res.BaseResponse<method*end> delete(@RequestBody AuthRoleSaveRequest authRoleSaveRequest) {
if (authRoleSaveRequest.getId<method*start>com.lmxdawn.api.admin.req.auth.AuthRoleSaveRequest.getId<method*end>() == null) {
return ResultVOUtils.error<method*start>com.lmxdawn.api.common.util.ResultVOUtils.error<method*end>(ResultEnum.PARAM_VERIFY_FALL<method*start>com.lmxdawn.api.common.enums.ResultEnum.PARAM_VERIFY_FALL<method*end>);
}
boolean b = authRoleService.deleteById<method*start>com.lmxdawn.api.admin.service.auth.AuthRoleService.deleteById<method*end>(authRoleSaveRequest.getId<method*start>com.lmxdawn.api.admin.req.auth.AuthRoleSaveRequest.getId<method*end>());
if (!b) {
return ResultVOUtils.error<method*start>com.lmxdawn.api.common.util.ResultVOUtils.error<method*end>(ResultEnum.NOT_NETWORK<method*start>com.lmxdawn.api.common.enums.ResultEnum.NOT_NETWORK<method*end>);
}
// TODO 删除角色后先前授权的缓存不会消失
// 再删除之前的授权
authPermissionService.deleteByRoleId<method*start>com.lmxdawn.api.admin.service.auth.AuthPermissionService.deleteByRoleId<method*end>(authRoleSaveRequest.getId<method*start>com.lmxdawn.api.admin.req.auth.AuthRoleSaveRequest.getId<method*end>());
return ResultVOUtils.success<method*start>com.lmxdawn.api.common.util.ResultVOUtils.success<method*end>();
}
|
肖敬先
| |
if (perms != null && perms.length > 0) {
if (perms.length == 1) {
if (!subject.isCheck(perms[0])) {
isPermitted = false;
}
} else {
if (!subject.isCheck(perms)) {
isPermitted = false;
}
}
}
return getPermitted;
}
|
annotation
|
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
Subject subject = getSubject(request, response);
String[] perms = (String[]) mappedValue;
boolean getPermitted = true;
return getPermitted;
}
|
肖敬先
| |
if (isRootUser()) {
// root用户拥有所有权限点
return sysAclDao.getAll();
}
|
conventional
|
public List getUserAclList(int userId) {
List userRoleIdList = sysRoleUserDao.getRoleIdListByUserId(userId);
if (CollectionUtils.isEmpty(userRoleIdList)) {
return Lists.newArrayList();
}
List userAclIdList = sysRoleAclDao.getAclIdListByRoleIdList(userRoleIdList);
if (CollectionUtils.isEmpty(userAclIdList)) {
return Lists.newArrayList();
}
return sysAclDao.getByIdList(userAclIdList);
}
|
肖敬先
| |
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;
}
|
肖敬先
| |
Subject subject = SecurityUtils.getSubject();
if (subject.hasRole("admin")) {
adminService.deleteUsers(username);
return BlogJSONResult.ok();
} else {
return BlogJSONResult.errorRolesMsg("无权限");
}
|
conventional
|
@GetMapping("delUsers")
public BlogJSONResult delUsers(@RequestParam(value = "username") String username) {
return BlogJSONResult.ok();
}
|
肖敬先
| |
if (!isStatAccessPermissionSet(MainActivity.this)) {
}
|
conventional
|
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.OpenButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
// 查看是否为应用设置了权限
startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
// 显示toast信息
Toast toast = Toast.makeText(getApplicationContext(), "请开启应用统计的使用权限", Toast.LENGTH_SHORT);
toast.show();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
});
}
|
肖敬先
| |
if (!this.client.doesBucketExist(bucketName)) {
throw new OssApiException("[阿里云OSS] 无法获取文件的访问权限!Bucket不存在:" + bucketName);
}
if (!this.client.doesObjectExist(bucketName, fileName)) {
throw new OssApiException("[阿里云OSS] 无法获取文件的访问权限!文件不存在:" + bucketName + "/" + fileName);
}
|
conventional
|
public Object getFileAcl(String fileName, String bucketName) {
try {
return this.client.getObjectAcl(bucketName, fileName).getPermission();
} finally {
this.shutdown();
}
}
|
肖敬先
| |
if (oConvertUtils.isEmpty(token)) {
return Result.error("TOKEN不允许为空!");
}
}
|
conventional
|
@RequestMapping(value = "/getUserPermissionByToken", method = RequestMethod.GET)
public Result getUserPermissionByToken(@RequestParam(name = "token", required = true) String token) {
Result result = new Result();
try {
log.info(" ------ 通过令牌获取用户拥有的访问菜单 ---- TOKEN ------ " + token);
String username = JwtUtil.getUsername(token);
List<SysPermission> metaList = sysPermissionService.queryByUser(username);
// 添加首页路由
PermissionDataUtil.addIndexPage(metaList);
JSONObject json = new JSONObject();
JSONArray menujsonArray = new JSONArray();
this.getPermissionJsonArray(menujsonArray, metaList, null);
JSONArray authjsonArray = new JSONArray();
this.getAuthJsonArray(authjsonArray, metaList);
LambdaQueryWrapper query = new LambdaQueryWrapper();
query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
query.eq(SysPermission::getMenuType, CommonConstant.MENU_TYPE_2);
List<SysPermission> allAuthList = sysPermissionService.list(query);
JSONArray allauthjsonArray = new JSONArray();
this.getAllAuthJsonArray(allauthjsonArray, allAuthList);
json.put("menu", menujsonArray);
json.put("auth", authjsonArray);
json.put("allAuth", allauthjsonArray);
result.setResult(json);
result.success("查询成功");
} catch (Exception e) {
result.error500("查询失败:" + e.getMessage());
log.error(e.getMessage(), e);
}
return result;
}
|
肖敬先
| |
if (StringTool.isBlank(xxlApiGroup.getName())) {
return new ReturnT(ReturnT.FAIL_CODE, "请输入“分组名称”");
}
XxlApiProject xxlApiProject = xxlApiProjectDao.load(xxlApiGroup.getProjectId());
if (!hasBizPermission(request, xxlApiProject.getBizId())) {
return new ReturnT(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通");
}
|
conventional
|
@RequestMapping("/add")
@ResponseBody
public ReturnT<String> add(HttpServletRequest request, XxlApiGroup xxlApiGroup) {
int ret = xxlApiGroupDao.add(xxlApiGroup);
return (ret > 0) ? ReturnT.SUCCESS : ReturnT.FAIL;
}
|
肖敬先
| |
if (map == null || map.size() == 0 || !map.containsKey(0)) {
return "不具有任何权限,\n请找管理员分配权限";
}
|
conventional
|
public static String getAdminlteTree(Map map) {
StringBuffer menuString = new StringBuffer();
List list = map.get(0);
for (TSFunction function : list) {
if (!function.hasSubFunction(map)) {
menuString.append(getChildOfTree(function, 1, map));
} else {
menuString.append("<li fit=\"false\" border=\"false\">");
menuString.append("<a onclick=\"onSelectTree('" + function.getId() + "')\">" + getMutiLang(function.getFunctionName()) + "</a>");
menuString.append("</li>");
}
}
return menuString.toString();
}
|
肖敬先
| |
if (user.isAdmin()) {
roles.add("admin");
} else {
roles.addAll(roleService.selectRolePermissionByUserId(user.getId()));
}
|
conventional
|
public Set<java.util.Set<String>> getRolePermission(SysUser user) {
Set<java.util.Set<String>> roles = new HashSet<>();
// 管理员拥有所有权限
roles.add("admin");
return roles;
}
|
肖敬先
| |
boolean[] permitted = SecurityUtils.getSubject().isPermitted(name);
for (boolean b : permitted) {
// 如果有一个权限,就成功
if (b) {
return true;
}
}
return false;
|
conventional
|
public boolean hasPermissionOr(String... name) {
return false;
}
|
肖敬先
| |
// 如果没有审核权限,则不允许删除或发布。
if (!UserUtils.getSubject<method*start>com.iwc.shop.modules.sys.utils.UserUtils.getSubject<method*end>().isPermitted<method*start>org.apache.shiro.subject.Subject.isPermitted<method*end>("cms:article:audit")) {
addMessage(redirectAttributes, "你没有删除或发布权限");
}
|
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")
public String<method*start>java.lang.String<method*end> delete(Article<method*start>com.iwc.shop.modules.cms.entity.Article<method*end> article, String<method*start>java.lang.String<method*end> categoryId, @RequestParam<method*start>org.springframework.web.bind.annotation.RequestParam<method*end>(required<method*start>org.springframework.web.bind.annotation.RequestParam.required<method*end> = false) Boolean<method*start>java.lang.Boolean<method*end> isRe, RedirectAttributes<method*start>org.springframework.web.servlet.mvc.support.RedirectAttributes<method*end> redirectAttributes) {
articleService.delete<method*start>com.iwc.shop.modules.cms.service.ArticleService.delete<method*end>(article, isRe);
addMessage(redirectAttributes, (isRe != null && isRe ? "发布" : "删除") + "文章成功");
return "redirect:" + adminPath<method*start>com.iwc.shop.common.web.BaseController.adminPath<method*end> + "/cms/article/?repage&category.id=" + (categoryId != null ? categoryId : "");
}
|
肖敬先
| |
if (null == configAttributes || configAttributes.size() <= 0) {
return;
}
ConfigAttribute c;
String needRole;
for (ConfigAttribute configAttribute : configAttributes) {
c = configAttribute;
needRole = c.getAttribute();
// authentication 为在注释1 中循环添加到 GrantedAuthority 对象中的权限信息集合
for (GrantedAuthority ga : authentication.getAuthorities()) {
if (needRole.trim().equals(ga.getAuthority())) {
return;
}
}
}
throw new AccessDeniedException("访问被拒绝,权限不足");
}
|
conventional
|
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
}
|
肖敬先
| |
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
}
// 校验一下是否是管理员
if (iUserService.checkAdminRole(user).isSuccess()) {
// 增加我们处理分类的逻辑
return iCategoryService.addCategory(categoryName, parentId);
} else {
return ServerResponse.createByErrorMessage("无权限操作,需要管理员权限");
}
|
conventional
|
@RequestMapping("add_category.do")
public ServerResponse addCategory(HttpSession session, String categoryName, @RequestParam(value = "parentId", defaultValue = "0") int parentId) {
User user = (User) session.getAttribute(Const.CURRENT_USER);
// 增加我们处理分类的逻辑
return iCategoryService.addCategory(categoryName, parentId);
}
|
肖敬先
| |
if (imMgr.validation<method*start>com.tencent.qcloud.roomservice.logic.IMMgr.validation<method*end>(userID, token) != 0) {
rsp.setCode<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp.setCode<method*end>(7);
rsp.setMessage<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp.setMessage<method*end>("请求失败,鉴权失败");
log.error<method*start>org.slf4j.Logger.error<method*end>("logout失败:鉴权失败:" + "userID:" + userID);
return rsp;
}
|
conventional
|
@Override
public BaseRsp<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp<method*end> logout(String<method*start>java.lang.String<method*end> userID, String<method*start>java.lang.String<method*end> token) {
BaseRsp<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp<method*end> rsp = new BaseRsp<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp<method*end>();
if (userID == null || token == null) {
rsp.setCode<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp.setCode<method*end>(2);
rsp.setMessage<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp.setMessage<method*end>("请求失败,缺少参数");
log.error<method*start>org.slf4j.Logger.error<method*end>("logout失败:缺少参数:" + "userID:" + userID + ",token: " + token);
return rsp;
}
// 删除session
imMgr.delLoginSession<method*start>com.tencent.qcloud.roomservice.logic.IMMgr.delLoginSession<method*end>(userID);
return rsp;
}
|
肖敬先
| |
if (tbPermissionMapper.deleteByPrimaryKey(id) != 1) {
throw new XmallException("删除权限失败");
}
|
conventional
|
@Override
public int deletePermission(int id) {
TbRolePermExample example = new TbRolePermExample();
TbRolePermExample.Criteria criteria = example.createCriteria();
criteria.andPermissionIdEqualTo(id);
tbRolePermMapper.deleteByExample(example);
return 1;
}
|
肖敬先
| |
// 判断请求头是否包含授权TOKEN
if (null == token) {
// 判断COOKIE是否包含授权TOKEN
if (null != cookies) {
for (Cookie<method*start>javax.servlet.http.Cookie<method*end> cookie : cookies) {
if (BaseConstants.TOKEN_KEY.toLowerCase<method*start>java.lang.String.toLowerCase<method*end>().equals<method*start>java.lang.String.equals<method*end>(cookie.getName<method*start>javax.servlet.http.Cookie.getName<method*end>().toLowerCase<method*start>java.lang.String.toLowerCase<method*end>())) {
token = cookie.getValue<method*start>javax.servlet.http.Cookie.getValue<method*end>();
}
}
}
}
if (null == token) {
userInfo.setErrCode<method*start>org.superboot.base.BaseToken.setErrCode<method*end>(StatusCode.TOKEN_NOT_FIND<method*start>org.superboot.base.StatusCode.TOKEN_NOT_FIND<method*end>);
} else {
userInfo = redisUtils.getTokenInfo<method*start>org.superboot.common.pub.Pub_RedisUtils.getTokenInfo<method*end>(token);
if (null == userInfo) {
userInfo = new BaseToken<method*start>org.superboot.base.BaseToken<method*end>();
userInfo.setErrCode<method*start>org.superboot.base.BaseToken.setErrCode<method*end>(StatusCode.TOKEN_INVALID<method*start>org.superboot.base.StatusCode.TOKEN_INVALID<method*end>);
}
}
|
conventional
|
public BaseToken<method*start>org.superboot.base.BaseToken<method*end> getTokenInfo(HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request) {
BaseToken<method*start>org.superboot.base.BaseToken<method*end> userInfo = new BaseToken<method*start>org.superboot.base.BaseToken<method*end>();
String<method*start>java.lang.String<method*end> token = request.getHeader<method*start>javax.servlet.http.HttpServletRequest.getHeader<method*end>(BaseConstants.TOKEN_KEY<method*start>org.superboot.base.BaseConstants.TOKEN_KEY<method*end>);
if (null == token) {
Cookie<method*start>javax.servlet.http.Cookie<method*end>[] cookies = request.getCookies<method*start>javax.servlet.http.HttpServletRequest.getCookies<method*end>();
if (null != cookies) {
for (Cookie<method*start>javax.servlet.http.Cookie<method*end> cookie : cookies) {
if (BaseConstants.TOKEN_KEY.toLowerCase<method*start>java.lang.String.toLowerCase<method*end>().equals<method*start>java.lang.String.equals<method*end>(cookie.getName<method*start>javax.servlet.http.Cookie.getName<method*end>().toLowerCase<method*start>java.lang.String.toLowerCase<method*end>())) {
token = cookie.getValue<method*start>javax.servlet.http.Cookie.getValue<method*end>();
}
}
}
}
}
return userInfo;
}
|
肖敬先
| |
DynamicData dynamicData1 = DynamicData.getDynamicData<method*start>io.jpom.permission.DynamicData.getDynamicData<method*end>(classFeature);
if (dynamicData1 == null) {
// 如果不是没有动态权限 就默认通过
return false;
}
|
conventional
|
public boolean errorDynamicPermission(UserModel<method*start>io.jpom.model.data.UserModel<method*end> userModel, ClassFeature<method*start>io.jpom.plugin.ClassFeature<method*end> classFeature, String<method*start>java.lang.String<method*end> dataId) {
if (JpomApplication.SYSTEM_ID.equals<method*start>java.lang.String.equals<method*end>(dataId)) {
// 系统构建id
return false;
}
if (userModel.isSystemUser<method*start>io.jpom.model.data.UserModel.isSystemUser<method*end>()) {
return false;
}
Set<method*start>java.util.Set<method*end><String<method*start>java.lang.String<method*end>> roles = userModel.getRoles<method*start>io.jpom.model.data.UserModel.getRoles<method*end>();
if (roles == null || roles.isEmpty<method*start>java.util.Set.isEmpty<method*end>()) {
return true;
}
for (String<method*start>java.lang.String<method*end> role : roles) {
RoleModel item = getItem<method*start>io.jpom.common.BaseOperService.getItem<method*end>(role);
if (item == null) {
continue;
}
if (item.contains<method*start>io.jpom.model.data.RoleModel.contains<method*end>(classFeature, dataId)) {
return false;
}
}
return true;
}
|
肖敬先
| |
if (!isAuthorizationEnabled()) {
return;
}
if (role == null) {
continue;
}
if (role.getIsRelatingToNamespace() && !namespace.equals(userRole.getNamespace())) {
continue;
}
List<RolePermission> rolePermissions = role.getRolePermissions();
if (rolePermissions == null || rolePermissions.isEmpty()) {
continue;
}
for (RolePermission rolePermission : rolePermissions) {
if (permissionKey.equals(rolePermission.getPermissionKey())) {
return;
}
}
if (userRoles != null) {
for (UserRole userRole : userRoles) {
Role role = userRole.getRole();
}
}
|
conventional
|
@Override
public void assertIsPermitted(String permissionKey, String userName, String namespace) throws SaturnJobConsoleException {
User user = getUser(userName);
List<UserRole> userRoles = user.getUserRoles();
throw new SaturnJobConsoleException(String.format("您没有操作所需要的权限:域:%s,权限:%s", namespace, permissionKey));
}
|
肖敬先
| |
if (!redisUser.getTenantId().equals(superAdminsService.getTeantId()) && roleDO.getSysRoleType().equals(RoleTypeEnum.admin.type)) {
throw BizException.fail("您无权限操作");
}
|
conventional
|
@Transactional
@Override
public String aclsToEnterprise(UserGroupPageReq userGroupPageReq) {
UserGroupDO uuid = userGroupMapper.uuid(userGroupPageReq.getUuid());
if (uuid == null) {
throw BizException.fail("待授权的企业不存在");
}
RoleDO roleDO = roleMapper.getVipAdminRole(uuid.getId(), RoleTypeEnum.admin.type);
if (null == roleDO) {
throw BizException.fail("请先为企业设置一个管理员用户");
}
RedisUser redisUser = this.redisUser();
List<AclDO> getAcls = userGroupPageReq.getAcls();
List<AclDO> redisAcls = Lists.newArrayList();
roleService.computeAclsToRole(getAcls, roleDO, redisUser, redisAcls);
roleRedisCacheServiceAsync.aclsToRoleToRedis(roleDO.getId(), redisAcls);
return "为企业授权成功";
}
|
肖敬先
| |
@PreAuthorize<method*start>org.springframework.security.access.prepost.PreAuthorize<method*end>("hasAnyRole('ADMIN','USER_ALL','USER_SELECT')")
|
annotation
|
@Log<method*start>com.dxj.log.annotation.Log<method*end>("查询用户")
@GetMapping<method*start>org.springframework.web.bind.annotation.GetMapping<method*end>(value<method*start>org.springframework.web.bind.annotation.GetMapping.value<method*end> = "/user")
public ResponseEntity<method*start>org.springframework.http.ResponseEntity<method*end><Map<method*start>java.util.Map<method*end><String<method*start>java.lang.String<method*end>, Object<method*start>java.lang.Object<method*end>>> getUsers(UserQuery<method*start>com.dxj.admin.query.UserQuery<method*end> query, Pageable<method*start>org.springframework.data.domain.Pageable<method*end> pageable) {
Set<method*start>java.util.Set<method*end><Long<method*start>java.lang.Long<method*end>> deptSet = new HashSet<method*start>java.util.HashSet<method*end><>();
Set<method*start>java.util.Set<method*end><Long<method*start>java.lang.Long<method*end>> result = new HashSet<method*start>java.util.HashSet<method*end><>();
if (!ObjectUtils.isEmpty<method*start>org.springframework.util.ObjectUtils.isEmpty<method*end>(query.getDeptId<method*start>com.dxj.admin.query.UserQuery.getDeptId<method*end>())) {
deptSet.add<method*start>java.util.Set.add<method*end>(query.getDeptId<method*start>com.dxj.admin.query.UserQuery.getDeptId<method*end>());
deptSet.addAll<method*start>java.util.Set.addAll<method*end>(dataScope.getDeptChildren<method*start>com.dxj.admin.config.DataScope.getDeptChildren<method*end>(deptService.findByPid<method*start>com.dxj.admin.service.DeptService.findByPid<method*end>(query.getDeptId<method*start>com.dxj.admin.query.UserQuery.getDeptId<method*end>())));
}
// 数据权限
Set<method*start>java.util.Set<method*end><Long<method*start>java.lang.Long<method*end>> deptIds = dataScope.getDeptIds<method*start>com.dxj.admin.config.DataScope.getDeptIds<method*end>();
// 查询条件不为空并且数据权限不为空则取交集
if (!CollectionUtils.isEmpty<method*start>org.springframework.util.CollectionUtils.isEmpty<method*end>(deptIds) && !CollectionUtils.isEmpty<method*start>org.springframework.util.CollectionUtils.isEmpty<method*end>(deptSet)) {
// 取交集
result.addAll<method*start>java.util.Set.addAll<method*end>(deptSet);
result.retainAll<method*start>java.util.Set.retainAll<method*end>(deptIds);
// 若无交集,则代表无数据权限
query.setDeptIds<method*start>com.dxj.admin.query.UserQuery.setDeptIds<method*end>(result);
if (result.size<method*start>java.util.Set.size<method*end>() == 0) {
return new ResponseEntity<method*start>org.springframework.http.ResponseEntity<method*end><>(PageUtil.toPage<method*start>com.dxj.common.util.PageUtil.toPage<method*end>(null, 0), HttpStatus.OK<method*start>org.springframework.http.HttpStatus.OK<method*end>);
} else
return new ResponseEntity<method*start>org.springframework.http.ResponseEntity<method*end><>(userService.queryAll<method*start>com.dxj.admin.service.UserService.queryAll<method*end>(query, pageable), HttpStatus.OK<method*start>org.springframework.http.HttpStatus.OK<method*end>);
// 否则取并集
} else {
result.addAll<method*start>java.util.Set.addAll<method*end>(deptSet);
result.addAll<method*start>java.util.Set.addAll<method*end>(deptIds);
query.setDeptIds<method*start>com.dxj.admin.query.UserQuery.setDeptIds<method*end>(result);
return new ResponseEntity<method*start>org.springframework.http.ResponseEntity<method*end><>(userService.queryAll<method*start>com.dxj.admin.service.UserService.queryAll<method*end>(query, pageable), HttpStatus.OK<method*start>org.springframework.http.HttpStatus.OK<method*end>);
}
}
|
肖敬先
| |
if (ValidateKit.isNullOrEmpty<method*start>cn.dreampie.ValidateKit.isNullOrEmpty<method*end>(permission)) {
throw new NullPointerException<method*start>java.lang.NullPointerException<method*end>("操作权限不存在");
}
|
conventional
|
public Role<method*start>org.icedog.function.user.model.Role<method*end> addPermission(Permission<method*start>org.icedog.function.user.model.Permission<method*end> permission) {
RolePermission<method*start>org.icedog.function.user.model.RolePermission<method*end> rolePermission = new RolePermission<method*start>org.icedog.function.user.model.RolePermission<method*end>();
rolePermission.set<method*start>cn.dreampie.web.model.Model.set<method*end>("role_id", this.get<method*start>cn.dreampie.web.model.Model.get<method*end>("id"));
rolePermission.set<method*start>cn.dreampie.web.model.Model.set<method*end>("permission_id", permission.get<method*start>cn.dreampie.web.model.Model.get<method*end>("id"));
rolePermission.save<method*start>cn.dreampie.web.model.Model.save<method*end>();
return this;
}
|
肖敬先
| |
// boolean authenticated = getSubjct().isAuthenticated();
|
conventional
|
@GetMapping("/login")
public String login() {
// 判断是记住登陆还是授权登陆
UserDO user = getUser();
if (user != null) {
return "redirect:management/index";
}
return "management/login";
}
|
肖敬先
| |
if (count > 0) {
return CommonResult.success(count);
}
|
conventional
|
@ApiOperation
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id, @RequestBody UmsPermission permission) {
int count = permissionService.update(id, permission);
return CommonResult.failed();
}
|
肖敬先
| |
if (imMgr.validation<method*start>com.tencent.qcloud.roomservice.logic.IMMgr.validation<method*end>(userID, token) != 0) {
rsp.setCode<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp.setCode<method*end>(7);
rsp.setMessage<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp.setMessage<method*end>("请求失败,鉴权失败");
log.error<method*start>org.slf4j.Logger.error<method*end>("getRoomList失败:鉴权失败:" + "userID:" + userID);
return rsp;
}
|
conventional
|
@Override
public GetRoomListRsp<method*start>com.tencent.qcloud.roomservice.pojo.Response.GetRoomListRsp<method*end> getRoomList(String<method*start>java.lang.String<method*end> userID, String<method*start>java.lang.String<method*end> token, GetRoomListReq<method*start>com.tencent.qcloud.roomservice.pojo.Request.GetRoomListReq<method*end> req, int type) {
GetRoomListRsp<method*start>com.tencent.qcloud.roomservice.pojo.Response.GetRoomListRsp<method*end> rsp = new GetRoomListRsp<method*start>com.tencent.qcloud.roomservice.pojo.Response.GetRoomListRsp<method*end>();
if (userID == null || token == null) {
rsp.setCode<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp.setCode<method*end>(2);
rsp.setMessage<method*start>com.tencent.qcloud.roomservice.pojo.Response.BaseRsp.setMessage<method*end>("请求失败,缺少参数");
log.error<method*start>org.slf4j.Logger.error<method*end>("getRoomList失败:缺少参数:" + "userID:" + userID + ",token: " + token + ",type: " + type);
return rsp;
}
rsp.setList<method*start>com.tencent.qcloud.roomservice.pojo.Response.GetRoomListRsp.setList<method*end>(roomMgr.getList<method*start>com.tencent.qcloud.roomservice.logic.RoomMgr.getList<method*end>(req.getCnt<method*start>com.tencent.qcloud.roomservice.pojo.Request.GetRoomListReq.getCnt<method*end>(), req.getIndex<method*start>com.tencent.qcloud.roomservice.pojo.Request.GetRoomListReq.getIndex<method*end>(), true, type));
return rsp;
}
|
肖敬先
| |
SysUser user = this.selectById(userId);
if (user == null) {
throw RequestException.fail("用户不存在");
}
SysUser sysUser = new SysUser();
BeanUtils.copyProperties(SecurityUtils.getSubject().getPrincipal(), sysUser);
if (user.getUsername().equals(sysUser.getUsername())) {
throw RequestException.fail("不能锁定自己的账户");
}
|
conventional
|
@Override
public void statusChange(String userId, Integer status) {
SysUser user = this.selectById(userId);
user.setStatus(status);
try {
this.updateById(user);
// 若为0 需要进行清除登陆授权以及权限信息
/*if(status==0){
}*/
shiroService.clearAuthByUserId(userId, true, true);
} catch (Exception e) {
throw RequestException.fail("操作失败", e);
}
}
|
肖敬先
| |
// 权限
XxlApiProject project = xxlApiProjectDao.load(oldVo.getProjectId());
if (!hasBizPermission(request, project.getBizId())) {
return new ReturnT(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通");
}
|
conventional
|
@RequestMapping("/update")
@ResponseBody
public ReturnT<String> update(HttpServletRequest request, XxlApiDocument xxlApiDocument) {
XxlApiDocument oldVo = xxlApiDocumentDao.load(xxlApiDocument.getId());
if (oldVo == null) {
return new ReturnT(ReturnT.FAIL_CODE, "操作失败,接口ID非法");
}
xxlApiDocument.setProjectId(oldVo.getProjectId());
xxlApiDocument.setStarLevel(oldVo.getStarLevel());
xxlApiDocument.setAddTime(oldVo.getAddTime());
int ret = xxlApiDocumentDao.update(xxlApiDocument);
return (ret > 0) ? ReturnT.SUCCESS : ReturnT.FAIL;
}
|
肖敬先
| |
Subject subject = SecurityUtils.getSubject();
if (subject.hasRole("admin")) {
PagedResult allUsers = adminService.getAllFriendsUrl(pageSize, pageNum);
return BlogJSONResult.ok(allUsers);
} else {
return BlogJSONResult.errorRolesMsg("无权限");
}
|
conventional
|
@GetMapping("getAllFriendsUrl")
public BlogJSONResult getAllFriendsUrl(@RequestParam(value = "pageSize") Integer pageSize, @RequestParam(value = "pageNum") Integer pageNum) {
PagedResult allUsers = adminService.getAllFriendsUrl(pageSize, pageNum);
return BlogJSONResult.ok(allUsers);
}
|
肖敬先
| |
int count = permissionService.delete(ids);
if (count > 0) {
return CommonResult.success(count);
}
|
conventional
|
@ApiOperation("根据id批量删除权限")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@RequestParam("ids") List<Long> ids) {
int count = permissionService.delete(ids);
return CommonResult.failed();
}
|
肖敬先
| |
checkNotNull(username, "Username could not be null.");
checkNotNull(password, "Password could not be null.");
|
conventional
|
public static void login(String username, String password, boolean rememberMe) {
Principal principal = credentials.getPrincipal(username);
if (principal == null) {
throw new HttpException(HttpMessage.USERNAME_NOT_FOUND);
}
boolean match;
String salt = principal.getSalt();
if (salt != null && !salt.isEmpty()) {
match = passwordService.match(password, principal.getPassword(), salt);
} else {
match = passwordService.match(password, principal.getPassword());
}
if (match) {
// 授权用户
// 时间
long expires = -1;
if (rememberMe) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, rememberDay);
expires = cal.getTimeInMillis();
}
// 授权用户
authenticateAs(username, expires);
logger.debug("Session authentication as " + username);
} else {
throw new HttpException(HttpMessage.PASSWORD_ERROR);
}
}
|
肖敬先
| |
UserPo user = (UserPo) request.getSession().getAttribute(RtConstant.KEY_USER_PO);
if (user.isCanReadGateway()) {
String gatewayId = requestVo.getVoData();
GatewayPo gatewayPo = gatewayService.getGatewayByGatewayId(gatewayId);
responseVo.setVoData(gatewayPo);
} else {
logger.error("根据ID查询网关错误,用户{}没有权限", user.getUsername());
responseVo.setStatus(false);
responseVo.setMessage("根据ID查询网关错误,用户没有权限");
}
|
conventional
|
@RequestMapping("/getGatewayByGatewayId")
@ResponseBody
public ResponseVo<GatewayPo> getGatewayByGatewayId(HttpServletRequest request, @RequestBody RequestVo<String> requestVo) {
ResponseVo<GatewayPo> responseVo = new ResponseVo<>();
try {
GatewayPo gatewayPo = gatewayService.getGatewayByGatewayId(gatewayId);
responseVo.setVoData(gatewayPo);
} catch (Exception e) {
logger.error("根据ID查询网关错误", e);
responseVo.setStatus(false);
responseVo.setMessage(e.getMessage());
}
return responseVo;
}
|
肖敬先
| |
if (AndroidVersionUtil.hasM<method*start>com.arialyy.frame.util.AndroidVersionUtil.hasM<method*end>()) {
if (requestCode == OnPermissionCallback.PERMISSION_ALERT_WINDOW<method*start>com.arialyy.frame.permission.OnPermissionCallback.PERMISSION_ALERT_WINDOW<method*end>) {
if (Settings.canDrawOverlays<method*start>android.provider.Settings.canDrawOverlays<method*end>(context)) {
// 在这判断是否请求权限成功
mPm.onSuccess<method*start>com.arialyy.frame.permission.PermissionManager.onSuccess<method*end>(Settings.ACTION_MANAGE_OVERLAY_PERMISSION<method*start>android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION<method*end>);
} else {
mPm.onFail<method*start>com.arialyy.frame.permission.PermissionManager.onFail<method*end>(Settings.ACTION_MANAGE_OVERLAY_PERMISSION<method*start>android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION<method*end>);
}
} else if (requestCode == OnPermissionCallback.PERMISSION_WRITE_SETTING<method*start>com.arialyy.frame.permission.OnPermissionCallback.PERMISSION_WRITE_SETTING<method*end>) {
if (Settings.System.canWrite<method*start>android.provider.Settings.System.canWrite<method*end>(context)) {
mPm.onSuccess<method*start>com.arialyy.frame.permission.PermissionManager.onSuccess<method*end>(Settings.ACTION_MANAGE_WRITE_SETTINGS<method*start>android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS<method*end>);
} else {
mPm.onFail<method*start>com.arialyy.frame.permission.PermissionManager.onFail<method*end>(Settings.ACTION_MANAGE_WRITE_SETTINGS<method*start>android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS<method*end>);
}
}
}
|
conventional
|
public void handleSpecialPermissionCallback(Context<method*start>android.content.Context<method*end> context, int requestCode, int resultCode, Intent<method*start>android.content.Intent<method*end> data) {
}
|
万爽
| |
@RequiresPermissions<method*start>org.apache.shiro.authz.annotation.RequiresPermissions<method*end>("oss:file:list")
|
annotation
|
@Log("文件上传列表")
@ApiOperation<method*start>io.swagger.annotations.ApiOperation<method*end>(value = "列表", notes<method*start>io.swagger.annotations.ApiOperation.notes<method*end> = "权限编码(oss:file:list)")
@GetMapping<method*start>org.springframework.web.bind.annotation.GetMapping<method*end>("/list")
public JsonResponse<method*start>com.king.common.utils.JsonResponse<method*end> list(@RequestParam<method*start>org.springframework.web.bind.annotation.RequestParam<method*end> Map<String<method*start>java.lang.String<method*end>, Object<method*start>java.lang.Object<method*end>> params) {
// 查询列表数据
Query<method*start>com.king.utils.Query<method*end> query = new Query(params, OssFile.class);
Page page = ossFileService.getPage<method*start>com.king.api.oss.OssFileService.getPage<method*end>(query);
return JsonResponse.success<method*start>com.king.common.utils.JsonResponse.success<method*end>(page);
}
|
万爽
| |
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
UIUtils.toast("授权成功");
}
|
conventional
|
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch(requestCode) {
case PERMISSIONS_REQUEST_CODE_STORAGE:
{
// If request is cancelled, the result arrays are empty.
case FilePickerDialog.EXTERNAL_READ_PERMISSION_GRANT:
{
if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
UIUtils.askForStoragePermission(this);
}
break;
}
}
}
|
万爽
| |
if (permission.getId() == null) {
throw new InvalidParamException("ID不存在");
}
final QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("code", permission.getCode());
queryWrapper.notIn("id", permission.getId());
if (this.count(queryWrapper) > 0) {
throw new InvalidParamException("权限标识: " + permission.getCode() + "已经存在");
}
|
conventional
|
@Override
public Boolean updatePermission(final SysPermission permission) {
return this.updateById(permission);
}
|
万爽
| |
if (user == null) {
return ServerResponse.createByErrorCodeMessage<method*start>com.mmall.common.ServerResponse.createByErrorCodeMessage<method*end>(ResponseCode.NEED_LOGIN.getCode<method*start>com.mmall.common.ResponseCode.getCode<method*end>(), "用户未登录,请登录管理员");
}
if (iUserService.checkAdminRole<method*start>com.mmall.service.IUserService.checkAdminRole<method*end>(user).isSuccess<method*start>com.mmall.common.ServerResponse.isSuccess<method*end>()) {
return iOrderService.manageDetail<method*start>com.mmall.service.IOrderService.manageDetail<method*end>(orderNo);
} else {
return ServerResponse.createByErrorMessage<method*start>com.mmall.common.ServerResponse.createByErrorMessage<method*end>("无权限操作");
}
|
conventional
|
@RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>("detail.do")
@ResponseBody
public ServerResponse<method*start>com.mmall.common.ServerResponse<method*end><OrderVo<method*start>com.mmall.vo.OrderVo<method*end>> orderDetail(HttpSession<method*start>javax.servlet.http.HttpSession<method*end> session, Long<method*start>java.lang.Long<method*end> orderNo) {
User<method*start>com.mmall.pojo.User<method*end> user = (User<method*start>com.mmall.pojo.User<method*end>) session.getAttribute<method*start>javax.servlet.http.HttpSession.getAttribute<method*end>(Const.CURRENT_USER<method*start>com.mmall.common.Const.CURRENT_USER<method*end>);
}
}
|
万爽
| |
if (checkRootUser && isRootUser()) {
return true;
}
if (acl == admin ) {
return true;
}
|
conventional
|
public boolean hasAcl(SysAcl acl, boolean checkRootUser) {
List<Integer> aclIdList = getCurrentUserAclIdListFromCache();
if (CollectionUtils.isEmpty(aclIdList)) {
return false;
}
return Sets.newHashSet(aclIdList).contains(acl.getId());
}
|
万爽
| |
// 检查权限
CheckAccess(comment);
|
conventional
|
@PostMapping(value = "/delete")
@ResponseBody
@SystemLog(description = "删除评论", type = LogTypeEnum.OPERATION)
public JsonResult moveToAway(@RequestParam("id") Long commentId) {
// 评论
Comment comment = commentService.get(commentId);
// 检查权限
if (Objects.equals(comment.getCommentStatus(), CommentStatusEnum.RECYCLE.getCode())) {
commentService.delete(commentId);
} else {
commentService.updateCommentStatus(commentId, CommentStatusEnum.RECYCLE.getCode());
}
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.delete-success"));
}
|
万爽
| |
@RequiresPermissions("配置管理:权限管理:后台用户管理")
|
annotation
|
@RequestMapping(value = "/menus/data", method = RequestMethod.GET)
@ResponseBody
public Object menusData(@ModelEntity(preFectchLazyFields = { "userR2Roles" }) User entity) {
List<Map<String, Object>> items = Lists.newArrayList();
List<Menu> userMenus = menuService.processUserMenu(entity);
for (Menu menu : userMenus) {
items.add(menu.buildMapDataForTreeDisplay());
}
return items;
}
|
肖敬先
| |
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
UIUtils.toast("授权成功");
}
break;
}
|
conventional
|
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch(requestCode) {
case PERMISSIONS_REQUEST_CODE_STORAGE:
{
case FilePickerDialog.EXTERNAL_READ_PERMISSION_GRANT:
{
if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
UIUtils.askForStoragePermission(this);
}
break;
}
}
}
|
肖敬先
| |
if (permission.getId() == null) {
throw new InvalidParamException("ID不存在");
}
final QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("code", permission.getCode());
queryWrapper.notIn("id", permission.getId());
if (this.count(queryWrapper) > 0) {
throw new InvalidParamException("权限标识: " + permission.getCode() + "已经存在");
}
|
conventional
|
@Override
public Boolean updatePermission(final SysPermission permission) {
return this.updateById(permission);
}
|
肖敬先
| |
if (user == null) {
return ServerResponse.createByErrorCodeMessage<method*start>com.mmall.common.ServerResponse.createByErrorCodeMessage<method*end>(ResponseCode.NEED_LOGIN.getCode<method*start>com.mmall.common.ResponseCode.getCode<method*end>(), "用户未登录,请登录管理员");
}
if (iUserService.checkAdminRole<method*start>com.mmall.service.IUserService.checkAdminRole<method*end>(user).isSuccess<method*start>com.mmall.common.ServerResponse.isSuccess<method*end>()) {
return iOrderService.manageDetail<method*start>com.mmall.service.IOrderService.manageDetail<method*end>(orderNo);
} else {
return ServerResponse.createByErrorMessage<method*start>com.mmall.common.ServerResponse.createByErrorMessage<method*end>("无权限操作");
}
|
conventional
|
@RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>("detail.do")
@ResponseBody
public ServerResponse<method*start>com.mmall.common.ServerResponse<method*end><OrderVo<method*start>com.mmall.vo.OrderVo<method*end>> orderDetail(HttpSession<method*start>javax.servlet.http.HttpSession<method*end> session, Long<method*start>java.lang.Long<method*end> orderNo) {
User<method*start>com.mmall.pojo.User<method*end> user = (User<method*start>com.mmall.pojo.User<method*end>) session.getAttribute<method*start>javax.servlet.http.HttpSession.getAttribute<method*end>(Const.CURRENT_USER<method*start>com.mmall.common.Const.CURRENT_USER<method*end>);
}
|
肖敬先
| |
if (checkRootUser && isRootUser()) {
return true;
}
if (acl == null || acl.getStatus() != Status.AVAILABLE.getCode()) {
// 不存在或未生效的,按照有权限处理
return true;
}
|
conventional
|
public boolean hasAcl(SysAcl acl, boolean checkRootUser) {
List<Integer> aclIdList = getCurrentUserAclIdListFromCache();
if (CollectionUtils.isEmpty(aclIdList)) {
return false;
}
return Sets.newHashSet(aclIdList).contains(acl.getId());
}
|
肖敬先
| |
Partner u = partnerMapper.getById(uid);
if (null == u) {
throw new UserNameNotFoundException("id不存在");
}
if (!u.getIsAdmin()) {
throw new NoPermissionException("普通用户无权登录管理系统");
}
|
conventional
|
@Override
public String getUsername(Integer uid, String password) throws UserNameNotFoundException, NoPermissionException {
return u.getPassword().equals(password) ? u.getUsername() : null;
}
|
肖敬先
| |
if (checkRootUser && isRootUser()) {
return true;
}
if (acl == null || acl.getStatus() != Status.AVAILABLE.getCode()) {
// 不存在或未生效的,按照有权限处理
return true;
}
|
conventional
|
@RequestMapping(value = { "/addContractByUnifiedSymbol" })
@ResponseBody
public ResponseVo<String> addContractByUnifiedSymbol(HttpServletRequest request, @RequestBody ContractPo contract) {
ResponseVo<String> responseVo = new ResponseVo<>();
try {
UserPo user = (UserPo) request
} catch (Exception e) {
logger.error("根据统一合约标识新增合约错误", e);
responseVo.setStatus(false);
responseVo.setMessage(e.getMessage());
}
return responseVo;
}
|
肖敬先
| |
if (!content.isHasDeleteRight<method*start>foo.cms.entity.main.Content.isHasDeleteRight<method*end>()) {
errors.addErrorCode<method*start>foo.common.web.springmvc.WebErrors.addErrorCode<method*end>("content.error.afterCheckDelete");
return errors;
}
|
conventional
|
private WebErrors<method*start>foo.cms.web.WebErrors<method*end> validateDelete(Integer<method*start>java.lang.Integer<method*end>[] ids, HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request) {
WebErrors<method*start>foo.cms.web.WebErrors<method*end> errors = WebErrors.create<method*start>foo.cms.web.WebErrors.create<method*end>(request);
CmsSite<method*start>foo.cms.entity.main.CmsSite<method*end> site = CmsUtils.getSite<method*start>foo.cms.web.CmsUtils.getSite<method*end>(request);
errors.ifEmpty<method*start>foo.common.web.springmvc.WebErrors.ifEmpty<method*end>(ids, "ids");
for (Integer<method*start>java.lang.Integer<method*end> id : ids) {
if (vldExist<method*start>foo.cms.action.admin.main.ContentAct.vldExist<method*end>(id, site.getId<method*start>foo.cms.entity.main.CmsSite.getId<method*end>(), errors)) {
return errors;
}
Content<method*start>foo.cms.entity.main.Content<method*end> content = manager.findById<method*start>foo.cms.manager.main.ContentMng.findById<method*end>(id);
// 是否有审核后删除权限。
}
return errors;
}
|
肖敬先
| |
if (user == null) {
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员");
}
if (iUserService.checkAdminRole(user).isSuccess()) {
// 填充业务
} else {
return ServerResponse.createByErrorMessage("无权限操作");
}
|
conventional
|
@RequestMapping("detail.do")
public ServerResponse<com.mmall.common.ServerResponse> getDetail(HttpSession session, Integer productId) {
User user = (User) session.getAttribute(Const.CURRENT_USER);
return iProductService.manageProductDetail(productId)
}
|
肖敬先
| |
wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
|
conventional
|
@GetMapping("/qrUserInfo")
public String qrUserInfo(@RequestParam("code") String code) {
WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
try {
wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
} catch (WxErrorException e) {
log.error("【微信网页授权】{}", e);
throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg());
}
log.info("wxMpOAuth2AccessToken={}", wxMpOAuth2AccessToken);
String openId = wxMpOAuth2AccessToken.getOpenId();
String redirectUrl = projectUrlConfig.getSell() + "/sell/seller/login";
return "redirect:" + redirectUrl + "?openid=" + openId;
}
|
肖敬先
| |
@RequiresPermissions("admin_user:edit")
|
annotation
|
@PostMapping("/edit")
public String edit(AdminUser adminUser) {
AdminUser _adminUser = getAdminUser();
if (StringUtils.isEmpty(adminUser.getPassword())) {
adminUser.setPassword(null);
} else {
adminUser.setPassword(new BCryptPasswordEncoder().encode(adminUser.getPassword()));
}
adminUserService.update(adminUser);
return redirect("/admin/admin_user/list");
}
|
肖敬先
| |
for (Object obj : pp.keySet()) {
String key = ((String) obj);
// 使用正则表达式验证 需要将 ? . 替换一下,并将通配符 * 处理一下
if (uri.matches(key.replace("?", "\\?").replace(".", "\\.").replace("*", ".*"))) {
// 如果 role 匹配
if (role.equals(pp.get(key))) {
authentificated = true;
break;
}
}
}
if (!authentificated) {
throw new RuntimeException(new AccountException("您无权访问该页面。请以合适的身份登陆后查看。"));
}
|
conventional
|
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
logger.info("{} 开始做过滤处理", this.getClass().getName());
HttpServletRequest request = (HttpServletRequest) req;
// 获取访问的路径,例如:admin.jsp
String requestURI = request.getRequestURI().replace(request.getContextPath() + "/", "");
// 获取 action 参数,例如:add
String action = req.getParameter("action");
action = action == null ? "" : action;
// 拼接成 URI。例如:log.do?action=list
String uri = requestURI + "?action=" + action;
// 从 session 中获取用户权限角色。
String role = (String) request.getSession(true).getAttribute("role");
role = role == null ? "guest" : role;
boolean authentificated = false;
// 开始检查该用户角色是否有权限访问 uri
// 继续运行
chain.doFilter(req, res);
}
|
肖敬先
| |
if (currentUserId != null)
|
conventional
|
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
// 取出鉴权时存入的登录用户Id
Long currentUserId = (Long) webRequest.getAttribute(C.CURRENT_USER_ID, RequestAttributes.SCOPE_REQUEST);
return userRepository.findById(currentUserId);
throw new MissingServletRequestPartException(C.CURRENT_USER_ID);
}
|
肖敬先
| |
if (StringUtils.isNotEmpty(token))
|
conventional
|
public LoginUser getLoginUser(HttpServletRequest request) {
String token = getToken(request);
Claims claims = parseToken(token);
String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
String userKey = getTokenKey(uuid);
return redisCacheService.getCacheObject(userKey);
return null;
}
|
肖敬先
| |
/* if (userId == null) {
return false;
}
User user = userService.getUserById(userId);
//超级管理员拥有所有执行器的权限
if (user != null && user.getRoleId() == 999) {
return true;
}
String agentIds = userService.getUserById(userId).getAgentIds();
agentIds = "," + agentIds + ",";
String thisAgentId = "," + jobAgentId + ",";
return agentIds.contains(thisAgentId);*/
|
conventional
|
private boolean checkJobPermission(Long jobAgentId, Long userId) {
String agentIds = userService.getUserById(userId).getAgentIds();
agentIds = "," + agentIds + ",";
String thisAgentId = "," + jobAgentId + ",";
return agentIds.contains(thisAgentId);*/
}
|
肖敬先
| |
Boolean isAdmin = loginUserIsAdmin();
|
conventional
|
private void basicCheck(Post post) {
if (post == null) {
throw new SensBusinessException(localeMessageUtil.getMessage("code.admin.common.post-not-exist"));
}
User user = getLoginUser();
if (!Objects.equals(post.getUserId(), user.getId()) && !isAdmin) {
throw new SensBusinessException(localeMessageUtil.getMessage("code.admin.common.permission-denied"));
}
}
|
肖敬先
| |
@RequiresPermissions("配置管理:权限管理:后台用户管理")
|
annotation
|
@RequestMapping(value = "/roles", method = RequestMethod.GET)
public String roles(User entity, Model model) {
Account account = entity.getAccount();
model.addAttribute(GlobalConstant.ROOT_VALUE, true);
if (Account.AuthTypeEnum.admin.equals(account.getAuthType()) && GlobalConstant.ROOT_VALUE.equals(account.getAuthUid())) {
model.addAttribute(GlobalConstant.ROOT_VALUE, true);
} else {
model.addAttribute(GlobalConstant.ROOT_VALUE, false);
model.addAttribute("roles", roleService.findAllCached());
}
return "admin/auth/user-roles";
}
|
肖敬先
| |
// valid
if (username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0) {
throw new RuntimeException("权限账号密码不可为空");
}
|
conventional
|
@Override
public void afterPropertiesSet() throws Exception {
// valid
// login token
// .getBytes("UTF-8")
String tokenTmp = DigestUtils.md5DigestAsHex(String.valueOf(username + "_" + password).getBytes());
tokenTmp = new BigInteger(1, tokenTmp.getBytes()).toString(16);
LOGIN_IDENTITY_TOKEN = tokenTmp;
}
|
肖敬先
| |
@RequiresPermissions("role:allotResource")
|
annotation
|
@PostMapping("/saveRoleResources")
@BussinessLog("分配角色拥有的资源")
public ResponseVO<method*start>com.zyd.blog.framework.object.ResponseVO<method*end> saveRoleResources(Long<method*start>java.lang.Long<method*end> roleId, String<method*start>java.lang.String<method*end> resourcesId) {
if (StringUtils.isEmpty<method*start>org.springframework.util.StringUtils.isEmpty<method*end>(roleId)) {
return ResultUtil.error<method*start>com.zyd.blog.util.ResultUtil.error<method*end>("error");
}
roleResourcesService.addRoleResources<method*start>com.zyd.blog.business.service.SysRoleResourcesService.addRoleResources<method*end>(roleId, resourcesId);
// 重新加载所有拥有roleId的用户的权限信息
shiroService.reloadAuthorizingByRoleId<method*start>com.zyd.blog.core.shiro.ShiroService.reloadAuthorizingByRoleId<method*end>(roleId);
return ResultUtil.success<method*start>com.zyd.blog.util.ResultUtil.success<method*end>("成功");
}
|
肖敬先
| |
if (imMgr.validation(userID, token) != 0) {
rsp.setCode(7);
rsp.setMessage("请求失败,鉴权失败");
log.error("getPushers失败:鉴权失败:" + "userID:" + userID);
return rsp;
}
|
conventional
|
@Override
public Room getPushers(String userID, String token, GetPushersReq req, int type) {
Room rsp = new Room();
if (userID == null || token == null) {
rsp.setCode(2);
rsp.setMessage("请求失败,缺少参数");
log.error("getPushers失败:缺少参数:" + "userID:" + userID + ",token: " + token + ",type: " + type);
return rsp;
}
rsp = roomMgr.getRoom(req.getRoomID(), type);
log.info("getRoom, type: " + type + " , roomID: " + req.getRoomID() + ", pushers counts : " + (rsp == null ? 0 : rsp.getPushersCnt()));
if (rsp == null) {
rsp = new Room();
rsp.setCode(1);
rsp.setMessage("请求失败,房间不存在");
log.error("getPushers失败:房间不存在:" + "userID:" + userID + ",roomID: " + req.getRoomID() + ",type: " + type);
}
return rsp;
}
|
肖敬先
| |
// 权限校验
XxlApiProject xxlApiProject = xxlApiProjectDao.load(existGroup.getProjectId());
if (!hasBizPermission(request, xxlApiProject.getBizId())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通");
}
|
conventional
|
@RequestMapping("/delete")
@ResponseBody
public ReturnT<String> delete(HttpServletRequest request, int id) {
// exist
XxlApiGroup existGroup = xxlApiGroupDao.load(id);
if (existGroup == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "更新失败,分组ID非法");
}
List<XxlApiDocument> documentList = xxlApiDocumentDao.loadByGroupId(id);
if (documentList != null && documentList.size() > 0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "拒绝删除,分组下存在接口,不允许强制删除");
}
int ret = xxlApiGroupDao.delete(id);
return (ret > 0) ? ReturnT.SUCCESS : ReturnT.FAIL;
}
|
肖敬先
| |
@RequiresPermissions("配置管理:权限管理:部门配置")
|
annotation
|
@RequestMapping(value = "/tree", method = RequestMethod.GET)
@ResponseBody
public MappingJacksonValue findTreeData(GroupPropertyFilter filter, Pageable pageable, HttpServletRequest request) {
filter.forceAnd(new PropertyFilter(MatchType.NE, "disabled", true));
Object value = departmentService.findByPage(filter, pageable);
final MappingJacksonValue jacksonValue = new MappingJacksonValue(value);
jacksonValue.setSerializationView(PropertyFilter.parseJsonView(request, JsonViews.Tree.class));
return jacksonValue;
}
|
肖敬先
| |
@RequiresPermissions(value = { "resource:batchDelete", "resource:delete" }, logical = Logical.OR)
@RequiresPermissions.Logical.OR
|
annotation
|
@PostMapping(value = "/remove")
@BussinessLog("删除资源")
public ResponseVO remove(Long[] ids) {
if (null == ids) {
return ResultUtil.error(500, "请至少选择一条记录");
}
for (Long id : ids) {
resourcesService.removeByPrimaryKey(id);
}
// 更新权限
shiroService.updatePermission();
return ResultUtil.success("成功删除 [" + ids.length + "] 个资源");
}
|
肖敬先
| |
BaseToken baseToken = getRedisUtils().getTokenInfo(token);
if (null != baseToken) {
// 判断用户的角色是否为空
if (!StringUtils.isBlank(baseToken.getUserRole())) {
// 获取系统有操作权限的角色
String[] roles = BaseConstants.ADMIN_ROLE_TYPE.split(",");
for (String role : roles) {
if (-1 != role.indexOf(baseToken.getUserRole())) {
return new BaseResponse(StatusCode.AUTHORIZATION_OPERATION);
}
}
}
}
|
conventional
|
@Override
public BaseResponse checkUserIsManager(String token) {
BaseToken baseToken = getRedisUtils().getTokenInfo(token);
return new BaseResponse(StatusCode.UNAUTHORIZED_OPERATION);
}
|
肖敬先
| |
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");
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>(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) {
RoleEntity<method*start>com.asofdate.hauth.entity.RoleEntity<method*end> roleEntity = parse<method*start>com.asofdate.hauth.controller.RoleController.parse<method*end>(request);
String<method*start>java.lang.String<method*end> domainId = roleEntity.getDomain_id<method*start>com.asofdate.hauth.entity.RoleEntity.getDomain_id<method*end>();
RetMsg<method*start>com.asofdate.utils.RetMsg<method*end> retMsg = roleService.add<method*start>com.asofdate.hauth.service.RoleService.add<method*end>(roleEntity);
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);
}
|
肖敬先
| |
if (!TextUtils.isEmpty(wxAuthorizationVo.getErrorMsg()))
|
conventional
|
@PostMapping(value = "/authentication")
public Response authentication(HttpServletRequest request, @RequestBody JSONObject json) {
// 邀请者的openId
String openId = json.getString("openId");
// 微信授权码
String code = json.getString("code");
AuthorizationVo wxAuthorizationVo = authenticationService.authentication(request, openId, code);
return Response.error(wxAuthorizationVo.getErrorCode(), wxAuthorizationVo.getErrorMsg());
}
|
肖敬先
| |
// 无权限
if (exception instanceof UnauthorizedException<method*start>org.apache.shiro.authz.UnauthorizedException<method*end>) {
return "/403.jsp";
}
// shiro session 过期
if (exception instanceof InvalidSessionException<method*start>org.apache.shiro.session.InvalidSessionException<method*end>) {
return "/error.jsp";
}
|
conventional
|
@ExceptionHandler<method*start>org.springframework.web.bind.annotation.ExceptionHandler<method*end>
public String<method*start>java.lang.String<method*end> exceptionHandler(HttpServletRequest<method*start>javax.servlet.http.HttpServletRequest<method*end> request, HttpServletResponse<method*start>javax.servlet.http.HttpServletResponse<method*end> response, Exception<method*start>java.lang.Exception<method*end> exception) {
_log.error<method*start>org.slf4j.Logger.error<method*end>("统一异常处理:", exception);
request.setAttribute<method*start>javax.servlet.http.HttpServletRequest.setAttribute<method*end>("ex", exception);
if (null != request.getHeader<method*start>javax.servlet.http.HttpServletRequest.getHeader<method*end>("X-Requested-With") && request.getHeader<method*start>javax.servlet.http.HttpServletRequest.getHeader<method*end>("X-Requested-With").equalsIgnoreCase<method*start>java.lang.String.equalsIgnoreCase<method*end>("XMLHttpRequest")) {
request.setAttribute<method*start>javax.servlet.http.HttpServletRequest.setAttribute<method*end>("requestHeader", "ajax");
}
return "/error.jsp";
}
|
肖敬先
| |
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员");
}
if (iUserService.checkAdminRole(user).isSuccess()) {
// 填充我们增加产品的业务逻辑
return iProductService.saveOrUpdateProduct(product);
} else {
return ServerResponse.createByErrorMessage("无权限操作");
}
|
conventional
|
@RequestMapping("save.do")
public ServerResponse<com.mmall.common.ServerResponse> productSave(HttpSession session, Product product) {
User user = (User) session.getAttribute(Const.CURRENT_USER);
return iProductService.saveOrUpdateProduct(product);
}
|
肖敬先
| |
@RequiresPermissions<method*start>org.apache.shiro.authz.annotation.RequiresPermissions<method*end>("permission:group:insert")
|
annotation
|
@ApiOperation<method*start>io.swagger.annotations.ApiOperation<method*end>(value<method*start>io.swagger.annotations.Api.value<method*end> = "新增权限组", httpMethod<method*start>io.swagger.annotations.ApiOperation.httpMethod<method*end> = "POST", produces<method*start>io.swagger.annotations.ApiOperation.produces<method*end> = "application/json", response<method*start>io.swagger.annotations.ApiOperation.response<method*end> = Result.class)
@ResponseBody<method*start>org.springframework.web.bind.annotation.ResponseBody<method*end>
@RequestMapping<method*start>org.springframework.web.bind.annotation.RequestMapping<method*end>(value<method*start>io.swagger.annotations.Api.value<method*end> = "group/insert", 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 Result<method*start>com.hunt.util.Result<method*end> insertGroup(@RequestParam<method*start>org.springframework.web.bind.annotation.RequestParam<method*end> String name, @RequestParam<method*start>org.springframework.web.bind.annotation.RequestParam<method*end> String description) {
boolean isExistGroupName = sysPermissionService.isExistGroupName<method*start>com.hunt.service.SysPermissionService.isExistGroupName<method*end>(name);
if (isExistGroupName) {
return Result.error<method*start>com.hunt.util.Result.error<method*end>(ResponseCode.name_already_exist.getMsg<method*start>com.hunt.util.ResponseCode.getMsg<method*end>());
}
SysPermissionGroup sysPermissionGroup = new SysPermissionGroup();
sysPermissionGroup.setName<method*start>com.hunt.model.entity.SysPermissionGroup.setName<method*end>(name);
sysPermissionGroup.setDescription<method*start>com.hunt.model.entity.SysPermissionGroup.setDescription<method*end>(description);
sysPermissionGroup.setIsFinal<method*start>com.hunt.model.entity.SysPermissionGroup.setIsFinal<method*end>(2);
long id = sysPermissionService.insertPermissionGroup<method*start>com.hunt.service.SysPermissionService.insertPermissionGroup<method*end>(sysPermissionGroup);
return Result.success<method*start>com.hunt.util.Result.success<method*end>(id);
}
|
肖敬先
| |
BaseConvert.checkPara(para);
|
conventional
|
public void update(DeptPara para) {
SysDept before = sysDeptDao.findById(para.getId());
Preconditions.checkNotNull(before, "待更新部门不存在");
if (checkExist(para.getParentId(), para.getName(), para.getId())) {
throw new ParaException("当前模块下存在相同名称的权限点");
}
SysDept after = DeptConvert.of(para);
after.setLevel(LevelUtil.calculateLevel(getLevel(para.getParentId()), para.getParentId()));
updateWithChild(before, after);
sysLogService.saveDeptLog(before, after);
}
|
肖敬先
| |
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_USER','ROLE_VISTOR')")
|
annotation
|
@PostMapping
public ResponseEntity<Response> createVote(Long blogId) {
try {
blogService.createVote(blogId);
} catch (ConstraintViolationException e) {
return ResponseEntity.ok().body(new Response(false, ConstraintViolationExceptionHandler.getMessage(e)));
} catch (Exception e) {
return ResponseEntity.ok().body(new Response(false, e.getMessage()));
}
return ResponseEntity.ok().body(new Response(true, "点赞成功", null));
}
|
肖敬先
| |
@RequiresPermissions("membership.permission:view")
|
annotation
|
@RequiresPermissions("membership.permission:view")
public Map<String, Object> list(final DataGridPager pager, final Integer id) {
final int moduleId = (id == null ? 0 : id);
final PageInfo pageInfo = pager.toPageInfo();
final List<Permission> list = this.service.getByPage(pageInfo, moduleId);
final Map<String, Object> modelMap = new HashMap<>(2);
modelMap.put("total", list.size());
modelMap.put("rows", list);
return modelMap;
}
|
肖敬先
| |
if (imMgr.validation(userID, token) != 0) {
rsp.setCode(7);
rsp.setMessage("请求失败,鉴权失败");
log.error("destroyRoom失败:鉴权失败:" + "userID:" + userID + ",roomID:" + req.getRoomID());
return rsp;
}
if (!roomMgr.isRoomCreator(req.getRoomID(), req.getUserID(), type)) {
rsp.setCode(3);
rsp.setMessage("不是房间主人,无法销毁房间");
log.error("destroyRoom失败:不是房间主人,无法销毁房间:" + ",userID:" + userID + ",roomID:" + req.getRoomID());
return rsp;
}
|
conventional
|
@Override
public BaseRsp destroyRoom(String userID, String token, DestroyRoomReq req, int type) {
BaseRsp rsp = new BaseRsp();
if (userID == null || token == null || req.getUserID() == null || req.getRoomID() == null) {
rsp.setCode(2);
rsp.setMessage("请求失败,缺少参数");
log.error("destroyRoom失败:缺少参数:" + "userID:" + userID + ",token: " + token + ",roomID:" + req.getRoomID() + ",type: " + type);
return rsp;
}
roomMgr.delRoom(req.getRoomID(), type);
imMgr.destroyGroup(req.getRoomID());
return rsp;
}
|
万爽
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.