You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.3 KiB

1 year ago
  1. package auth
  2. import (
  3. "fmt"
  4. )
  5. type User struct {
  6. ID string `json:"id"`
  7. Name string `json:"name"`
  8. }
  9. type UserInfo struct {
  10. User
  11. Permissions []string `json:"permissions"`
  12. }
  13. type Result struct {
  14. User *UserInfo `json:"user"`
  15. Token string `json:"token,omitempty"`
  16. Session string `json:"session,omitempty"`
  17. PasswordChangeRequired bool `json:"passwordChangeRequired"`
  18. }
  19. func (user *UserInfo) HasIDOrPermission(userID, subject, action string) bool {
  20. return user.HasID(userID) || user.HasPermission(subject, action)
  21. }
  22. func (user *UserInfo) HasID(id string) bool {
  23. return user != nil && user.ID == id
  24. }
  25. func (user *UserInfo) HasOpPermission(userID, subject, action string) bool {
  26. if !user.HasID(userID) && !user.HasPermission(subject, "admin") {
  27. return false
  28. }
  29. return user.HasPermission(subject, action)
  30. }
  31. func (user *UserInfo) HasPermission(subject, action string) bool {
  32. if user == nil {
  33. return false
  34. }
  35. anyAll := "*.*"
  36. anyAction := fmt.Sprintf("%s.*", subject)
  37. anySubject := fmt.Sprintf("*.%s", action)
  38. specific := fmt.Sprintf("%s.%s", subject, action)
  39. if action == "admin" {
  40. anyAction = specific
  41. }
  42. for _, perm := range user.Permissions {
  43. if perm == anyAll || perm == anyAction || perm == anySubject || perm == specific {
  44. return true
  45. }
  46. }
  47. return false
  48. }