Skip to content

Commit

Permalink
xanzy#1210 move custom token into context
Browse files Browse the repository at this point in the history
  • Loading branch information
Алексей Волегов authored and pdecat committed Jan 23, 2022
1 parent 9816322 commit d230ec3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 18 deletions.
25 changes: 25 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package gitlab

import "context"

type key uint8

const optKey key = iota

func WithToken(ctx context.Context, token string) context.Context {
return context.WithValue(ctx, optKey, token)
}

func TokenFromContext(ctx context.Context) *string {
val := ctx.Value(optKey)
if val == nil {
return nil
}

opt, ok := val.(string)
if !ok {
return nil
}

return &opt
}
35 changes: 17 additions & 18 deletions gitlab.go
Original file line number Diff line number Diff line change
Expand Up @@ -644,20 +644,30 @@ func (c *Client) Do(req *retryablehttp.Request, v interface{}) (*Response, error
// silently as the limiter will be disabled in case of an error.
c.configureLimiterOnce.Do(func() { c.configureLimiter(req.Context()) })

ctx := req.Context()

// Wait will block until the limiter can obtain a new token.
err := c.limiter.Wait(req.Context())
err := c.limiter.Wait(ctx)
if err != nil {
return nil, err
}

var token string
c.tokenLock.RLock()
token = c.token
c.tokenLock.RUnlock()

authToken := TokenFromContext(ctx)
if authToken != nil {
token = *authToken
}

// Set the correct authentication header. If using basic auth, then check
// if we already have a token and if not first authenticate and get one.
var basicAuthToken string
switch c.authType {
case basicAuth:
c.tokenLock.RLock()
basicAuthToken = c.token
c.tokenLock.RUnlock()
basicAuthToken = token
if basicAuthToken == "" {
// If we don't have a token yet, we first need to request one.
basicAuthToken, err = c.requestOAuthToken(req.Context(), basicAuthToken)
Expand All @@ -667,11 +677,11 @@ func (c *Client) Do(req *retryablehttp.Request, v interface{}) (*Response, error
}
req.Header.Set("Authorization", "Bearer "+basicAuthToken)
case jobToken:
req.Header.Set("JOB-TOKEN", c.token)
req.Header.Set("JOB-TOKEN", token)
case oAuthToken:
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("Authorization", "Bearer "+token)
case privateToken:
req.Header.Set("PRIVATE-TOKEN", c.token)
req.Header.Set("PRIVATE-TOKEN", token)
}

resp, err := c.client.Do(req)
Expand Down Expand Up @@ -834,14 +844,3 @@ func parseError(raw interface{}) string {
return fmt.Sprintf("failed to parse unexpected error type: %T", raw)
}
}

// WithToken сhanges the token, but does not change the authorization method.
// For change authorization method create new Client.
func (c *Client) WithToken(token string) *Client {
c.tokenLock.Lock()
defer c.tokenLock.Unlock()

c.token = token

return c
}

0 comments on commit d230ec3

Please sign in to comment.