AddAuthTokenHeader adds an authentication token header for the host specified by the request.
(rt http.RoundTripper, cfg config)
| 152 | |
| 153 | // AddAuthTokenHeader adds an authentication token header for the host specified by the request. |
| 154 | func AddAuthTokenHeader(rt http.RoundTripper, cfg config) http.RoundTripper { |
| 155 | return &funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) { |
| 156 | // If the header is already set in the request, don't overwrite it. |
| 157 | if req.Header.Get(authorization) != "" { |
| 158 | return rt.RoundTrip(req) |
| 159 | } |
| 160 | |
| 161 | var redirectHostnameChange bool |
| 162 | if req.Response != nil && req.Response.Request != nil { |
| 163 | redirectHostnameChange = getHostname(req) != getHostname(req.Response.Request) |
| 164 | } |
| 165 | |
| 166 | // Only set header if an initial request or redirect request to the same host as the initial request. |
| 167 | // If the host has changed during a redirect do not add the authentication token header. |
| 168 | if redirectHostnameChange { |
| 169 | return rt.RoundTrip(req) |
| 170 | } |
| 171 | |
| 172 | hostnameInRequest := ghauth.NormalizeHostname(getHostname(req)) |
| 173 | token, _ := cfg.ActiveToken(hostnameInRequest) |
| 174 | if token == "" { |
| 175 | // The request may be aimed at a host's api_host, which gh is |
| 176 | // not logged in to and so has no token of its own. Fall back |
| 177 | // to the token of the host it stands in for. This only ever |
| 178 | // adds a token where there would have been none, so hosts we |
| 179 | // already authenticate keep resolving exactly as before. |
| 180 | if canonicalHost, ok := cfg.HostForAPIHost(hostnameInRequest); ok { |
| 181 | token, _ = cfg.ActiveToken(canonicalHost) |
| 182 | } |
| 183 | } |
| 184 | if token != "" { |
| 185 | req.Header.Set(authorization, fmt.Sprintf("token %s", token)) |
| 186 | } |
| 187 | |
| 188 | return rt.RoundTrip(req) |
| 189 | }} |
| 190 | } |
| 191 | |
| 192 | // ExtractHeader extracts a named header from any response received by this client and, |
| 193 | // if non-blank, saves it to dest. |