Browse Source

调整配置文件,调整权限验证读取方式

NorthLan 7 years ago
parent
commit
0d895ef219

+ 0 - 15
zen-api/src/main/kotlin/com/gxzc/zen/api/sys/mapper/SysPermissionMapper.kt

@@ -1,15 +0,0 @@
-package com.gxzc.zen.api.sys.mapper
-
-import com.gxzc.zen.api.sys.model.SysPermission
-import com.gxzc.zen.common.base.BaseMapper
-import org.springframework.stereotype.Repository
-/**
- * <p>
- * 权限表 Mapper 接口
- * </p>
- *
- * @author NorthLan123
- * @since 2018-02-06
- */
-@Repository
-interface SysPermissionMapper : BaseMapper<SysPermission>

+ 7 - 1
zen-api/src/main/kotlin/com/gxzc/zen/api/sys/mapper/SysUserRoleMapper.kt

@@ -1,8 +1,11 @@
 package com.gxzc.zen.api.sys.mapper
 
+import com.gxzc.zen.api.sys.model.SysRole
 import com.gxzc.zen.api.sys.model.SysUserRole
 import com.gxzc.zen.common.base.BaseMapper
+import org.apache.ibatis.annotations.Param
 import org.springframework.stereotype.Repository
+
 /**
  * <p>
  * 用户角色表 Mapper 接口
@@ -12,4 +15,7 @@ import org.springframework.stereotype.Repository
  * @since 2018-02-06
  */
 @Repository
-interface SysUserRoleMapper : BaseMapper<SysUserRole>
+interface SysUserRoleMapper : BaseMapper<SysUserRole> {
+    fun selectUserRoleListByUserId(@Param("userId") id: Long): MutableList<SysRole>
+    fun selectUserRoleListByUserIdList(@Param("userIdList") id: Array<Int>): MutableList<SysRole>
+}

+ 0 - 33
zen-api/src/main/kotlin/com/gxzc/zen/api/sys/model/SysPermission.kt

@@ -1,33 +0,0 @@
-package com.gxzc.zen.api.sys.model
-
-import com.baomidou.mybatisplus.annotations.TableName
-import com.gxzc.zen.common.base.BaseModel
-
-/**
- * <p>
- * 权限表
- * </p>
- *
- * @author NorthLan123
- * @since 2018-02-06
- */
-@TableName("sys_permission")
-data class SysPermission(
-        /**
-         * 平台ID(0:通用,1:系统,2:接收,3:保存,4:管理,5:利用)
-         */
-        var platformId: Int? = null,
-        /**
-         * 权限名称
-         */
-        var name: String? = null,
-        /**
-         * 权限代码
-         */
-        var perm: String? = null,
-        /**
-         * 权限描述
-         */
-        var description: String? = null
-) : BaseModel() {
-}

+ 1 - 1
zen-api/src/main/kotlin/com/gxzc/zen/api/sys/model/SysRole.kt

@@ -20,6 +20,6 @@ data class SysRole(
         /**
          * 权限列表
          */
-        var permIds: String? = null
+        var perms: String? = null
 ) : BaseModel() {
 }

+ 11 - 7
zen-api/src/main/kotlin/com/gxzc/zen/api/sys/service/ISysPermissionService.kt

@@ -1,16 +1,20 @@
 package com.gxzc.zen.api.sys.service
 
-import com.gxzc.zen.api.sys.model.SysPermission
-import com.gxzc.zen.common.base.BaseService
-
 /**
  * <p>
- * 权限 服务类
+ * 权限 服务类
  * </p>
  *
- * @author NorthLan123
+ * @author NorthLan
  * @since 2018-02-06
  */
-interface ISysPermissionService : BaseService<SysPermission> {
-    fun getPermissionByUserId(id: Long): Set<String>
+interface ISysPermissionService {
+    /**
+     * 获取指定用户的所有权限并缓存至user_perm key: uid_*
+     */
+    fun getPermissionSetByUserId(id: Long): HashSet<String>
+    /**
+     * 初始化所有用户的权限缓存
+     */
+    fun initPermissionCacheAllUser()
 }

+ 9 - 1
zen-api/src/main/kotlin/com/gxzc/zen/api/sys/service/ISysUserRoleService.kt

@@ -13,5 +13,13 @@ import com.gxzc.zen.common.base.BaseService
  * @since 2018-02-06
  */
 interface ISysUserRoleService : BaseService<SysUserRole> {
-    fun getRoleByUserId(id: Long): SysRole
+    /**
+     * 获取指定用户的角色列表
+     */
+    fun getUserRoleListByUserId(id: Long): MutableList<SysRole>
+
+    /**
+     * 获取所有用户的角色列表
+     */
+    fun getUserRoleList(): Map<Int, MutableList<SysRole>>
 }

+ 18 - 13
zen-api/src/main/kotlin/com/gxzc/zen/api/sys/service/impl/SysPermissionServiceImpl.kt

@@ -1,12 +1,10 @@
 package com.gxzc.zen.api.sys.service.impl
 
-import com.baomidou.mybatisplus.service.impl.ServiceImpl
-import com.gxzc.zen.api.sys.mapper.SysPermissionMapper
-import com.gxzc.zen.api.sys.model.SysPermission
 import com.gxzc.zen.api.sys.service.ISysPermissionService
 import com.gxzc.zen.api.sys.service.ISysUserRoleService
 import com.gxzc.zen.common.contants.CACHEKEYS
 import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.cache.CacheManager
 import org.springframework.cache.annotation.Cacheable
 import org.springframework.stereotype.Service
 
@@ -19,20 +17,27 @@ import org.springframework.stereotype.Service
  * @since 2018-02-06
  */
 @Service
-class SysPermissionServiceImpl : ServiceImpl<SysPermissionMapper, SysPermission>(), ISysPermissionService {
+class SysPermissionServiceImpl : ISysPermissionService {
+    @Autowired
+    private lateinit var cacheManager: CacheManager
 
     @Autowired
     private lateinit var sysUserRoleService: ISysUserRoleService
 
-    /**
-     * 获取指定用户的所有权限并缓存
-     * 任何对 用户id
-     */
-    @Cacheable(value = [CACHEKEYS.USER_PERM], key = "#id")
-    override fun getPermissionByUserId(id: Long): Set<String> {
-        val role = sysUserRoleService.getRoleByUserId(id)
-        return baseMapper.selectBatchIds(role.permIds?.split(','))
-                .mapNotNull { it.perm }.toSet()
+
+    @Cacheable(value = [CACHEKEYS.USER_PERM], key = "'uid_' + #id")
+    override fun getPermissionSetByUserId(id: Long): HashSet<String> {
+        val roleList = sysUserRoleService.getUserRoleListByUserId(id)
+        val permIds = linkedSetOf<String>()
+        for (item in roleList) {
+            item.perms?.split(',')?.toCollection(permIds)
+        }
+        return permIds
+    }
+
+    override fun initPermissionCacheAllUser() {
+        val cache = cacheManager.getCache(CACHEKEYS.USER_PERM)
+
     }
 
 }

+ 8 - 15
zen-api/src/main/kotlin/com/gxzc/zen/api/sys/service/impl/SysUserRoleServiceImpl.kt

@@ -1,14 +1,11 @@
 package com.gxzc.zen.api.sys.service.impl
 
+import com.baomidou.mybatisplus.mapper.EntityWrapper
 import com.baomidou.mybatisplus.service.impl.ServiceImpl
 import com.gxzc.zen.api.sys.mapper.SysUserRoleMapper
 import com.gxzc.zen.api.sys.model.SysRole
 import com.gxzc.zen.api.sys.model.SysUserRole
-import com.gxzc.zen.api.sys.service.ISysRoleService
 import com.gxzc.zen.api.sys.service.ISysUserRoleService
-import com.gxzc.zen.common.contants.CACHEKEYS
-import org.springframework.beans.factory.annotation.Autowired
-import org.springframework.cache.annotation.Cacheable
 import org.springframework.stereotype.Service
 
 /**
@@ -21,17 +18,13 @@ import org.springframework.stereotype.Service
  */
 @Service
 class SysUserRoleServiceImpl : ServiceImpl<SysUserRoleMapper, SysUserRole>(), ISysUserRoleService {
+    override fun getUserRoleListByUserId(id: Long): MutableList<SysRole> {
+        return baseMapper.selectUserRoleListByUserId(id)
+    }
 
-    @Autowired
-    private lateinit var sysRoleService: ISysRoleService
-
-    /**
-     * 获取指定用户的角色
-     * 缓存在
-     */
-    @Cacheable(value = [CACHEKEYS.USER_ROLE], key = "'uid_'.concat(#result.id)")
-    override fun getRoleByUserId(id: Long): SysRole {
-        val userRole = baseMapper.selectOne(SysUserRole().also { it.userId = id })
-        return sysRoleService.selectById(userRole.roleId)
+    override fun getUserRoleList(): Map<Int, MutableList<SysRole>> {
+        val allSysUserRole = baseMapper.selectList(EntityWrapper<SysUserRole>())
+        allSysUserRole.
+                return baseMapper.selectUserRoleList()
     }
 }

+ 0 - 20
zen-api/src/main/resources/mapping/sys/SysPermissionMapper.xml

@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-<mapper namespace="com.gxzc.zen.api.sys.mapper.SysPermissionMapper">
-
-    <!-- 通用查询映射结果 -->
-    <resultMap id="BaseResultMap" type="com.gxzc.zen.api.sys.model.SysPermission">
-    <result column="id" property="id" />
-    <result column="enable" property="enable" />
-    <result column="remark" property="remark" />
-    <result column="create_time" property="createTime" />
-    <result column="create_by" property="createBy" />
-    <result column="update_time" property="updateTime" />
-    <result column="update_by" property="updateBy" />
-        <result column="platform_id" property="platformId" />
-        <result column="name" property="name" />
-        <result column="perm" property="perm" />
-        <result column="description" property="description" />
-    </resultMap>
-
-</mapper>

+ 1 - 1
zen-api/src/main/resources/mapping/sys/SysRoleMapper.xml

@@ -12,7 +12,7 @@
     <result column="update_time" property="updateTime" />
     <result column="update_by" property="updateBy" />
         <result column="name" property="name" />
-        <result column="perm_ids" property="permIds" />
+        <result column="perms" property="perms" />
     </resultMap>
 
 </mapper>

+ 29 - 9
zen-api/src/main/resources/mapping/sys/SysUserRoleMapper.xml

@@ -4,15 +4,35 @@
 
     <!-- 通用查询映射结果 -->
     <resultMap id="BaseResultMap" type="com.gxzc.zen.api.sys.model.SysUserRole">
-    <result column="id" property="id" />
-    <result column="enable" property="enable" />
-    <result column="remark" property="remark" />
-    <result column="create_time" property="createTime" />
-    <result column="create_by" property="createBy" />
-    <result column="update_time" property="updateTime" />
-    <result column="update_by" property="updateBy" />
-        <result column="role_id" property="roleId" />
-        <result column="user_id" property="userId" />
+        <result column="id" property="id"/>
+        <result column="enable" property="enable"/>
+        <result column="remark" property="remark"/>
+        <result column="create_time" property="createTime"/>
+        <result column="create_by" property="createBy"/>
+        <result column="update_time" property="updateTime"/>
+        <result column="update_by" property="updateBy"/>
+        <result column="role_id" property="roleId"/>
+        <result column="user_id" property="userId"/>
     </resultMap>
 
+    <select id="selectUserRoleListByUserId" resultType="com.gxzc.zen.api.sys.model.SysRole">
+        SELECT A.*
+        FROM
+            sys_role AS A
+            INNER JOIN sys_user_role AS B ON B.role_id = A.id
+        WHERE B.user_id = #{userId}
+    </select>
+
+    <select id="selectUserRoleListByUserIdList" parameterType="java.util.Map" resultType="com.gxzc.zen.api.sys.model.SysRole">
+        SELECT A.*
+        FROM
+        sys_role AS A
+        INNER JOIN sys_user_role AS B ON B.role_id = A.id
+        WHERE
+        B.user_id IN
+        <foreach collection="userIdList" item="item" open="(" close=")">
+            #{item}
+        </foreach>
+    </select>
+
 </mapper>

+ 1 - 1
zen-core/src/main/kotlin/com/gxzc/zen/common/contants/CACHEKEYS.kt

@@ -8,7 +8,7 @@ package com.gxzc.zen.common.contants
  */
 object CACHEKEYS {
     const val USER = "user"
+    const val ROLE = "role"
     const val USER_ROLE = "user_role"
     const val USER_PERM = "user_perm"
-    const val PERMISSION = "sys_permission"
 }

+ 13 - 0
zen-core/src/main/resources/application-cache.yml

@@ -7,8 +7,21 @@ spring:
 
 cache:
   enable: true # 是否生效
+  recordStats: &recordStats
+    recordStats: false # 开发统计功能
   cache-specs: # see also {CaffeineSpec}
     user: # cache name
+      initialCapacity: -1 # 初始化容量 默认-1
+      maximumSize: 50 # 最大容量
+      # maximumWeight: -1 # 最大权重,与maximumSize冲突
+      # expireAfterAccess: 1 # 最后一次写入或访问后经过固定时间过期 以expireAfterWrite为准
+      # expireAfterWrite: 1 # 最后一次写入后经过固定时间过期
+      # refreshAfterWrite: 1 # 创建缓存或者最近一次更新缓存后经过固定的时间间隔刷新缓存
+      <<: *recordStats # 开发统计功能
+      weakKeys: false # 该key是否为弱引用
+      weakValues: false # 该key对应的values是否为弱引用 与softValues冲突
+      softValues: false # 该key对应的values是否为软引用
+    user_perm: # cache name
       initialCapacity: -1 # 初始化容量 默认-1
       maximumSize: 50 # 最大容量
       # maximumWeight: -1 # 最大权重,与maximumSize冲突

+ 1 - 4
zen-orm/src/main/resources/application-orm-local.yml

@@ -1,6 +1,5 @@
-### 多数据源开关
 orm:
-  multi-datasource-enable: false
+  multi-datasource-enable: true # 多数据源开关
 
 ################## Alibaba Druid 配置 ##################
 spring:
@@ -44,7 +43,6 @@ datasource:
     test-while-idle: true
     validation-query: SELECT 1
     async-init: false
-    name: sys
     filters: logback,log4j,wall,mergeStat
     keep-alive: false
     initial-size: 5
@@ -63,7 +61,6 @@ datasource:
     test-while-idle: true
     validation-query: SELECT 1
     async-init: false
-    name: sys
     filters: logback,log4j,wall,mergeStat
     keep-alive: false
     initial-size: 5

+ 71 - 53
zen-orm/src/main/resources/application-orm.yml

@@ -1,76 +1,94 @@
-#spring:
-#  datasource:
-#    type: com.alibaba.druid.pool.DruidDataSource
-
-###################  mybatis-plus配置  ###################
-mybatis-plus:
-  mapper-locations: classpath*:mapping/**/*.xml
-#  type-aliases-package: com.gxzc.zen.api.bus.mapper,com.gxzc.zen.api.sys.mapper #,com.gxzc.zen.api.useage.mapper
-  global-config:
-    id-type: 0  #0:数据库ID自增   1:用户输入id  2:全局唯一id(IdWorker)  3:全局唯一ID(uuid)
-    db-column-underline: true
-    refresh-mapper: true
-    logic-delete-value: 0
-    logic-not-delete-value: 1
-    sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
-  configuration:
-    map-underscore-to-camel-case: true
-    cache-enabled: true #配置的缓存的全局开关
-    lazyLoadingEnabled: true #延时加载的开关
-    multipleResultSetsEnabled: true #延时加载一个属性时会加载该对象全部属性,否则按需加载属性
-    interceptors: com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor
-    # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql语句,调试用
-
+orm:
+  multi-datasource-enable: true # 多数据源开关
 
 ################## Alibaba Druid 配置 ##################
 spring:
   datasource:
+    type: com.alibaba.druid.pool.DruidDataSource
     druid:
       stat-view-servlet:
         enabled: true
         login-username: root
         login-password: root
         reset-enable: false
+      ############ 以下是关闭多数据源时使用的默认数据源 ############
+      username: root
+      password: root
+      url: jdbc:mysql://127.0.0.1:3306/archives_sys?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
+      driver-class-name: com.mysql.jdbc.Driver
+      test-on-borrow: false
+      test-on-return: false
+      test-while-idle: true
+      validation-query: SELECT 1
+      async-init: false
+      name: system
+      filters: logback,log4j,wall,mergeStat
+      keep-alive: false
+      initial-size: 5
+      min-idle: 5
+      max-active: 20
+      time-between-eviction-runs-millis: 60000
+      min-evictable-idle-time-millis: 30000
 
+################## 数据源 配置 ##################
 datasource:
   sys:
-    name: archives_sys
+    name: system
     url: jdbc:mysql://192.168.1.124:3307/archives_sys?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
+    driver-class-name: com.mysql.jdbc.Driver
     username: archives
     password: archives
-    testWhileIdle: true
-    testOnBorrow: false
-    testOnReturn: false
-    validationQuery: SELECT 1
-    asyncInit: false # 异步初始化
-    filters: log4j,wall,mergeStat
-    keepAlive: false
-    driver-class-name: com.mysql.jdbc.Driver
-    initialize: false #指定初始化数据源,是否用data.sql来初始化,默认: true
-    initialSize: 5
-    minIdle: 5
-    maxActive: 20
-    timeBetweenEvictionRunsMillis: 60000
-    minEvictableIdleTimeMillis: 30000
+    test-on-borrow: false
+    test-on-return: false
+    test-while-idle: true
+    validation-query: SELECT 1
+    async-init: false
+    filters: logback,log4j,wall,mergeStat
+    keep-alive: false
+    initial-size: 5
+    min-idle: 5
+    max-active: 20
+    time-between-eviction-runs-millis: 60000
+    min-evictable-idle-time-millis: 30000
   bus:
-    name: archives_bus
+    name: business
     url: jdbc:mysql://192.168.1.124:3307/archives_mgr?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
+    driver-class-name: com.mysql.jdbc.Driver
     username: archives
     password: archives
-    testWhileIdle: true
-    testOnBorrow: false
-    testOnReturn: false
-    validationQuery: SELECT 1
-    asyncInit: false # 异步初始化
-    filters: log4j,wall,mergeStat
-    keepAlive: false
-    driver-class-name: com.mysql.jdbc.Driver
-    initialize: false #指定初始化数据源,是否用data.sql来初始化,默认: true
-    initialSize: 5
-    minIdle: 5
-    maxActive: 20
-    timeBetweenEvictionRunsMillis: 60000
-    minEvictableIdleTimeMillis: 30000
+    test-on-borrow: false
+    test-on-return: false
+    test-while-idle: true
+    validation-query: SELECT 1
+    async-init: false
+    filters: logback,log4j,wall,mergeStat
+    keep-alive: false
+    initial-size: 5
+    min-idle: 5
+    max-active: 20
+    time-between-eviction-runs-millis: 60000
+    min-evictable-idle-time-millis: 30000
+
+###################  mybatis-plus配置  ###################
+mybatis-plus:
+  mapper-locations: classpath*:mapping/**/*.xml
+  type-aliases-package: com.gxzc.zen.api.bus.mapper,com.gxzc.zen.api.sys.mapper
+  global-config:
+    id-type: 0  #0:数据库ID自增   1:用户输入id  2:全局唯一id(IdWorker)  3:全局唯一ID(uuid)
+    db-column-underline: true
+    refresh-mapper: true
+    # logic-delete-value: 0
+    # logic-not-delete-value: 1
+    sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
+    meta-object-handler: com.gxzc.zen.orm.CustomMetaObjectHandler
+  configuration:
+    map-underscore-to-camel-case: true
+    cache-enabled: true #配置的缓存的全局开关
+    lazyLoadingEnabled: true #延时加载的开关
+    multipleResultSetsEnabled: true #延时加载一个属性时会加载该对象全部属性,否则按需加载属性
+    interceptors: com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor
+    # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql语句,调试用
+
 
 ##sharding-jdbc
 #sharding:

+ 3 - 0
zen-umps/src/main/kotlin/com/gxzc/zen/umps/KissoAuthorization.kt

@@ -6,8 +6,11 @@ import com.gxzc.zen.common.util.PlatformUtil
 import org.apache.commons.lang3.StringUtils
 import org.springframework.beans.factory.annotation.Autowired
 import org.springframework.cache.CacheManager
+import org.springframework.stereotype.Component
 
+@Component
 class KissoAuthorization : SSOAuthorization {
+
     @Autowired
     private lateinit var cacheManager: CacheManager
 

+ 1 - 1
zen-web/build.gradle

@@ -1,7 +1,7 @@
 apply plugin: 'war'
 
 dependencies {
-//    compile project(":zen-orm")
+    compile project(":zen-orm")
     compile project(":zen-core")
     compile project(":zen-api")
     compile project(":zen-umps")

+ 1 - 1
zen-web/src/main/kotlin/com/gxzc/zen/MainApplication.kt

@@ -6,7 +6,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder
 import org.springframework.boot.web.support.SpringBootServletInitializer
 
 
-@SpringBootApplication(exclude = [])
+@SpringBootApplication//(exclude = [])
 class MainApplication : SpringBootServletInitializer() {
     override fun configure(builder: SpringApplicationBuilder?): SpringApplicationBuilder? {
         return builder?.sources(MainApplication::class.java)

+ 18 - 2
zen-web/src/main/kotlin/com/gxzc/zen/controller/ExampleController.kt

@@ -1,9 +1,12 @@
 package com.gxzc.zen.controller
 
-import com.gxzc.zen.api.bus.service.IMgrFondsService
+import com.baomidou.kisso.annotation.Action
+import com.baomidou.kisso.annotation.Login
+import com.gxzc.zen.api.sys.service.ISysPermissionService
 import com.gxzc.zen.api.sys.service.ISysUserService
 import org.slf4j.LoggerFactory
 import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.cache.CacheManager
 import org.springframework.web.bind.annotation.GetMapping
 import org.springframework.web.bind.annotation.RestController
 
@@ -15,11 +18,14 @@ class ExampleController {
     }
 
     @Autowired
-    private lateinit var mgrFondsService: IMgrFondsService
+    private lateinit var cacheManager: CacheManager
 
     @Autowired
     private lateinit var sysUserService: ISysUserService
 
+    @Autowired
+    private lateinit var sysPermissionService: ISysPermissionService
+
     @GetMapping("testTransaction")
     fun testTransaction() {
 //        mgrFondsService.testTransaction()
@@ -29,4 +35,14 @@ class ExampleController {
     fun testLoad() {
 //        sysUserService.selectListCacheable()
     }
+
+    @GetMapping("testCache")
+    @Login(action = Action.Skip)
+    fun testCache() {
+        println(cacheManager.cacheNames)
+
+        val a = sysPermissionService.getPermissionByUserId(1)
+
+        val test = cacheManager.getCache("user")["test1"]
+    }
 }

+ 1 - 1
zen-web/src/main/resources/application.yml

@@ -6,7 +6,7 @@ server:
 spring:
   profiles:
     active: dev
-    include: orm-local,mq,cache,umps
+    include: orm-local,mq,cache,umps,platform
 #  redis:
 #    host: localhost
 #    port: 6379