2022-02-23 20:02:02 +01:00
|
|
|
package jwtclaims
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/golang-jwt/jwt"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2022-03-01 15:22:18 +01:00
|
|
|
TokenUserProperty = "user"
|
|
|
|
AccountIDSuffix = "wt_account_id"
|
|
|
|
DomainIDSuffix = "wt_account_domain"
|
|
|
|
DomainCategorySuffix = "wt_account_domain_category"
|
|
|
|
UserIDClaim = "sub"
|
2022-02-23 20:02:02 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// Extract function type
|
|
|
|
type ExtractClaims func(r *http.Request, authAudiance string) AuthorizationClaims
|
|
|
|
|
|
|
|
// ClaimsExtractor struct that holds the extract function
|
|
|
|
type ClaimsExtractor struct {
|
|
|
|
ExtractClaimsFromRequestContext ExtractClaims
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewClaimsExtractor returns an extractor, and if provided with a function with ExtractClaims signature,
|
|
|
|
// then it will use that logic. Uses ExtractClaimsFromRequestContext by default
|
|
|
|
func NewClaimsExtractor(e ExtractClaims) *ClaimsExtractor {
|
|
|
|
var extractFunc ExtractClaims
|
|
|
|
if extractFunc = e; extractFunc == nil {
|
|
|
|
extractFunc = ExtractClaimsFromRequestContext
|
|
|
|
}
|
|
|
|
|
|
|
|
return &ClaimsExtractor{
|
|
|
|
ExtractClaimsFromRequestContext: extractFunc,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ExtractClaimsFromRequestContext extracts claims from the request context previously filled by the JWT token (after auth)
|
2022-05-05 20:02:15 +02:00
|
|
|
func ExtractClaimsFromRequestContext(r *http.Request, authAudience string) AuthorizationClaims {
|
2022-06-14 10:32:54 +02:00
|
|
|
if r.Context().Value(TokenUserProperty) == nil {
|
|
|
|
return AuthorizationClaims{}
|
|
|
|
}
|
2022-02-23 20:02:02 +01:00
|
|
|
token := r.Context().Value(TokenUserProperty).(*jwt.Token)
|
2022-05-05 20:02:15 +02:00
|
|
|
return ExtractClaimsWithToken(token, authAudience)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ExtractClaimsWithToken extracts claims from the token (after auth)
|
|
|
|
func ExtractClaimsWithToken(token *jwt.Token, authAudience string) AuthorizationClaims {
|
2022-02-23 20:02:02 +01:00
|
|
|
claims := token.Claims.(jwt.MapClaims)
|
|
|
|
jwtClaims := AuthorizationClaims{}
|
|
|
|
jwtClaims.UserId = claims[UserIDClaim].(string)
|
2022-05-05 20:02:15 +02:00
|
|
|
accountIdClaim, ok := claims[authAudience+AccountIDSuffix]
|
2022-02-23 20:02:02 +01:00
|
|
|
if ok {
|
|
|
|
jwtClaims.AccountId = accountIdClaim.(string)
|
|
|
|
}
|
2022-05-05 20:02:15 +02:00
|
|
|
domainClaim, ok := claims[authAudience+DomainIDSuffix]
|
2022-02-23 20:02:02 +01:00
|
|
|
if ok {
|
|
|
|
jwtClaims.Domain = domainClaim.(string)
|
|
|
|
}
|
2022-05-05 20:02:15 +02:00
|
|
|
domainCategoryClaim, ok := claims[authAudience+DomainCategorySuffix]
|
2022-03-01 15:22:18 +01:00
|
|
|
if ok {
|
|
|
|
jwtClaims.DomainCategory = domainCategoryClaim.(string)
|
|
|
|
}
|
2022-02-23 20:02:02 +01:00
|
|
|
return jwtClaims
|
|
|
|
}
|