GraphQL API and utilities for the rpdata project
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.

48 lines
1.2 KiB

  1. package models
  2. // A Token contains the parsed results from an bearer token. Its methods are safe to use with a nil receiver, but
  3. // the userID should be checked.
  4. type Token struct {
  5. UserID string
  6. Permissions []string
  7. }
  8. // Authenticated returns true if the token is non-nil and parsed
  9. func (token *Token) Authenticated() bool {
  10. return token != nil && token.UserID != ""
  11. }
  12. // Permitted returns true if the token is non-nil and has the given permission or the "admin" permission
  13. func (token *Token) Permitted(permissions ...string) bool {
  14. if token == nil {
  15. return false
  16. }
  17. for _, tokenPermission := range token.Permissions {
  18. if tokenPermission == "admin" {
  19. return true
  20. }
  21. for _, permission := range permissions {
  22. if permission == tokenPermission {
  23. return true
  24. }
  25. }
  26. }
  27. return false
  28. }
  29. // PermittedUser checks the first permission if the user matches, the second otherwise. This is a common
  30. // pattern.
  31. func (token *Token) PermittedUser(userID, permissionIfUser, permissionOtherwise string) bool {
  32. if token == nil {
  33. return false
  34. }
  35. if token.UserID == userID {
  36. return token.Permitted(permissionIfUser)
  37. }
  38. return token.Permitted(permissionOtherwise)
  39. }