-
Notifications
You must be signed in to change notification settings - Fork 83
/
authenticator.go
71 lines (55 loc) · 2.17 KB
/
authenticator.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
package authentication
import (
"context"
"github.com/kyma-incubator/compass/components/director/pkg/log"
"github.com/pkg/errors"
)
//go:generate mockery --name=Authenticator --disable-version-string
type Authenticator interface {
AuthenticateToken(context context.Context) (string, error)
Authenticate(context context.Context) (string, error)
AuthenticateCertificate(context context.Context) (string, string, error)
}
func NewAuthenticator() Authenticator {
return &authenticator{}
}
type authenticator struct {
}
func (a *authenticator) Authenticate(ctx context.Context) (string, error) {
clientId, tokenAuthErr := a.AuthenticateToken(ctx)
if tokenAuthErr == nil {
log.C(ctx).Debugf("Client with id %s successfully authenticated with token", clientId)
return clientId, nil
}
clientId, _, certAuthErr := a.AuthenticateCertificate(ctx)
if certAuthErr != nil {
return "", errors.Errorf("Failed to authenticate request. Token authentication error: %s. Certificate authentication error: %s",
tokenAuthErr.Error(), certAuthErr.Error())
}
log.C(ctx).Debugf("Client with id %s successfully authenticated with certificate", clientId)
return clientId, nil
}
func (a *authenticator) AuthenticateToken(context context.Context) (string, error) {
clientId, err := GetStringFromContext(context, ClientIdFromTokenKey)
if err != nil {
return "", errors.Wrap(err, "Failed to authenticate request, token not provided")
}
if clientId == "" {
return "", errors.New("Failed to authenticate with one time token.")
}
return clientId, nil
}
func (a *authenticator) AuthenticateCertificate(context context.Context) (string, string, error) {
clientId, err := GetStringFromContext(context, ClientIdFromCertificateKey)
if err != nil {
return "", "", errors.Wrap(err, "Failed to authenticate with Certificate. Invalid subject.")
}
if clientId == "" {
return "", "", errors.New("Failed to authenticate with Certificate. Invalid subject.")
}
certificateHash, err := GetStringFromContext(context, ClientCertificateHashKey)
if err != nil {
return "", "", errors.Wrap(err, "Failed to authenticate with Certificate. Invalid certificate hash.")
}
return clientId, certificateHash, nil
}