|
1 | 1 | package api
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "bytes" |
4 | 5 | "context"
|
| 6 | + "encoding/json" |
5 | 7 | "errors"
|
| 8 | + "io/ioutil" |
6 | 9 | "net/http"
|
7 | 10 | "net/http/httputil"
|
8 | 11 | "net/url"
|
9 | 12 | "regexp"
|
| 13 | + "strings" |
10 | 14 | "sync"
|
11 | 15 |
|
12 | 16 | "golang.org/x/oauth2"
|
@@ -169,13 +173,57 @@ func (bb *BitBucketGateway) authenticate(w http.ResponseWriter, r *http.Request)
|
169 | 173 | return errors.New("Access to endpoint not allowed: your role doesn't allow access")
|
170 | 174 | }
|
171 | 175 |
|
| 176 | +func rewriteBitBucketLink(link, endpointAPIURL, proxyAPIURL string) string { |
| 177 | + return proxyAPIURL + strings.TrimPrefix(link, endpointAPIURL) |
| 178 | +} |
| 179 | + |
| 180 | +func rewriteLinksInBitBucketResponse(resp *http.Response, endpointAPIURL, proxyAPIURL string) error { |
| 181 | + body, err := ioutil.ReadAll(resp.Body) |
| 182 | + if err != nil { |
| 183 | + return err |
| 184 | + } |
| 185 | + |
| 186 | + var b map[string]interface{} |
| 187 | + if err := json.Unmarshal(body, &b); err != nil { |
| 188 | + return err |
| 189 | + } |
| 190 | + |
| 191 | + if next, ok := b["next"].(string); ok { |
| 192 | + b["next"] = rewriteBitBucketLink(next, endpointAPIURL, proxyAPIURL) |
| 193 | + } |
| 194 | + |
| 195 | + if prev, ok := b["previous"].(string); ok { |
| 196 | + b["previous"] = rewriteBitBucketLink(prev, endpointAPIURL, proxyAPIURL) |
| 197 | + } |
| 198 | + |
| 199 | + newBody, err := json.Marshal(b) |
| 200 | + println(newBody) |
| 201 | + resp.Body = ioutil.NopCloser(bytes.NewReader(newBody)) |
| 202 | + |
| 203 | + return nil |
| 204 | +} |
| 205 | + |
172 | 206 | type BitBucketTransport struct{}
|
173 | 207 |
|
174 | 208 | func (t *BitBucketTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
| 209 | + ctx := r.Context() |
| 210 | + config := getConfig(ctx) |
175 | 211 | resp, err := http.DefaultTransport.RoundTrip(r)
|
176 |
| - if err == nil { |
177 |
| - // remove CORS headers from BitBucket and use our own |
178 |
| - resp.Header.Del("Access-Control-Allow-Origin") |
| 212 | + if err != nil { |
| 213 | + return resp, err |
179 | 214 | }
|
180 |
| - return resp, err |
| 215 | + |
| 216 | + // remove CORS headers from BitBucket and use our own |
| 217 | + resp.Header.Del("Access-Control-Allow-Origin") |
| 218 | + |
| 219 | + if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") { |
| 220 | + repo := config.BitBucket.Repo |
| 221 | + apiURL := singleJoiningSlash(config.BitBucket.Endpoint, "/repositories/"+repo) |
| 222 | + err = rewriteLinksInBitBucketResponse(resp, apiURL, "") |
| 223 | + if err != nil { |
| 224 | + return resp, err |
| 225 | + } |
| 226 | + } |
| 227 | + |
| 228 | + return resp, nil |
181 | 229 | }
|
0 commit comments