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.

154 lines
3.8 KiB

  1. package auth
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "git.aiterp.net/rpdata/api/models"
  10. "git.aiterp.net/rpdata/api/models/users"
  11. jwt "github.com/dgrijalva/jwt-go"
  12. )
  13. var contextKey = &struct{ data string }{"Token Context Key"}
  14. // ErrNoKid is returned if the key id is missing from the jwt token header,
  15. var ErrNoKid = errors.New("Missing \"kid\" field in token")
  16. // ErrKeyNotFound is returned if the key wasn't found.
  17. var ErrKeyNotFound = errors.New("Key not found")
  18. // ErrInvalidClaims is returned by parseClaims if the claims cannot be parsed
  19. var ErrInvalidClaims = errors.New("Invalid claims in token")
  20. // ErrExpired is returned by parseClaims if the expiry date is in the past
  21. var ErrExpired = errors.New("Claims have already expired")
  22. // ErrWrongUser is returned by CheckToken if the key cannot represent this user
  23. var ErrWrongUser = errors.New("Key is not valid for this user")
  24. // ErrWrongPermissions is returned by CheckToken if the key cannot claim one or more of its permissions
  25. var ErrWrongPermissions = errors.New("User does not have these permissions")
  26. // ErrDeletedUser is returned by CheckToken if the key can represent this user, but the user doesn't exist.
  27. var ErrDeletedUser = errors.New("User was not found")
  28. // TokenFromContext gets the token from context.
  29. func TokenFromContext(ctx context.Context) *models.Token {
  30. token, ok := ctx.Value(contextKey).(*models.Token)
  31. if !ok {
  32. return nil
  33. }
  34. return token
  35. }
  36. // RequestWithToken either returns the request, or the request with a new context that
  37. // has the token.
  38. func RequestWithToken(r *http.Request) *http.Request {
  39. header := r.Header.Get("Authorization")
  40. if header == "" {
  41. return r
  42. }
  43. if !strings.HasPrefix(header, "Bearer ") {
  44. return r
  45. }
  46. token, err := CheckToken(header[7:])
  47. if err != nil {
  48. return r
  49. }
  50. return r.WithContext(context.WithValue(r.Context(), contextKey, &token))
  51. }
  52. // CheckToken reads the token string and returns a token if everything is kosher.
  53. func CheckToken(tokenString string) (token models.Token, err error) {
  54. var key Key
  55. jwtToken, err := jwt.Parse(tokenString, func(jwtToken *jwt.Token) (interface{}, error) {
  56. if _, ok := jwtToken.Method.(*jwt.SigningMethodHMAC); !ok {
  57. return nil, fmt.Errorf("Unexpected signing method: %v", jwtToken.Header["alg"])
  58. }
  59. kid, ok := jwtToken.Header["kid"].(string)
  60. if !ok {
  61. return nil, ErrNoKid
  62. }
  63. key, err = FindKey(kid)
  64. if err != nil || key.ID == "" {
  65. return nil, ErrKeyNotFound
  66. }
  67. return []byte(key.Secret), nil
  68. })
  69. if err != nil {
  70. return models.Token{}, err
  71. }
  72. userid, permissions, err := parseClaims(jwtToken.Claims)
  73. if err != nil {
  74. return models.Token{}, err
  75. }
  76. if !key.ValidForUser(userid) {
  77. return models.Token{}, ErrWrongUser
  78. }
  79. user, err := users.Ensure(userid)
  80. if err != nil {
  81. return models.Token{}, ErrDeletedUser
  82. }
  83. acceptedPermissions := make([]string, 0, 8)
  84. for _, permission := range permissions {
  85. found := false
  86. for _, userPermission := range user.Permissions {
  87. if permission == userPermission {
  88. found = true
  89. break
  90. }
  91. }
  92. if found {
  93. acceptedPermissions = append(acceptedPermissions, permission)
  94. }
  95. }
  96. return models.Token{UserID: user.ID, Permissions: acceptedPermissions}, nil
  97. }
  98. func parseClaims(jwtClaims jwt.Claims) (userid string, permissions []string, err error) {
  99. mapClaims, ok := jwtClaims.(jwt.MapClaims)
  100. if !ok {
  101. return "", nil, ErrInvalidClaims
  102. }
  103. if !mapClaims.VerifyExpiresAt(time.Now().Unix(), true) {
  104. return "", nil, ErrExpired
  105. }
  106. if userid, ok = mapClaims["user"].(string); !ok {
  107. return "", nil, ErrInvalidClaims
  108. }
  109. if claimedPermissions, ok := mapClaims["permissions"].([]interface{}); ok {
  110. for _, permission := range claimedPermissions {
  111. if permission, ok := permission.(string); ok {
  112. permissions = append(permissions, permission)
  113. }
  114. }
  115. }
  116. if len(permissions) == 0 {
  117. return "", nil, ErrInvalidClaims
  118. }
  119. return
  120. }