2017-05-23 18:56:10 +00:00
|
|
|
package security
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-07-07 21:57:52 +00:00
|
|
|
"errors"
|
2017-05-23 18:56:10 +00:00
|
|
|
"net/http"
|
|
|
|
|
2019-03-21 01:20:14 +00:00
|
|
|
"github.com/portainer/portainer/api"
|
2017-05-23 18:56:10 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
contextKey int
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
contextAuthenticationKey contextKey = iota
|
|
|
|
contextRestrictedRequest
|
|
|
|
)
|
|
|
|
|
|
|
|
// storeTokenData stores a TokenData object inside the request context and returns the enhanced context.
|
|
|
|
func storeTokenData(request *http.Request, tokenData *portainer.TokenData) context.Context {
|
|
|
|
return context.WithValue(request.Context(), contextAuthenticationKey, tokenData)
|
|
|
|
}
|
|
|
|
|
|
|
|
// RetrieveTokenData returns the TokenData object stored in the request context.
|
|
|
|
func RetrieveTokenData(request *http.Request) (*portainer.TokenData, error) {
|
|
|
|
contextData := request.Context().Value(contextAuthenticationKey)
|
|
|
|
if contextData == nil {
|
2020-07-07 21:57:52 +00:00
|
|
|
return nil, errors.New("Unable to find JWT data in request context")
|
2017-05-23 18:56:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
tokenData := contextData.(*portainer.TokenData)
|
|
|
|
return tokenData, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// storeRestrictedRequestContext stores a RestrictedRequestContext object inside the request context
|
|
|
|
// and returns the enhanced context.
|
|
|
|
func storeRestrictedRequestContext(request *http.Request, requestContext *RestrictedRequestContext) context.Context {
|
|
|
|
return context.WithValue(request.Context(), contextRestrictedRequest, requestContext)
|
|
|
|
}
|
|
|
|
|
|
|
|
// RetrieveRestrictedRequestContext returns the RestrictedRequestContext object stored in the request context.
|
|
|
|
func RetrieveRestrictedRequestContext(request *http.Request) (*RestrictedRequestContext, error) {
|
|
|
|
contextData := request.Context().Value(contextRestrictedRequest)
|
|
|
|
if contextData == nil {
|
2020-07-07 21:57:52 +00:00
|
|
|
return nil, errors.New("Unable to find security details in request context")
|
2017-05-23 18:56:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
requestContext := contextData.(*RestrictedRequestContext)
|
|
|
|
return requestContext, nil
|
|
|
|
}
|