-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApplication.go
118 lines (95 loc) · 2.58 KB
/
Application.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
110
111
112
113
114
115
116
117
118
// Package metrafin provides structured means for accessing the Metrafin Public API and authenticating Metrafin users.
package metrafin
import (
"encoding/json"
"errors"
)
// An Application for the Metrafin API
type Application struct {
PrivateToken string
}
type createAccessTokenReq struct {
AuthorizationCode string `json:"authorizationCode"`
}
type createAccessTokenRes struct {
Error string `json:"error"`
AccessToken string `json:"accessToken"`
}
type resolveUserReq struct {
ResolveBy string `json:"resolveBy"`
Value string `json:"value"`
}
// ResolveUserRes represents responses from a documented endpoint: https://github.com/metrafin/documentation#post-v1resolveuser
type ResolveUserRes struct {
Error string `json:"error"`
UserID string `json:"userId"`
Username string `json:"username"`
}
// Auth creates a new Authorization by "authorizationCode" or "accessToken".
func (a *Application) Auth(by string, value string) (auth *Authorization, err error) {
if by == "authorizationCode" {
data := createAccessTokenReq{
AuthorizationCode: value,
}
serialized, err := json.Marshal(data)
if err != nil {
return nil, err
}
parsed := &createAccessTokenRes{}
err = doRequest(request{
URL: "https://api.metrafin.com/v1/createAccessToken",
Method: "POST",
Data: &serialized,
Headers: &map[string]string{
"Authorization": (*a).PrivateToken,
},
}, nil, parsed)
if err != nil {
return nil, err
}
if parsed.Error != "" {
return nil, errors.New(parsed.Error)
}
return &Authorization{
application: a,
AccessToken: parsed.AccessToken,
}, nil
} else if by == "accessToken" {
return &Authorization{
application: a,
AccessToken: value,
}, nil
} else {
panic("Unknown authorization method \"" + by + "\"")
}
}
// ResolveUser resolves a user by either "username" or "userId".
func (a *Application) ResolveUser(resolveBy string, value string) (result *ResolveUserRes, err error) {
data := resolveUserReq{
ResolveBy: resolveBy,
Value: value,
}
if data.ResolveBy != "username" && data.ResolveBy != "userId" {
panic("Cannot resolve by '" + data.ResolveBy + "'")
}
serialized, err := json.Marshal(data)
if err != nil {
return nil, err
}
parsed := &ResolveUserRes{}
err = doRequest(request{
URL: "https://api.metrafin.com/v1/resolveUser",
Method: "POST",
Data: &serialized,
Headers: &map[string]string{
"Authorization": (*a).PrivateToken,
},
}, nil, parsed)
if err != nil {
return nil, err
}
if parsed.Error != "" {
return nil, errors.New(parsed.Error)
}
return parsed, nil
}