jamfpro

package
v0.0.97 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 1, 2024 License: MIT Imports: 14 Imported by: 0

README

Jamf Pro API Handler

The Jamf Pro API Handler is an integral component of the Go API HTTP Client, designed specifically for seamless integration with the Jamf Pro API. This handler facilitates the encoding and decoding of requests and responses, manages API-specific headers, and constructs endpoints for efficient API communication.

Features

  • Endpoint Construction: Dynamically constructs API resource and authentication endpoints based on the instance name and predefined URL patterns.
  • Content-Type Handling: Determines the appropriate Content-Type header for requests, with specialized handling for both the Classic API (XML) and the JamfPro API (JSON).
  • Accept Header Management: Generates a weighted Accept header to indicate the client's capability to process various MIME types, prioritizing XML for compatibility with the Classic API.
  • Standard Headers: Provides a set of standard headers required for API requests, including Accept, Content-Type, and Authorization.
  • Request Marshaling: Encodes request bodies into the appropriate format (XML or JSON) based on the target API endpoint, with support for multipart/form-data encoding for file uploads.
  • Response Handling: Processes API responses, decoding them into the desired data structures and handling binary data responses where applicable.

The logic of this api handler is defined as follows: Classic API:

For requests (GET, POST, PUT, DELETE):

  • Encoding (Marshalling): Use XML format. For responses (GET, POST, PUT):
  • Decoding (Unmarshalling): Use XML format. For responses (DELETE):
  • Handle response codes as response body lacks anything useful. Headers
  • Sets accept headers based on weighting. XML out weighs JSON to ensure XML is returned
  • Sets content header as application/xml with edge case exceptions based on need.

JamfPro API:

For requests (GET, POST, PUT, DELETE):

  • Encoding (Marshalling): Use JSON format. For responses (GET, POST, PUT):
  • Decoding (Unmarshalling): Use JSON format. For responses (DELETE):
  • Handle response codes as response body lacks anything useful. Headers
  • Sets accept headers based on weighting. Jamf Pro API doesn't support XML, so MIME type is skipped and returns JSON
  • Set content header as application/json with edge case exceptions based on need.

Usage

To utilize the Jamf Pro API Handler within the Go API HTTP Client, instantiate the client with the Jamf Pro-specific configuration:

package main

import (
    "log"

    "github.com/deploymenttheory/go-api-http-client/httpclient"
    "github.com/deploymenttheory/go-api-http-client/apihandlers/jamfpro"
)

func main() {
    // Configuration for the HTTP client specific to Jamf Pro
    config := httpclient.ClientConfig{
        Environment: httpclient.EnvironmentConfig{
            InstanceName: "your-instance-name",
            APIType:      "jamfpro", // Specify the API type as "jamfpro"
        },
        // Other configuration settings...
    }

    // Initialize the Jamf Pro API handler with the configuration
    jamfHandler, err := jamfpro.LoadAPIHandler(config.Environment.APIType, config.Logger)
    if err != nil {
        log.Fatalf("Failed to initialize Jamf Pro API handler: %v", err)
    }

    // Use the handler for API interactions
    // Example: Constructing an API resource endpoint
    resourceURL := jamfHandler.ConstructAPIResourceEndpoint(config.Environment.InstanceName, "/path/to/resource", config.Logger)
    log.Printf("Constructed Resource URL: %s", resourceURL)

    // Proceed with making API calls using the constructed URLs and the configured HTTP client...
}

Documentation

Overview

jamfpro_api_error_messages.go

jamfpro_api_headers.go

jamfpro_api_request.go

jamfpro_api_handler.go

jamfpro_api_url.go

Index

Constants

View Source
const (
	APIName                            = "jamf pro"                      // APIName: represents the name of the API.
	DefaultBaseDomain                  = ".jamfcloud.com"                // DefaultBaseDomain: represents the base domain for the jamf instance.
	OAuthTokenEndpoint                 = "/api/oauth/token"              // OAuthTokenEndpoint: The endpoint to obtain an OAuth token.
	BearerTokenEndpoint                = "/api/v1/auth/token"            // BearerTokenEndpoint: The endpoint to obtain a bearer token.
	TokenRefreshEndpoint               = "/api/v1/auth/keep-alive"       // TokenRefreshEndpoint: The endpoint to refresh an existing token.
	TokenInvalidateEndpoint            = "/api/v1/auth/invalidate-token" // TokenInvalidateEndpoint: The endpoint to invalidate an active token.
	BearerTokenAuthenticationSupport   = true                            // BearerTokenAuthSuppport: A boolean to indicate if the API supports bearer token authentication.
	OAuthAuthenticationSupport         = true                            // OAuthAuthSuppport: A boolean to indicate if the API supports OAuth authentication.
	OAuthWithCertAuthenticationSupport = false                           // OAuthWithCertAuthSuppport: A boolean to indicate if the API supports OAuth with client certificate authentication.
)

Endpoint constants represent the URL suffixes used for Jamf API token interactions.

Variables

This section is empty.

Functions

func ExtractErrorMessageFromHTML

func ExtractErrorMessageFromHTML(htmlContent string) string

ExtractErrorMessageFromHTML attempts to parse an HTML error page and extract a combined human-readable error message.

func ParseJSONErrorResponse

func ParseJSONErrorResponse(body []byte) (string, error)

ParseJSONErrorResponse parses the JSON error message from the response body.

Types

type APIHandlerError added in v0.0.59

type APIHandlerError struct {
	HTTPStatusCode int                    `json:"httpStatusCode"`
	ErrorType      string                 `json:"errorType"`
	ErrorMessage   string                 `json:"errorMessage"`
	ExtraDetails   map[string]interface{} `json:"extraDetails"`
}

APIHandlerError represents an error response from the Jamf Pro API.

type ConfigMap

type ConfigMap map[string]EndpointConfig

ConfigMap is a map that associates endpoint URL patterns with their corresponding configurations. The map's keys are strings that identify the endpoint, and the values are EndpointConfig structs that hold the configuration for that endpoint.

type EndpointConfig

type EndpointConfig struct {
	Accept      string  `json:"accept"`       // Accept specifies the MIME type the endpoint can handle in responses.
	ContentType *string `json:"content_type"` // ContentType, if not nil, specifies the MIME type to set for requests sent to the endpoint. A pointer is used to distinguish between a missing field and an empty string.
}

EndpointConfig is a struct that holds configuration details for a specific API endpoint. It includes what type of content it can accept and what content type it should send.

type JamfAPIHandler

type JamfAPIHandler struct {
	OverrideBaseDomain string        // OverrideBaseDomain is used to override the base domain for URL construction.
	InstanceName       string        // InstanceName is the name of the Jamf instance.
	Logger             logger.Logger // Logger is the structured logger used for logging.
}

JamfAPIHandler implements the APIHandler interface for the Jamf Pro API.

func (*JamfAPIHandler) ConstructAPIAuthEndpoint

func (j *JamfAPIHandler) ConstructAPIAuthEndpoint(instanceName string, endpointPath string, log logger.Logger) string

ConstructAPIAuthEndpoint constructs the full URL for a Jamf API auth endpoint path and logs the URL.

func (*JamfAPIHandler) ConstructAPIResourceEndpoint

func (j *JamfAPIHandler) ConstructAPIResourceEndpoint(instanceName string, endpointPath string, log logger.Logger) string

ConstructAPIResourceEndpoint constructs the full URL for a Jamf API resource endpoint path and logs the URL.

func (*JamfAPIHandler) GetAPIBearerTokenAuthenticationSupportStatus added in v0.0.7

func (j *JamfAPIHandler) GetAPIBearerTokenAuthenticationSupportStatus() bool

GetAPIBearerTokenAuthenticationSupportStatus returns a boolean indicating if bearer token authentication is supported in the api handler.

func (*JamfAPIHandler) GetAPIOAuthAuthenticationSupportStatus added in v0.0.7

func (j *JamfAPIHandler) GetAPIOAuthAuthenticationSupportStatus() bool

GetAPIOAuthAuthenticationSupportStatus returns a boolean indicating if OAuth authentication is supported in the api handler.

func (*JamfAPIHandler) GetAPIOAuthWithCertAuthenticationSupportStatus added in v0.0.7

func (j *JamfAPIHandler) GetAPIOAuthWithCertAuthenticationSupportStatus() bool

GetAPIOAuthWithCertAuthenticationSupportStatus returns a boolean indicating if OAuth with client certificate authentication is supported in the api handler.

func (*JamfAPIHandler) GetAPIRequestHeaders added in v0.0.43

func (j *JamfAPIHandler) GetAPIRequestHeaders(endpoint string) map[string]string

GetAPIRequestHeaders returns a map of standard headers required for making API requests.

func (*JamfAPIHandler) GetAcceptHeader

func (j *JamfAPIHandler) GetAcceptHeader() string

GetAcceptHeader constructs and returns a weighted Accept header string for HTTP requests. The Accept header indicates the MIME types that the client can process and prioritizes them based on the quality factor (q) parameter. Higher q-values signal greater preference. This function specifies a range of MIME types with their respective weights, ensuring that the server is informed of the client's versatile content handling capabilities while indicating a preference for XML. The specified MIME types cover common content formats like images, JSON, XML, HTML, plain text, and certificates, with a fallback option for all other types.

func (*JamfAPIHandler) GetBearerTokenEndpoint

func (j *JamfAPIHandler) GetBearerTokenEndpoint() string

GetBearerTokenEndpoint returns the endpoint for obtaining a bearer token. Used for constructing API URLs for the http client.

func (*JamfAPIHandler) GetContentTypeHeader

func (j *JamfAPIHandler) GetContentTypeHeader(endpoint string, log logger.Logger) string

GetContentTypeHeader determines the appropriate Content-Type header for a given API endpoint. It attempts to find a content type that matches the endpoint prefix in the global configMap. If a match is found and the content type is defined (not nil), it returns the specified content type. If the content type is nil or no match is found in configMap, it falls back to default behaviors: - For url endpoints starting with "/JSSResource", it defaults to "application/xml" for the Classic API. - For url endpoints starting with "/api", it defaults to "application/json" for the JamfPro API. If the endpoint does not match any of the predefined patterns, "application/json" is used as a fallback. This method logs the decision process at various stages for debugging purposes.

func (*JamfAPIHandler) GetDefaultBaseDomain

func (j *JamfAPIHandler) GetDefaultBaseDomain() string

GetDefaultBaseDomain returns the default base domain used for constructing API URLs to the http client.

func (*JamfAPIHandler) GetOAuthTokenEndpoint

func (j *JamfAPIHandler) GetOAuthTokenEndpoint() string

GetOAuthTokenEndpoint returns the endpoint for obtaining an OAuth token. Used for constructing API URLs for the http client.

func (*JamfAPIHandler) GetTokenInvalidateEndpoint

func (j *JamfAPIHandler) GetTokenInvalidateEndpoint() string

GetTokenInvalidateEndpoint returns the endpoint for invalidating an active token. Used for constructing API URLs for the http client.

func (*JamfAPIHandler) GetTokenRefreshEndpoint

func (j *JamfAPIHandler) GetTokenRefreshEndpoint() string

GetTokenRefreshEndpoint returns the endpoint for refreshing an existing token. Used for constructing API URLs for the http client.

func (*JamfAPIHandler) HandleAPIErrorResponse added in v0.0.62

func (j *JamfAPIHandler) HandleAPIErrorResponse(resp *http.Response, out interface{}, log logger.Logger) error

func (*JamfAPIHandler) HandleAPISuccessResponse added in v0.0.62

func (j *JamfAPIHandler) HandleAPISuccessResponse(resp *http.Response, out interface{}, log logger.Logger) error

Functions

func (*JamfAPIHandler) MarshalMultipartRequest

func (j *JamfAPIHandler) MarshalMultipartRequest(fields map[string]string, files map[string]string, log logger.Logger) ([]byte, string, error)

MarshalMultipartFormData takes a map with form fields and file paths and returns the encoded body and content type.

func (*JamfAPIHandler) MarshalRequest

func (j *JamfAPIHandler) MarshalRequest(body interface{}, method string, endpoint string, log logger.Logger) ([]byte, error)

MarshalRequest encodes the request body according to the endpoint for the API.

func (*JamfAPIHandler) ReturnAPIErrorResponse added in v0.0.59

func (j *JamfAPIHandler) ReturnAPIErrorResponse(resp *http.Response) *APIHandlerError

ReturnAPIErrorResponse parses an HTTP error response from the Jamf Pro API.

func (*JamfAPIHandler) SetBaseDomain added in v0.0.7

func (j *JamfAPIHandler) SetBaseDomain() string

SetBaseDomain returns the appropriate base domain for URL construction. It uses j.OverrideBaseDomain if set, otherwise falls back to DefaultBaseDomain.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL