From 4c2b1b945ca28392eb79637646fbf67c3ad10750 Mon Sep 17 00:00:00 2001 From: chrisforrette Date: Mon, 17 Feb 2020 17:13:09 -0800 Subject: [PATCH] Adding GetCurrentUser method --- user.go | 15 +++++++++++++++ user_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/user.go b/user.go index 6d08e7fd..b3cebc71 100644 --- a/user.go +++ b/user.go @@ -77,6 +77,11 @@ type GetUserOptions struct { Includes []string `url:"include,omitempty,brackets"` } +// GetCurrentUserOptions is the data structure used when calling the GetCurrentUser API endpoint. +type GetCurrentUserOptions struct { + Includes [] string `url:"include,omitempty,brackets"` +} + // ListUsers lists users of your PagerDuty account, optionally filtered by a search query. func (c *Client) ListUsers(o ListUsersOptions) (*ListUsersResponse, error) { v, err := query.Values(o) @@ -123,6 +128,16 @@ func (c *Client) UpdateUser(u User) (*User, error) { return getUserFromResponse(c, resp, err) } +// GetCurrentUser gets details about the authenticated user when using a user-level API key or OAuth token +func (c *Client) GetCurrentUser(o GetCurrentUserOptions) (*User, error) { + v, err := query.Values(o) + if err != nil { + return nil, err + } + resp, err := c.get("/users/me?" + v.Encode()) + return getUserFromResponse(c, resp, err) +} + func getUserFromResponse(c *Client, resp *http.Response, err error) (*User, error) { if err != nil { return nil, err diff --git a/user_test.go b/user_test.go index fc5fe71a..924ef3fb 100644 --- a/user_test.go +++ b/user_test.go @@ -151,6 +151,35 @@ func TestUser_Update(t *testing.T) { testEqual(t, want, res) } +// Get Current User +func TestUser_GetCurrent(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/users/me", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + w.Write([]byte(`{"user": {"id": "1", "email":"foo@bar.com"}}`)) + }) + + var client = &Client{apiEndpoint: server.URL, authToken: "foo", HTTPClient: defaultHTTPClient} + opts := GetCurrentUserOptions{ + Includes: []string{}, + } + res, err := client.GetCurrentUser(opts) + + want := &User{ + APIObject: APIObject{ + ID: "1", + }, + Email: "foo@bar.com", + } + + if err != nil { + t.Fatal(err) + } + testEqual(t, want, res) +} + // List User Contactmethods func TestUser_ListContactMethods(t *testing.T) { setup()