Skip to content

Commit 902a41c

Browse files
committed
feat: support the new oauth2 endpoint in Jira cloud
1 parent e6b4ef6 commit 902a41c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

internal/client/upload.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,13 @@ package client
22

33
import (
44
"context"
5+
"encoding/json"
56
"fmt"
7+
"io"
68
"log"
79
"net/http"
10+
"net/url"
11+
"path"
812
"time"
913

1014
jira "github.com/andygrunwald/go-jira"
@@ -66,6 +70,32 @@ func newOAuth2HTTPClient(ctx context.Context) (*http.Client, oauth2.TokenSource,
6670
return httpClient, tokenSource, auth, nil
6771
}
6872

73+
func OAuth2JiraURL(client *http.Client, jiraURL string) (string, error) {
74+
tenantInfo := struct {
75+
CloudID string `json:"cloudId"`
76+
}{}
77+
urlTmpl := "https://api.atlassian.com/ex/jira/%s"
78+
ju, err := url.Parse(jiraURL)
79+
if err != nil {
80+
return "", fmt.Errorf("couldn't parse Jira URL: %v", err)
81+
}
82+
ju.Path = path.Join(ju.Path, "/_edge/tenant_info")
83+
// get the cloud ID
84+
resp, err := client.Get(ju.String())
85+
if err != nil {
86+
return "", fmt.Errorf("couldn't get tenant info: %v", err)
87+
}
88+
defer resp.Body.Close()
89+
data, err := io.ReadAll(resp.Body)
90+
if err != nil {
91+
return "", fmt.Errorf("couldn't read response body: %v", err)
92+
}
93+
if err = json.Unmarshal(data, &tenantInfo); err != nil {
94+
return "", fmt.Errorf("couldn't unmrashal tenant info: %v", err)
95+
}
96+
return fmt.Sprintf(urlTmpl, tenantInfo.CloudID), nil
97+
}
98+
6999
// UploadWorklogs uploads the given worklogs to Jira, with the
70100
// given day offset (e.g. -1 == yesterday).
71101
func UploadWorklogs(ctx context.Context, jiraURL string,
@@ -85,6 +115,12 @@ func UploadWorklogs(ctx context.Context, jiraURL string,
85115
if err != nil {
86116
return fmt.Errorf("couldn't construct OAuth2 HTTP client: %v", err)
87117
}
118+
// rewrite the Jira URL as per the docs for OAuth2 clients
119+
// https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#authentication
120+
jiraURL, err = OAuth2JiraURL(httpClient, jiraURL)
121+
if err != nil {
122+
return fmt.Errorf("couldn't construct OAuth2 Jira URL: %v", err)
123+
}
88124
}
89125
// wrap this http client in a jira client via jira.NewClient
90126
c, err := jira.NewClient(httpClient, jiraURL)

0 commit comments

Comments
 (0)