Преглед изворни кода

解决配置文件include和active

baihe пре 2 година
родитељ
комит
86c7a02cfe

+ 31 - 0
common-springboot/src/main/java/com/gihon/demo/common/controller/PermissionContoller.java

@@ -0,0 +1,31 @@
+package com.gihon.demo.common.controller;
+
+import java.util.List;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.gihon.common.web.response.Response;
+import com.gihon.demo.common.service.PermissionService;
+import com.gihon.sso.entity.vo.MenuVO;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+
+@Api(value ="根据权限获取菜单当前系统菜单" ,tags = "根据权限获取菜单当前系统菜单")
+@RestController
+@RequestMapping("permission")
+public class PermissionContoller {
+
+    @Autowired
+    private PermissionService permissionService;
+    
+    @ApiOperation("权限菜单:列表用于前后端分离判断路由和按钮")
+    @GetMapping()
+    public Response<List<MenuVO>> getPermission() {
+        List<MenuVO> list = permissionService.getPermission();
+        return Response.ok(list);
+    }
+}

+ 10 - 0
common-springboot/src/main/java/com/gihon/demo/common/service/PermissionService.java

@@ -0,0 +1,10 @@
+package com.gihon.demo.common.service;
+
+import java.util.List;
+
+import com.gihon.sso.entity.vo.MenuVO;
+
+public interface PermissionService {
+
+    List<MenuVO> getPermission();
+}

+ 94 - 0
common-springboot/src/main/java/com/gihon/demo/common/service/impl/PermissionServiceImpl.java

@@ -0,0 +1,94 @@
+package com.gihon.demo.common.service.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.stereotype.Service;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.gihon.common.auth.AuthConstans;
+import com.gihon.common.auth.AuthUser;
+import com.gihon.common.auth.AuthUtils;
+import com.gihon.common.enums.ModuleType;
+import com.gihon.common.properties.GihonCommonProperties;
+import com.gihon.common.properties.RedisConstants;
+import com.gihon.common.util.JacksonJsonUtils;
+import com.gihon.demo.common.service.PermissionService;
+import com.gihon.sso.entity.vo.MenuVO;
+import com.gihon.sso.entity.vo.PermissionVO;
+
+@Service
+public class PermissionServiceImpl implements PermissionService {
+
+    @Autowired
+    private StringRedisTemplate stringRedisTemplate;
+
+    @Autowired
+    private GihonCommonProperties gihonCommonProperties;
+    
+    @Override
+    public List<MenuVO> getPermission() {
+        
+        String menuJson = (String) stringRedisTemplate.opsForHash().get(RedisConstants.MENU_TREE_REDIS,
+                gihonCommonProperties.getModuleCode() + RedisConstants.SEP + gihonCommonProperties.getModuleType());
+        TypeReference<List<MenuVO>> valueTypeRef = new TypeReference<List<MenuVO>>() {
+        };
+        List<MenuVO> root = JacksonJsonUtils.readObject(menuJson, valueTypeRef);
+        //原始
+        List<MenuVO> list = new ArrayList<>(root.size());
+        
+        AuthUser user = AuthUtils.getUser();
+        if (AuthConstans.ADMIN.equals(user.getUsername()) && gihonCommonProperties.getModuleType() == ModuleType.WEB.getCode()) {
+           
+            return root;
+        }
+        
+        // 获取全部的角色
+        List<String> role = user.getRoleList();
+        //返回有权限的终极菜单。其他不需要后台控制的菜单有前端自行展示
+        cloneCopyMenu(root,list,role);
+        
+        
+        return list;
+    }
+
+    /**
+     * 递归查询菜单Copy
+     * 
+     * @param vo
+     * @param list
+     */
+    private void cloneCopyMenu(List<MenuVO> root, List<MenuVO> list, List<String> role) {
+        if(role==null ||role.isEmpty()) {
+            //无角色就无权限
+            return;
+        }
+        for (MenuVO voi : root) {
+            List<PermissionVO> permissions = voi.getPermissions();
+            if (permissions == null || permissions.isEmpty()) {
+                continue;
+            }
+            List<PermissionVO> pt = permissions.stream().filter(poi -> {
+                if (poi.getRoleList() == null || poi.getRoleList().isEmpty()) {//未配置角色就是只有超级管理员有权限@See AuthServiceImpl#checkPermission
+                    return false;
+                }else if(poi.getRoleList().stream().anyMatch(s->role.contains(s))) {//角色是任意一个即可
+                    return true;
+                }
+                return false;
+            }).collect(Collectors.toList());
+            
+            if(pt.isEmpty()) {//菜单需要有任意一个操作权限
+                continue;
+            }
+            MenuVO mv = new MenuVO();
+            mv.setMenuCode(voi.getMenuCode());
+            mv.setMenuId(voi.getMenuId());
+            mv.setPermissions(pt);
+            list.add(mv);
+        }
+    }
+    
+}

+ 22 - 0
common-springboot/src/main/resources/application-dev.yml

@@ -0,0 +1,22 @@
+spring: 
+# Redis           
+  redis:
    database: 8          # Redis数据库索引(默认为0)
+    timeout: 0            # 连接超时时间(毫秒)
+    host: 172.18.0.23
+    port: 6379
+    password: Ebe1tech/Passw0rd       
+# dataBase
+  datasource: 
+    druid:
+      # 从这里开始(druid)
+      url: jdbc:mysql://172.18.0.23:3306/gihon?characterEncoding=UTF-8&useSSL=false
+      username: root
+      password: 1q2w3e4r
+gihon:
+  common:
+    module-type: 1
+    module-code: SystemManage
+    
+  
+      
+  

+ 4 - 4
common-springboot/src/main/resources/application.yml

@@ -8,8 +8,12 @@ server:
     
 spring: 
   profiles:
+    #include 会按顺序覆盖当前文件中同名
     include:
       - common
+    #active 会按顺序覆盖当前文件和include中同名
+    active:
+      - dev
 
   # Redis           
   redis:
@@ -36,7 +40,3 @@ knife4j:
     - 
       group: SSO
       name: 登录验证模块
-gihon:
-  common:
-    module-type: 1
-    module-code: SystemManage

+ 47 - 9
common-sso/src/main/java/com/gihon/sso/auth/impl/AuthServiceImpl.java

@@ -25,6 +25,7 @@ import com.gihon.common.properties.GihonCommonProperties;
 import com.gihon.common.properties.RedisConstants;
 import com.gihon.common.util.JacksonJsonUtils;
 import com.gihon.sso.auth.AuthService;
+import com.gihon.sso.entity.vo.MenuVO;
 import com.gihon.sso.entity.vo.PermissionVO;
 import com.gihon.sso.entity.vo.TokenVal;
 import com.gihon.sso.service.GihonButtonService;
@@ -92,13 +93,13 @@ public class AuthServiceImpl implements AuthService{
         // 获取全部的权限列表匹配
         // 用权限匹配角色,如果没有角色那么就通过
         List<String> needRole = getPermission(uri);
-        // Null 是没有配置权限
+        // Null 是没有配置权限只要登录即可
         if (needRole == null) {
             return true;
-        } else if (role == null) {
+        } else if (role == null||role.isEmpty()) {
             return false;
         }
-        // Empty是配置权限但是没有角色
+        // Empty是配置权限但是没有角色 只有管理员才行 @See PermissionServiceImpl#cloneCopyMenu
         return needRole.stream().anyMatch(r -> role.contains(r));
     }
 
@@ -155,23 +156,60 @@ public class AuthServiceImpl implements AuthService{
                 return;
             }
             List<GihonMenu> menuList = gihonMenuService.getAllMenu(module.getId());
+            
+            List<MenuVO> menus = new ArrayList<>();
+            
+            MenuVO root = new MenuVO();
+            root.setMenuCode(gihonCommonProperties.getModuleCode());
+            root.setMenuId(-1L);
+            
+            menus.add(root);
+            
+            MenuVO mp = new MenuVO();
+           
+            menuList.forEach(m -> {
+                MenuVO mv = new MenuVO();
+                mv.setMenuCode(m.getMenuCode());
+                mv.setMenuId(m.getId());
+                menus.add(mv);
+//                mp.setMenuId(m.getParentId());
+//                int index = menus.indexOf(mp);
+//                if (index > 0) {
+//                    menus.get(index).addMenu(mp);
+//                }
+            });
+
             List<GihonButton> buttonList = gihonButtonService.getMenuButton(menuList.stream().map(m -> m.getId()).collect(Collectors.toList()));
             List<PermissionVO> plist = new ArrayList<PermissionVO>();
             for (GihonButton btn : buttonList) {
-                if (StringUtils.isBlank(btn.getPath())) {
-                    continue;
-                }
                 List<Long> rbtnList = gihonRoleButtonService.getRoleListByBtn(btn.getId());
                 PermissionVO pvo = new PermissionVO();
                 pvo.setUrl(btn.getPath());
                 pvo.setMethod(btn.getMethod());
-                List<GihonRole> rl = gihonRoleService.getRoleListByIds(rbtnList);
-                pvo.setRoleList(rl.stream().map(r -> r.getCompanyId()+RedisConstants.SEP+r.getRoleCode()).collect(Collectors.toList()));
+                pvo.setBtnCode(btn.getButtonCode());
+                pvo.setBtnName(btn.getButtonName());
+                if (!rbtnList.isEmpty()) {
+                    List<GihonRole> rl = gihonRoleService.getRoleListByIds(rbtnList);
+                    pvo.setRoleList(rl.stream().map(r -> r.getCompanyId()+RedisConstants.SEP+r.getRoleCode()).collect(Collectors.toList()));
+                }else {
+                    pvo.setRoleList(new ArrayList<>(0));
+                }
+                mp.setMenuId(btn.getMenuId());
+                int index = menus.indexOf(mp);
+                if (index > 0) {
+                    menus.get(index).addPermission(pvo);
+                }
+                if (StringUtils.isBlank(btn.getPath())) {
+                    continue;
+                }
                 plist.add(pvo);
             }
-
+            //用于拦截器的访问权限按钮
             stringRedisTemplate.opsForHash().put(RedisConstants.PERMISSN_REDIS,
                     gihonCommonProperties.getModuleCode() + RedisConstants.SEP + gihonCommonProperties.getModuleType(), JacksonJsonUtils.writeObject(plist));
+            //用于拦截器的访问权限按钮
+            stringRedisTemplate.opsForHash().put(RedisConstants.MENU_TREE_REDIS,
+                    gihonCommonProperties.getModuleCode() + RedisConstants.SEP + gihonCommonProperties.getModuleType(), JacksonJsonUtils.writeObject(menus));
         } catch (Exception e) {
             log.error("初始化AuthService失败:", e);
         }

+ 1 - 1
common-sso/src/main/java/com/gihon/sso/controller/LoginController.java

@@ -64,7 +64,7 @@ public class LoginController {
      * @return
      */
     @ApiOperation("SSO:token获取用户信息")
-    @GetMapping("useInfo")
+    @GetMapping("userInfo")
     public Response<UserInfo> userInfo() {
         String token = (String) AuthUtils.getRequest().getAttribute(AuthUtils.REQ_TOKEN);
         UserInfo userInfo = tokenService.checkTokenInfo(token);

+ 46 - 0
common-sso/src/main/java/com/gihon/sso/entity/vo/MenuVO.java

@@ -0,0 +1,46 @@
+package com.gihon.sso.entity.vo;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * 菜单树
+ * 
+ * @author baihe
+ *
+ */
+@EqualsAndHashCode(of = "menuId")
+@Setter
+@Getter
+public class MenuVO {
+
+    @JsonIgnore
+    private Long menuId;
+
+    private String menuCode;
+
+    private List<MenuVO> children = new ArrayList<>();
+
+    private List<PermissionVO> permissions = new ArrayList<>();
+
+    public void addMenu(MenuVO menu) {
+        children.add(menu);
+    }
+    public void addPermission(PermissionVO permission) {
+        permissions.add(permission);
+    }
+    /**
+     * 不符合的返回true
+     * 
+     * @return
+     */
+    public boolean filter() {
+        return (children == null || children.isEmpty()) && (permissions == null || permissions.isEmpty());
+    }
+}

+ 4 - 1
common-sso/src/main/java/com/gihon/sso/entity/vo/PermissionVO.java

@@ -2,7 +2,6 @@ package com.gihon.sso.entity.vo;
 
 import java.util.List;
 
-import lombok.Data;
 import lombok.Getter;
 import lombok.Setter;
 
@@ -15,6 +14,10 @@ import lombok.Setter;
 @Getter
 public class PermissionVO {
 
+    private String btnCode;
+    
+    private String btnName;
+    
 	private String url;
 	
 	private String method;

+ 5 - 0
common-sso/src/main/java/com/gihon/sso/entity/vo/UserInfo.java

@@ -65,6 +65,11 @@ public class UserInfo implements AuthUser, Serializable {
      */
     private boolean credentialsNonExpired = true;
     
+    /**
+     * 创建时间
+     */
+    private long createdTime = System.currentTimeMillis();
+    
     
     private List<String> roleList;
 

+ 3 - 3
common-sso/src/main/java/com/gihon/sso/service/impl/GihonRoleServiceImpl.java

@@ -46,9 +46,6 @@ public class GihonRoleServiceImpl extends ServiceImpl<GihonRoleMapper, GihonRole
      */
     public List<GihonRole> getRoleList(Long userId) {
         List<Long> roleList = gihonUserRoleService.roleListByUserId(userId);
-        if (roleList.isEmpty()) {
-            return new ArrayList<>(0);
-        }
         return this.getRoleListByIds(roleList);
     }
 
@@ -56,6 +53,9 @@ public class GihonRoleServiceImpl extends ServiceImpl<GihonRoleMapper, GihonRole
      * 按照角色IDS获取角色列表
      */
     public List<GihonRole> getRoleListByIds(List<Long> ids) {
+        if (ids.isEmpty()) {
+            return new ArrayList<>(0);
+        }
         return this.lambdaQuery().in(GihonRole::getId, ids).list();
     }
 

+ 8 - 2
common-sso/src/main/java/com/gihon/sso/service/impl/TokenServiceImpl.java

@@ -213,16 +213,22 @@ public class TokenServiceImpl implements TokenService {
     public UserInfo getUserInfo(String account) {
         String userAccount = (String) stringRedisTemplate.opsForHash().get(USER_STORE, account);
         UserInfo userInfo = null;
+        long now = System.currentTimeMillis();
         if (StringUtils.hasText(userAccount)) {
             userInfo = JacksonJsonUtils.readObject(userAccount, UserInfo.class);
-        } else {
-            userInfo = loginUserService.queryUserByUserAccount(userAccount);
+            if((userInfo.getCreatedTime() + gihonCommonProperties.getRefreshTokenExpired()) >= now) {//超时重新获取,有AOP同步账号信息
+                userInfo = null; 
+            }
+        } 
+        if(userInfo==null) {
+            userInfo = loginUserService.queryUserByUserAccount(account);
             if (userInfo == null) {
                 return null;
             }
             // add roleList;
             List<GihonRole> rl = gihonRoleService.getRoleList(userInfo.getId());
             userInfo.setRoleList(rl.stream().map(r -> r.getCompanyId()+RedisConstants.SEP+r.getRoleCode()).collect(Collectors.toList()));
+            userInfo.setCreatedTime(now);
             stringRedisTemplate.opsForHash().put(USER_STORE, account, JacksonJsonUtils.writeObject(userInfo));
         }
         return userInfo;

+ 19 - 0
common-sso/src/main/resources/application-dev.yml

@@ -0,0 +1,19 @@
+spring: 
+# Redis           
+  redis:
    database: 8          # Redis数据库索引(默认为0)
+    timeout: 0            # 连接超时时间(毫秒)
+    host: 172.18.0.23
+    port: 6379
+    password: Ebe1tech/Passw0rd       
+# dataBase
+  datasource: 
+    druid:
+      # 从这里开始(druid)
+      url: jdbc:mysql://172.18.0.23:3306/gihon?characterEncoding=UTF-8&useSSL=false
+      username: root
+      password: 1q2w3e4r
+
+    
+  
+      
+  

+ 2 - 1
common-sso/src/main/resources/application.yml

@@ -7,7 +7,8 @@ server:
     basedir: /data/tmp
     
 spring: 
-  profiles:
    include:
      - common
    
+  profiles:
    include:
      - common
+    active:
      - dev
    
 # Redis           
   redis:
    database: 8          # Redis数据库索引(默认为0)
     timeout: 0            # 连接超时时间(毫秒)

+ 7 - 0
common-util/src/main/java/com/gihon/common/auth/AuthUtils.java

@@ -44,6 +44,13 @@ public class AuthUtils {
         return r == null ? null : r.getResponse();
     }
 
+    public static String getToken() {
+        HttpServletRequest request = getRequest();
+        if (request == null) {
+            return null;
+        }
+        return (String) request.getAttribute(AuthUtils.REQ_TOKEN);
+    }
     public static Long getUserId() {
         AuthUser user = getUser();
         if (user != null) {

+ 2 - 0
common-util/src/main/java/com/gihon/common/properties/RedisConstants.java

@@ -4,5 +4,7 @@ public interface RedisConstants {
 
 	final static String PERMISSN_REDIS = "PERMISSON_REDIS_";
 	
+	final static String MENU_TREE_REDIS = "MENU_TREE_REDIS_";
+	
 	final static String SEP = "@";
 }