diff --git a/blog-admin/src/main/java/com/zyd/blog/controller/ErrorPagesController.java b/blog-admin/src/main/java/com/zyd/blog/controller/ErrorPagesController.java new file mode 100644 index 0000000000000000000000000000000000000000..827bf9f3cc0dab6ab76bb9ee70391bb41708c91e --- /dev/null +++ b/blog-admin/src/main/java/com/zyd/blog/controller/ErrorPagesController.java @@ -0,0 +1,194 @@ +/** + * MIT License + * Copyright (c) 2018 yadong.zhang + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.zyd.blog.controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.web.ErrorAttributes; +import org.springframework.boot.autoconfigure.web.ErrorController; +import org.springframework.boot.autoconfigure.web.ErrorProperties; +import org.springframework.boot.autoconfigure.web.ServerProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Map; + +/** + * 重写BasicErrorController,主要负责系统的异常页面的处理以及错误信息的显示 + *

+ * 此处指需要记录 + * @see org.springframework.boot.autoconfigure.web.BasicErrorController + * @see org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration + *

+ * 要注意,这个类里面的代码一定不能有异常或者潜在异常发生,否则可能会让程序陷入死循环。 + *

+ * + * @author yadong.zhang (yadong.zhang0415(a)gmail.com) + * @website https://www.zhyd.me + * @version 1.0 + * @date 2018/4/16 16:26 + * @since 1.0 + */ +@Controller +@RequestMapping("/error") +@EnableConfigurationProperties({ServerProperties.class}) +public class ErrorPagesController implements ErrorController { + private static final Logger LOG = LoggerFactory.getLogger(ErrorPagesController.class); + + private ErrorAttributes errorAttributes; + + @Autowired + private ServerProperties serverProperties; + + /** + * 初始化ExceptionController + * + * @param errorAttributes + */ + @Autowired + public ErrorPagesController(ErrorAttributes errorAttributes) { + Assert.notNull(errorAttributes, "ErrorAttributes must not be null"); + this.errorAttributes = errorAttributes; + } + + @RequestMapping("/404") + public ModelAndView errorHtml404(HttpServletRequest request, HttpServletResponse response) { + response.setStatus(HttpStatus.NOT_FOUND.value()); + Map model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)); + + return new ModelAndView("error/404", model); + } + + @RequestMapping("/403") + public ModelAndView errorHtml403(HttpServletRequest request, HttpServletResponse response) { + response.setStatus(HttpStatus.FORBIDDEN.value()); + // 404拦截规则,如果是静态文件发生的404则不记录到DB + Map model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)); + if (!String.valueOf(model.get("path")).contains(".")) { + model.put("status", HttpStatus.FORBIDDEN.value()); + } + return new ModelAndView("error/403", model); + } + + @RequestMapping("/400") + public ModelAndView errorHtml400(HttpServletRequest request, HttpServletResponse response) { + response.setStatus(HttpStatus.BAD_REQUEST.value()); + Map model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)); + return new ModelAndView("error/400", model); + } + + @RequestMapping("/401") + public ModelAndView errorHtml401(HttpServletRequest request, HttpServletResponse response) { + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + Map model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)); + return new ModelAndView("error/401", model); + } + + @RequestMapping("/500") + public ModelAndView errorHtml500(HttpServletRequest request, HttpServletResponse response) { + response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + Map model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)); + return new ModelAndView("error/500", model); + } + + /** + * Determine if the stacktrace attribute should be included. + * + * @param request + * the source request + * @param produces + * the media type produced (or {@code MediaType.ALL}) + * @return if the stacktrace attribute should be included + */ + protected boolean isIncludeStackTrace(HttpServletRequest request, + MediaType produces) { + ErrorProperties.IncludeStacktrace include = this.serverProperties.getError().getIncludeStacktrace(); + if (include == ErrorProperties.IncludeStacktrace.ALWAYS) { + return true; + } + return include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM && getTraceParameter(request); + } + + + /** + * 获取错误的信息 + * + * @param request + * @param includeStackTrace + * @return + */ + private Map getErrorAttributes(HttpServletRequest request, + boolean includeStackTrace) { + RequestAttributes requestAttributes = new ServletRequestAttributes(request); + return this.errorAttributes.getErrorAttributes(requestAttributes, + includeStackTrace); + } + + /** + * 是否包含trace + * + * @param request + * @return + */ + private boolean getTraceParameter(HttpServletRequest request) { + String parameter = request.getParameter("trace"); + return parameter != null && !"false".equalsIgnoreCase(parameter); + } + + /** + * 获取错误编码 + * + * @param request + * @return + */ + private HttpStatus getStatus(HttpServletRequest request) { + Integer statusCode = (Integer) request + .getAttribute("javax.servlet.error.status_code"); + if (statusCode == null) { + return HttpStatus.INTERNAL_SERVER_ERROR; + } + try { + return HttpStatus.valueOf(statusCode); + } catch (Exception ex) { + LOG.error("获取当前HttpStatus发生异常", ex); + return HttpStatus.INTERNAL_SERVER_ERROR; + } + } + + /** + * 实现错误路径,暂时无用 + * + * @return + */ + @Override + public String getErrorPath() { + return ""; + } +} diff --git a/blog-admin/src/main/java/com/zyd/blog/controller/PassportController.java b/blog-admin/src/main/java/com/zyd/blog/controller/PassportController.java index bf3a8e511db6d59828838ea3ce661c3c87c082f9..ce6838d052bad0972bc28cf71472842cf02d5873 100644 --- a/blog-admin/src/main/java/com/zyd/blog/controller/PassportController.java +++ b/blog-admin/src/main/java/com/zyd/blog/controller/PassportController.java @@ -20,8 +20,8 @@ package com.zyd.blog.controller; import com.zyd.blog.business.annotation.BussinessLog; -import com.zyd.blog.framework.property.AppProperties; import com.zyd.blog.framework.object.ResponseVO; +import com.zyd.blog.framework.property.AppProperties; import com.zyd.blog.util.ResultUtil; import com.zyd.blog.util.SessionUtil; import org.apache.shiro.SecurityUtils; @@ -60,6 +60,10 @@ public class PassportController { @BussinessLog("进入登录页面") @GetMapping("/login") public ModelAndView login(Model model) { + Subject subject = SecurityUtils.getSubject(); + if (subject.isAuthenticated()||subject.isRemembered()){ + return ResultUtil.redirect("/index"); + } model.addAttribute("enableKaptcha", config.getEnableKaptcha()); return ResultUtil.view("/login"); } diff --git a/blog-admin/src/main/java/com/zyd/blog/controller/RestArticleController.java b/blog-admin/src/main/java/com/zyd/blog/controller/RestArticleController.java index ec1c702ee136eb30cfc28f1ee0743e947245a439..57e11b254a347df1e5f9245a3602e0abab066c71 100644 --- a/blog-admin/src/main/java/com/zyd/blog/controller/RestArticleController.java +++ b/blog-admin/src/main/java/com/zyd/blog/controller/RestArticleController.java @@ -33,6 +33,7 @@ import com.zyd.blog.framework.object.ResponseVO; import com.zyd.blog.util.FileUtil; import com.zyd.blog.util.ResultUtil; import com.zyd.blog.util.SessionUtil; +import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; @@ -58,6 +59,7 @@ public class RestArticleController { @Autowired private BizArticleTagsService articleTagsService; + @RequiresPermissions("articles") @PostMapping("/list") public PageResult list(ArticleConditionVO vo) { PageHelper.startPage(vo.getPageNumber() - 1, vo.getPageSize()); diff --git a/blog-admin/src/main/java/com/zyd/blog/controller/RestCommentController.java b/blog-admin/src/main/java/com/zyd/blog/controller/RestCommentController.java index 43f98a9039b8215f54725c8d7a98e977142d14e9..5ccf49aa099f04e0c4d5af0a06412aaab0bebeee 100644 --- a/blog-admin/src/main/java/com/zyd/blog/controller/RestCommentController.java +++ b/blog-admin/src/main/java/com/zyd/blog/controller/RestCommentController.java @@ -36,6 +36,7 @@ import com.zyd.blog.framework.object.PageResult; import com.zyd.blog.framework.object.ResponseVO; import com.zyd.blog.util.ResultUtil; import com.zyd.blog.util.SessionUtil; +import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -61,6 +62,7 @@ public class RestCommentController { @Autowired private MailService mailService; + @RequiresPermissions("comments") @PostMapping("/list") public PageResult list(CommentConditionVO vo) { PageHelper.startPage(vo.getPageNumber() - 1, vo.getPageSize()); diff --git a/blog-admin/src/main/java/com/zyd/blog/controller/RestResourcesController.java b/blog-admin/src/main/java/com/zyd/blog/controller/RestResourcesController.java index 472967fbde04b19b777b66b6fbef0fbc088808bf..c2f4a6de0c3145121b8d3105f2deaf2aa371244d 100644 --- a/blog-admin/src/main/java/com/zyd/blog/controller/RestResourcesController.java +++ b/blog-admin/src/main/java/com/zyd/blog/controller/RestResourcesController.java @@ -29,7 +29,6 @@ import com.zyd.blog.core.shiro.ShiroService; import com.zyd.blog.framework.object.PageResult; import com.zyd.blog.framework.object.ResponseVO; import com.zyd.blog.util.ResultUtil; -import com.zyd.blog.util.SessionUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.web.bind.annotation.PathVariable; @@ -37,9 +36,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.HashMap; import java.util.List; -import java.util.Map; /** * 系统资源管理 @@ -71,15 +68,6 @@ public class RestResourcesController { return ResultUtil.success(null, resourcesService.queryResourcesListWithSelected(rid)); } - @PostMapping("/loadMenu") - public List loadMenu() { - Map map = new HashMap<>(); - Long userId = SessionUtil.getUser().getId(); - map.put("type", "menu"); - map.put("userId", userId); - return resourcesService.listUserResources(map); - } - @PostMapping("/listParents") public List listParents() { return resourcesService.listAllParentResource(); diff --git a/blog-admin/src/main/java/com/zyd/blog/controller/RestRoleController.java b/blog-admin/src/main/java/com/zyd/blog/controller/RestRoleController.java index ac571e400fc2e6db7902e114419d5eea174dce9f..76f27083912a7642307d57a452c8eea9b78a93e1 100644 --- a/blog-admin/src/main/java/com/zyd/blog/controller/RestRoleController.java +++ b/blog-admin/src/main/java/com/zyd/blog/controller/RestRoleController.java @@ -26,6 +26,7 @@ import com.zyd.blog.business.enums.ResponseStatus; import com.zyd.blog.business.service.SysRoleResourcesService; import com.zyd.blog.business.service.SysRoleService; import com.zyd.blog.business.vo.RoleConditionVO; +import com.zyd.blog.core.shiro.ShiroService; import com.zyd.blog.framework.object.PageResult; import com.zyd.blog.framework.object.ResponseVO; import com.zyd.blog.util.ResultUtil; @@ -54,6 +55,8 @@ public class RestRoleController { private SysRoleService roleService; @Autowired private SysRoleResourcesService roleResourcesService; + @Autowired + private ShiroService shiroService; @PostMapping("/list") public PageResult getAll(RoleConditionVO vo) { @@ -67,13 +70,14 @@ public class RestRoleController { return ResultUtil.success(null, roleService.queryRoleListWithSelected(uid)); } - //分配角色 @PostMapping("/saveRoleResources") public ResponseVO saveRoleResources(Long roleId, String resourcesId) { if (StringUtils.isEmpty(roleId)) { return ResultUtil.error("error"); } roleResourcesService.addRoleResources(roleId, resourcesId); + // 重新加载所有拥有roleId的用户的权限信息 + shiroService.reloadAuthorizingByRoleId(roleId); return ResultUtil.success("成功"); } diff --git a/blog-admin/src/main/java/com/zyd/blog/core/shiro/ShiroService.java b/blog-admin/src/main/java/com/zyd/blog/core/shiro/ShiroService.java index 1584b49f15259036d4d417e9f687bd013480bba2..3346aa897391fa182726a84fb702d9a3e67949ae 100644 --- a/blog-admin/src/main/java/com/zyd/blog/core/shiro/ShiroService.java +++ b/blog-admin/src/main/java/com/zyd/blog/core/shiro/ShiroService.java @@ -20,14 +20,24 @@ package com.zyd.blog.core.shiro; import com.zyd.blog.business.entity.Resources; +import com.zyd.blog.business.entity.User; import com.zyd.blog.business.service.SysResourcesService; +import com.zyd.blog.business.service.SysUserService; +import com.zyd.blog.core.shiro.realm.ShiroRealm; import com.zyd.blog.framework.holder.SpringContextHolder; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.mgt.RealmSecurityManager; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; +import org.apache.shiro.subject.SimplePrincipalCollection; +import org.apache.shiro.subject.Subject; import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager; import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver; import org.apache.shiro.web.servlet.AbstractShiroFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.LinkedHashMap; @@ -45,8 +55,12 @@ import java.util.Map; */ @Service public class ShiroService { + + private static final Logger LOG = LoggerFactory.getLogger(ShiroService.class); @Autowired private SysResourcesService resourcesService; + @Autowired + private SysUserService userService; /** * 初始化权限 @@ -109,44 +123,41 @@ public class ShiroService { String chainDefinition = entry.getValue().trim().replace(" ", ""); manager.createChain(url, chainDefinition); } - - System.out.println("更新权限成功!!"); } } /** - * 根据userId 清除当前session存在的用户的权限缓存 - * @param userIds 已经修改了权限的userId + * 重新加载用户权限 + * + * @param user */ - /* public void clearUserAuthByUserId(List userIds){ - if(null == userIds || userIds.size() == 0) return ; - //获取所有session - Collection sessions = redisSessionDAO.getActiveSessions(); - //定义返回 - List list = new ArrayList(); - for (Session session:sessions){ - //获取session登录信息。 - Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY); - if(null != obj && obj instanceof SimplePrincipalCollection){ - //强转 - SimplePrincipalCollection spc = (SimplePrincipalCollection)obj; - //判断用户,匹配用户ID。 - obj = spc.getPrimaryPrincipal(); - if(null != obj && obj instanceof User){ - User user = (User) obj; - System.out.println("user:"+user); - //比较用户ID,符合即加入集合 - if(null != user && userIds.contains(user.getId())){ - list.add(spc); - } - } - } + public void reloadAuthorizingByUserId(User user) { + RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager(); + ShiroRealm shiroRealm = (ShiroRealm) rsm.getRealms().iterator().next(); + Subject subject = SecurityUtils.getSubject(); + String realmName = subject.getPrincipals().getRealmNames().iterator().next(); + SimplePrincipalCollection principals = new SimplePrincipalCollection(user.getId(), realmName); + subject.runAs(principals); + shiroRealm.getAuthorizationCache().remove(subject.getPrincipals()); + subject.releaseRunAs(); + + LOG.info("用户[{}]的权限更新成功!!", user.getUsername()); + + } + + /** + * 重新加载所有拥有roleId角色的用户的权限 + * + * @param roleId + */ + public void reloadAuthorizingByRoleId(Long roleId) { + List userList = userService.listByRoleId(roleId); + if (CollectionUtils.isEmpty(userList)) { + return; } - RealmSecurityManager securityManager = - (RealmSecurityManager) SecurityUtils.getSecurityManager(); - MyShiroRealm realm = (MyShiroRealm)securityManager.getRealms().iterator().next(); - for (SimplePrincipalCollection simplePrincipalCollection : list) { - realm.clearCachedAuthorizationInfo(simplePrincipalCollection); + for (User user : userList) { + reloadAuthorizingByUserId(user); } - }*/ + } + } diff --git a/blog-admin/src/main/java/com/zyd/blog/core/shiro/credentials/RetryLimitCredentialsMatcher.java b/blog-admin/src/main/java/com/zyd/blog/core/shiro/credentials/RetryLimitCredentialsMatcher.java index 538395cd61a35a90a07b5eec50d204cbdca704f5..100343f011ca4737bb9f04f278528db718636a1b 100644 --- a/blog-admin/src/main/java/com/zyd/blog/core/shiro/credentials/RetryLimitCredentialsMatcher.java +++ b/blog-admin/src/main/java/com/zyd/blog/core/shiro/credentials/RetryLimitCredentialsMatcher.java @@ -19,7 +19,6 @@ */ package com.zyd.blog.core.shiro.credentials; -import com.alibaba.fastjson.JSONObject; import com.zyd.blog.business.consts.SessionConst; import com.zyd.blog.business.entity.User; import com.zyd.blog.business.service.SysUserService; @@ -34,7 +33,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; -import javax.annotation.Resource; import java.util.concurrent.TimeUnit; /** @@ -59,14 +57,14 @@ public class RetryLimitCredentialsMatcher extends CredentialsMatcher { */ private static final String SHIRO_IS_LOCK = "shiro_is_lock_"; @Autowired - RedisTemplate redisTemplate; - @Resource + private RedisTemplate redisTemplate; + @Autowired private SysUserService userService; @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { - User user = (User) info.getPrincipals().getPrimaryPrincipal(); - LOGGER.info("== 验证用户:{}", JSONObject.toJSONString(user)); + Long userId = (Long) info.getPrincipals().getPrimaryPrincipal(); + User user = userService.getByPrimaryKey(userId); String username = user.getUsername(); // 访问一次,计数一次 ValueOperations opsForValue = redisTemplate.opsForValue(); @@ -104,6 +102,6 @@ public class RetryLimitCredentialsMatcher extends CredentialsMatcher { // 当验证都通过后,把用户信息放在session里 // 注:User必须实现序列化 SecurityUtils.getSubject().getSession().setAttribute(SessionConst.USER_SESSION_KEY, user); - return matches; + return true; } } diff --git a/blog-admin/src/main/java/com/zyd/blog/core/shiro/realm/ShiroRealm.java b/blog-admin/src/main/java/com/zyd/blog/core/shiro/realm/ShiroRealm.java index 919c91808e3a23f797c853e1768330c353fd04c2..1f3f52da2b1b24d93254538ad4efd1e2b7963bff 100644 --- a/blog-admin/src/main/java/com/zyd/blog/core/shiro/realm/ShiroRealm.java +++ b/blog-admin/src/main/java/com/zyd/blog/core/shiro/realm/ShiroRealm.java @@ -58,7 +58,6 @@ public class ShiroRealm extends AuthorizingRealm { /** * 提供账户信息返回认证信息(用户的角色信息集合) - * */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { @@ -72,13 +71,13 @@ public class ShiroRealm extends AuthorizingRealm { throw new LockedAccountException("帐号已被锁定,禁止登录!"); } - SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( - user, + // principal参数使用用户Id,方便动态刷新用户权限 + return new SimpleAuthenticationInfo( + user.getId(), user.getPassword(), ByteSource.Util.bytes(username), getName() ); - return authenticationInfo; } /** @@ -86,9 +85,9 @@ public class ShiroRealm extends AuthorizingRealm { */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { - User user = (User) SecurityUtils.getSubject().getPrincipal(); + Long userId = (Long) SecurityUtils.getSubject().getPrincipal(); Map map = new HashMap(); - map.put("userId", user.getId()); + map.put("userId", userId); List resourcesList = resourcesService.listUserResources(map); // 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission) SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); @@ -111,14 +110,4 @@ public class ShiroRealm extends AuthorizingRealm { return info; } - /** - * 指定principalCollection 清除 - */ - /* public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) { - - SimplePrincipalCollection principals = new SimplePrincipalCollection( - principalCollection, getName()); - super.clearCachedAuthorizationInfo(principals); - } -*/ } diff --git a/blog-admin/src/main/resources/static/assets/js/zhyd.core.js b/blog-admin/src/main/resources/static/assets/js/zhyd.core.js index 7b12c53a92b257eed0cfbd95b27dd86df42e4b2c..e801216c8fcc73ce6de93271b2549d7d33ead1f5 100644 --- a/blog-admin/src/main/resources/static/assets/js/zhyd.core.js +++ b/blog-admin/src/main/resources/static/assets/js/zhyd.core.js @@ -205,31 +205,7 @@ $.fn.popover.Constructor.prototype.leave = function (a) { // zhyd.initSidebar(); zhyd.initDaterangepicker(); zhyd.initValidator(); - var menuHtml = localStorage.getItem("menu"); - if (menuHtml) { - $(".side-menu").append(menuHtml); - zhyd.initSidebar(); - } else { - $.ajax({ - cache: true, - type: "POST", - url: '/resources/loadMenu', - dataType: "json", - success: function (data) { - var html = ""; - $.each(data, function (index) { - console.log(this); - this.hasNodes = this.nodes && this.nodes.length > 0; - var tpl = '{{#hasNodes}}

  • {{name}}
  • {{/hasNodes}}'; - tpl += '{{^hasNodes}}
  • {{name}}
  • {{/hasNodes}}'; - html += Mustache.render(tpl, this); - }); - localStorage.setItem("menu", html); - $(".side-menu").append(html); - zhyd.initSidebar(); - } - }); - } + zhyd.initSidebar(); $.ajax({ cache: false, diff --git a/blog-admin/src/main/resources/templates/layout/sidebar.ftl b/blog-admin/src/main/resources/templates/layout/sidebar.ftl index 122133fca590944f8a6883e6137c78dfc31a042c..e496aae3be62e0e0245b1feba44f933b3e81fff7 100644 --- a/blog-admin/src/main/resources/templates/layout/sidebar.ftl +++ b/blog-admin/src/main/resources/templates/layout/sidebar.ftl @@ -2,6 +2,24 @@ diff --git a/blog-core/src/main/java/com/zyd/blog/business/service/SysUserService.java b/blog-core/src/main/java/com/zyd/blog/business/service/SysUserService.java index ed82ea8d1cd7229cd336fc1a492f8e71e30ee8a3..10f95343e73a20a75fb6824598c142c49e593ff5 100644 --- a/blog-core/src/main/java/com/zyd/blog/business/service/SysUserService.java +++ b/blog-core/src/main/java/com/zyd/blog/business/service/SysUserService.java @@ -25,6 +25,8 @@ import com.zyd.blog.business.entity.User; import com.zyd.blog.business.vo.UserConditionVO; import com.zyd.blog.framework.object.AbstractService; +import java.util.List; + /** * 用户 * @@ -60,4 +62,12 @@ public interface SysUserService extends AbstractService { */ User getByUserName(String userName); + /** + * 通过角色Id获取用户列表 + * + * @param roleId + * @return + */ + List listByRoleId(Long roleId); + } diff --git a/blog-core/src/main/java/com/zyd/blog/business/service/impl/SysRoleServiceImpl.java b/blog-core/src/main/java/com/zyd/blog/business/service/impl/SysRoleServiceImpl.java index 1f70c5a0325fab0719a6a3a2e485e231e01cc98c..5904f7ac14042759adb970a6543a8bb7a872be61 100644 --- a/blog-core/src/main/java/com/zyd/blog/business/service/impl/SysRoleServiceImpl.java +++ b/blog-core/src/main/java/com/zyd/blog/business/service/impl/SysRoleServiceImpl.java @@ -121,11 +121,10 @@ public class SysRoleServiceImpl implements SysRoleService { public void insertList(List entities) { Assert.notNull(entities, "entities不可为空!"); List sysRole = new ArrayList<>(); - String regIp = IpUtil.getRealIp(RequestHolder.getRequest()); - for (Role Role : entities) { - Role.setUpdateTime(new Date()); - Role.setCreateTime(new Date()); - sysRole.add(Role.getSysRole()); + for (Role role : entities) { + role.setUpdateTime(new Date()); + role.setCreateTime(new Date()); + sysRole.add(role.getSysRole()); } roleMapper.insertList(sysRole); } diff --git a/blog-core/src/main/java/com/zyd/blog/business/service/impl/SysUserServiceImpl.java b/blog-core/src/main/java/com/zyd/blog/business/service/impl/SysUserServiceImpl.java index 5ff0044293369a1a48b1a2e28b2f255d2ef66d67..63eb42eb4d62872288ea239f16ec4c28af1b0865 100644 --- a/blog-core/src/main/java/com/zyd/blog/business/service/impl/SysUserServiceImpl.java +++ b/blog-core/src/main/java/com/zyd/blog/business/service/impl/SysUserServiceImpl.java @@ -250,4 +250,23 @@ public class SysUserServiceImpl implements SysUserService { return getOneByEntity(user); } + /** + * 通过角色Id获取用户列表 + * + * @param roleId + * @return + */ + @Override + public List listByRoleId(Long roleId) { + List sysUsers = sysUserMapper.listByRoleId(roleId); + if (CollectionUtils.isEmpty(sysUsers)) { + return null; + } + List users = new ArrayList<>(); + for (SysUser su : sysUsers) { + users.add(new User(su)); + } + return users; + } + } diff --git a/blog-core/src/main/java/com/zyd/blog/framework/tag/CustomTagDirective.java b/blog-core/src/main/java/com/zyd/blog/framework/tag/CustomTagDirective.java index ce9854ac7c7c745d22ebfeb100da39b49fee0581..af6b4329685f7be1697e30d3214cce3f764e2ec8 100644 --- a/blog-core/src/main/java/com/zyd/blog/framework/tag/CustomTagDirective.java +++ b/blog-core/src/main/java/com/zyd/blog/framework/tag/CustomTagDirective.java @@ -28,8 +28,10 @@ import freemarker.core.Environment; import freemarker.template.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; import java.io.IOException; +import java.util.HashMap; import java.util.Map; /** @@ -85,6 +87,20 @@ public class CustomTagDirective implements TemplateDirectiveModel { // 站点属性 environment.setVariable("siteInfo", builder.build().wrap(configService.getSiteInfo())); break; + case "menus": + Integer userId = null; + if (map.containsKey("userId")) { + String userIdStr = map.get("userId").toString(); + if(StringUtils.isEmpty(userIdStr)){ + return; + } + userId = Integer.parseInt(userIdStr); + } + Map params = new HashMap<>(2); + params.put("type", "menu"); + params.put("userId", userId); + environment.setVariable("menus", builder.build().wrap(resourcesService.listUserResources(params))); + break; default: break; } diff --git a/blog-core/src/main/java/com/zyd/blog/persistence/mapper/SysUserMapper.java b/blog-core/src/main/java/com/zyd/blog/persistence/mapper/SysUserMapper.java index d0f9c6422adf6627c10ffac19bc5672d90d9cbd4..0d9f120becabf20cec90a73a2e60353c14acb127 100644 --- a/blog-core/src/main/java/com/zyd/blog/persistence/mapper/SysUserMapper.java +++ b/blog-core/src/main/java/com/zyd/blog/persistence/mapper/SysUserMapper.java @@ -42,4 +42,6 @@ public interface SysUserMapper extends BaseMapper { List findPageBreakByCondition(UserConditionVO vo); + List listByRoleId(Long roleId); + } diff --git a/blog-core/src/main/resources/mybatis/SysUserMapper.xml b/blog-core/src/main/resources/mybatis/SysUserMapper.xml index 7bbaa988f3ea3375a94af8d3d899da5bfc2fc0d3..bc72d99b8a5a14614e3c1ff8360c7932409fed86 100644 --- a/blog-core/src/main/resources/mybatis/SysUserMapper.xml +++ b/blog-core/src/main/resources/mybatis/SysUserMapper.xml @@ -80,5 +80,17 @@ s.create_time DESC + +