role.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // SiYuan - Refactor your thinking
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package model
  17. import "github.com/gin-gonic/gin"
  18. type Role uint
  19. const (
  20. RoleContextKey = "role"
  21. )
  22. const (
  23. RoleAdministrator Role = iota // 管理员
  24. RoleEditor // 编辑者
  25. RoleReader // 读者
  26. RoleVisitor // 匿名访问者
  27. )
  28. func IsValidRole(role Role, roles []Role) bool {
  29. for _, role_ := range roles {
  30. if role == role_ {
  31. return true
  32. }
  33. }
  34. return false
  35. }
  36. func IsReadOnlyRole(role Role) bool {
  37. return IsValidRole(role, []Role{
  38. RoleReader,
  39. RoleVisitor,
  40. })
  41. }
  42. func GetGinContextRole(c *gin.Context) Role {
  43. if role, exists := c.Get(RoleContextKey); exists {
  44. return role.(Role)
  45. } else {
  46. return RoleVisitor
  47. }
  48. }
  49. func IsAdminRoleContext(c *gin.Context) bool {
  50. return GetGinContextRole(c) == RoleAdministrator
  51. }