PermissionUtil.kt 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package com.gxzc.zen.umps.util
  2. import com.gxzc.zen.umps.common.Permission
  3. import org.slf4j.LoggerFactory
  4. import org.springframework.util.Assert
  5. /**
  6. *
  7. * @author NorthLan
  8. * @date 2018/2/6
  9. * @url https://noahlan.com
  10. */
  11. object PermissionUtil {
  12. private val logger = LoggerFactory.getLogger(PermissionUtil::class.java)
  13. /**
  14. * 权限判定
  15. * @param needPermString 需要的权限
  16. * @param userPerm 用户权限列表
  17. */
  18. fun isPermitted(needPermString: String, userPerm: HashSet<String>): Boolean {
  19. try {
  20. assertPermissionString(needPermString)
  21. val userPermSet = convertToPermissionSet(userPerm)
  22. val needPerm = convertToPermission(needPermString)
  23. // 验证逻辑 platformId=0 为通用(超级)权限
  24. userPermSet
  25. .filter { it.perm == needPerm.perm && verifyCRUD(needPerm.crud, it.crud) }
  26. .forEach {
  27. // 验证平台
  28. return if (it.platformId == 0) {
  29. true
  30. } else {
  31. it.platformId == needPerm.platformId
  32. }
  33. }
  34. } catch (e: RuntimeException) {
  35. logger.error("权限验证系统错误...", e)
  36. return false
  37. }
  38. return false
  39. }
  40. /**
  41. * 验证 CRUD 四项权限
  42. */
  43. private fun verifyCRUD(needCRUD: String, userCRUD: String): Boolean {
  44. needCRUD.forEach {
  45. if (it !in userCRUD) {
  46. return false
  47. }
  48. }
  49. return true
  50. }
  51. /**
  52. * 批量将权限串转换为权限实体
  53. */
  54. private fun convertToPermissionSet(perms: HashSet<String>): HashSet<Permission> {
  55. val result = hashSetOf<Permission>()
  56. perms.forEach({
  57. result.add(convertToPermission(it))
  58. })
  59. return result
  60. }
  61. /**
  62. * 将权限串转换为权限实体
  63. */
  64. private fun convertToPermission(str: String): Permission {
  65. return Permission(str)
  66. }
  67. private fun assertPermissionString(str: String) {
  68. Assert.notNull(str, "Permission string not be null.")
  69. val splitList = str.split(':')
  70. if (splitList.size < 3) {
  71. throw RuntimeException("permission字符串错误,必须为:分割且长度等于3")
  72. }
  73. }
  74. }