-
Notifications
You must be signed in to change notification settings - Fork 4
/
auth.go
72 lines (57 loc) · 1.86 KB
/
auth.go
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// SPDX-FileCopyrightText: 2020 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
// Package acquire is used for getting Auths to pass in http requests.
package acquire
import (
"errors"
"fmt"
"net/http"
)
// ErrEmptyCredentials is returned whenever an Acquirer is attempted to
// be built with empty credentials.
// Use DefaultAcquirer for such no-op use case.
var ErrEmptyCredentials = errors.New("Empty credentials are not valid")
// Acquirer gets an Authorization value that can be added to an http request.
// The format of the string returned should be the key, a space, and then the
// auth string: '[AuthType] [AuthValue]'
type Acquirer interface {
Acquire() (string, error)
}
// DefaultAcquirer is a no-op Acquirer.
type DefaultAcquirer struct{}
// Acquire returns the zero values of the return types.
func (d *DefaultAcquirer) Acquire() (string, error) {
return "", nil
}
// AddAuth adds an auth value to the Authorization header of an http request.
func AddAuth(r *http.Request, acquirer Acquirer) error {
if r == nil {
return errors.New("can't add authorization to nil request")
}
if acquirer == nil {
return errors.New("acquirer is undefined")
}
auth, err := acquirer.Acquire()
if err != nil {
return fmt.Errorf("failed to acquire auth for request: %w", err)
}
if auth != "" {
r.Header.Set("Authorization", auth)
}
return nil
}
// FixedValueAcquirer implements Acquirer with a constant authorization value.
type FixedValueAcquirer struct {
authValue string
}
func (f *FixedValueAcquirer) Acquire() (string, error) {
return f.authValue, nil
}
// NewFixedAuthAcquirer returns a FixedValueAcquirer with the given authValue.
func NewFixedAuthAcquirer(authValue string) (*FixedValueAcquirer, error) {
if authValue != "" {
return &FixedValueAcquirer{
authValue: authValue}, nil
}
return nil, ErrEmptyCredentials
}