Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding OAuth token support #203

Merged
merged 1 commit into from
Feb 25, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ const (
apiEndpoint = "https://api.pagerduty.com"
)

// The type of authentication to use with the API client
type authType int

const (
// Account/user API token authentication
apiToken authType = iota

// OAuth token authentication
oauthToken
)

// APIObject represents generic api json response that is shared by most
// domain object (like escalation
type APIObject struct {
Expand Down Expand Up @@ -88,17 +99,31 @@ type Client struct {
authToken string
apiEndpoint string

// Authentication type to use for API
authType authType

// HTTPClient is the HTTP client used for making requests against the
// PagerDuty API. You can use either *http.Client here, or your own
// implementation.
HTTPClient HTTPClient
}

// NewClient creates an API client
// NewClient creates an API client using an account/user API token
func NewClient(authToken string) *Client {
return &Client{
authToken: authToken,
apiEndpoint: apiEndpoint,
authType: apiToken,
HTTPClient: defaultHTTPClient,
}
}

// NewOAuthClient creates an API client using an OAuth token
func NewOAuthClient(authToken string) *Client {
return &Client{
authToken: authToken,
apiEndpoint: apiEndpoint,
authType: oauthToken,
HTTPClient: defaultHTTPClient,
}
}
Expand Down Expand Up @@ -142,7 +167,13 @@ func (c *Client) do(method, path string, body io.Reader, headers *map[string]str
}
req.Header.Set("User-Agent", "go-pagerduty/"+Version)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Token token="+c.authToken)

switch c.authType {
case oauthToken:
req.Header.Set("Authorization", "Bearer "+c.authToken)
default:
req.Header.Set("Authorization", "Token token="+c.authToken)
}

resp, err := c.HTTPClient.Do(req)
return c.checkResponse(resp, err)
Expand Down