/
authService.go
83 lines (70 loc) · 1.84 KB
/
authService.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
package rest
import (
"bytes"
"crypto/md5"
"crypto/rsa"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/golang/glog"
"go.kicksware.com/api/service-common/config"
"go.kicksware.com/api/service-common/core"
"go.kicksware.com/api/service-common/util"
)
type authService struct {
publicKey *rsa.PublicKey
authEndpoint string
accessChecksum []byte
}
func NewAuthService(authConfig config.AuthConfig) core.AuthService {
return &authService{
util.GetPublicKey(authConfig.PublicKeyPath),
authConfig.AuthEndpoint,
getAccessChecksum(authConfig.AccessKey),
}
}
func (s *authService) PublicKey() *rsa.PublicKey {
return s.publicKey
}
func (s *authService) Authenticate() (string, error) {
resp, err := http.Get(s.guestEndpoint()); if err != nil {
return "", errors.New("error has occurred in authenticating service: %q\", err")
}
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body); if err != nil {
return "", err
}
token := make(map[string]interface{})
err = json.Unmarshal(bytes, &token); if err != nil {
return "", err
}
return token["Token"].(string), nil
}
func (s *authService) AccessKey() []byte {
return s.accessChecksum
}
func (s *authService) VerifyAccessKey(hash []byte) bool {
ok := bytes.Equal(s.accessChecksum, hash)
return ok
}
func getAccessChecksum(accessKey string) []byte {
input := strings.NewReader(accessKey)
hash := md5.New()
if _, err := io.Copy(hash, input); err != nil {
glog.Fatalln(err)
}
return hash.Sum(nil)
}
func (s *authService) guestEndpoint() string {
req, err := http.NewRequest("GET", s.authEndpoint, nil); if err != nil {
glog.Fatalf("error has occurred in core.AuthService.guestEndpoint(): %q", err)
return ""
}
query := req.URL.Query()
query.Add("access", string(s.accessChecksum))
req.URL.RawQuery = query.Encode()
return req.URL.String()
}