summaryrefslogtreecommitdiff
path: root/services/worker/internal/fetcher/authentication.go
blob: 9ee453919c4a52bacadf516734993bb4d5a87334 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package fetcher

import (
	"encoding/base64"
	"fmt"
	"net/http"
	"net/url"
	"strings"
)

type AuthenticationConfiguration struct {
	AuthenticationType  string
	AuthenticationValue string
}

func ApplyAuthentication(request *http.Request, authenticationConfig AuthenticationConfiguration) error {
	switch authenticationConfig.AuthenticationType {
	case "bearer":
		request.Header.Set("Authorization", "Bearer "+authenticationConfig.AuthenticationValue)
	case "basic":
		encodedCredentials := base64.StdEncoding.EncodeToString([]byte(authenticationConfig.AuthenticationValue))

		request.Header.Set("Authorization", "Basic "+encodedCredentials)
	case "query_param":
		parts := strings.SplitN(authenticationConfig.AuthenticationValue, "=", 2)

		if len(parts) != 2 {
			return fmt.Errorf("query_param credential must be in format 'param_name=value', got: %s", authenticationConfig.AuthenticationValue)
		}

		existingURL, parseError := url.Parse(request.URL.String())

		if parseError != nil {
			return fmt.Errorf("failed to parse request URL for query param authentication: %w", parseError)
		}

		queryParameters := existingURL.Query()

		queryParameters.Set(parts[0], parts[1])

		existingURL.RawQuery = queryParameters.Encode()
		request.URL = existingURL
	case "":
		return nil
	default:
		return fmt.Errorf("unsupported authentication type: %s", authenticationConfig.AuthenticationType)
	}

	return nil
}