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.

153 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. for _, permission := range permissions {
  84. found := false
  85. for _, userPermission := range user.Permissions {
  86. if permission == userPermission {
  87. found = true
  88. break
  89. }
  90. }
  91. if !found {
  92. return models.Token{}, ErrWrongPermissions
  93. }
  94. }
  95. return models.Token{UserID: user.ID, Permissions: permissions}, nil
  96. }
  97. func parseClaims(jwtClaims jwt.Claims) (userid string, permissions []string, err error) {
  98. mapClaims, ok := jwtClaims.(jwt.MapClaims)
  99. if !ok {
  100. return "", nil, ErrInvalidClaims
  101. }
  102. if !mapClaims.VerifyExpiresAt(time.Now().Unix(), true) {
  103. return "", nil, ErrExpired
  104. }
  105. if userid, ok = mapClaims["user"].(string); !ok {
  106. return "", nil, ErrInvalidClaims
  107. }
  108. if claimedPermissions, ok := mapClaims["permissions"].([]interface{}); ok {
  109. for _, permission := range claimedPermissions {
  110. if permission, ok := permission.(string); ok {
  111. permissions = append(permissions, permission)
  112. }
  113. }
  114. }
  115. if len(permissions) == 0 {
  116. return "", nil, ErrInvalidClaims
  117. }
  118. return
  119. }