-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
109 lines (93 loc) · 2.51 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package adp
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
type ADPAuthenticationSystem interface {
Authenticate() error
NewHttpClient() (*http.Client, error)
SetRequestAuthorizationHeader(*http.Request)
}
type ADPOAuthAuthentication struct {
KeyFilePath string
CertificateFilePath string
Credential string
Token *ADPOAuthOutput
}
type ADPOAuthOutput struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
}
func NewOAuthAuthenticationSystem(certificateFilePath, keyFilePath, credential string) (*ADPOAuthAuthentication, error) {
err := []error{}
if !fileExists(keyFilePath) {
err = append(err, fmt.Errorf("key file path does not exists: %s", keyFilePath))
}
if !fileExists(certificateFilePath) {
err = append(err, fmt.Errorf("certficatefile path does not exsits: %s", certificateFilePath))
}
if len(err) > 0 {
return nil, errors.Join(err...)
}
return &ADPOAuthAuthentication{
KeyFilePath: keyFilePath,
CertificateFilePath: certificateFilePath,
Credential: credential,
}, nil
}
func (a *ADPOAuthAuthentication) Authenticate() error {
client, err := a.NewHttpClient()
if err != nil {
return err
}
request, err := http.NewRequest(
http.MethodPost,
"https://accounts.adp.com/auth/oauth/v2/token?grant_type=client_credentials",
nil,
)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", fmt.Sprintf("Basic %s", a.Credential))
resp, err := client.Do(request)
if err != nil {
return err
}
if !isValidResponseStatusCode(resp) {
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("unable to retrieve access token: %s", body)
}
token := ADPOAuthOutput{}
if err = json.NewDecoder(resp.Body).Decode(&token); err != nil {
return err
}
a.Token = &token
return nil
}
func (a *ADPOAuthAuthentication) SetRequestAuthorizationHeader(request *http.Request) {
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", a.Token.AccessToken))
}
func (a *ADPOAuthAuthentication) NewHttpClient() (*http.Client, error) {
certificates, err := tls.LoadX509KeyPair(a.CertificateFilePath, a.KeyFilePath)
if err != nil {
return nil, err
}
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{certificates},
},
},
}
return client, nil
}