-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
206 lines (175 loc) · 5.42 KB
/
client.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package sberbank_id
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
const (
rqUIDcharset = "abcdefABCDEF0123456789"
rqUIDlen = 32
// refer tot https://developer.sberbank.ru/doc/v1/sberbank-id/tokensurl
//ApiUrlAuthDev = "https://dev.api.sberbank.ru/ru/prod/tokens/v2/oidc"
//ApiUrlAuthProd = "https://sec.api.sberbank.ru/ru/prod/tokens/v2/oidc"
AuthorizeAccessTokenUrl = "http://45.12.238.224:8181/CSAFront/oidc/sberbank_id/authorize.do"
TokenAuthorizeUrl = "http://45.12.238.224:8181/ru/prod/tokens/v2/oidc"
PersonalDataUrl = "http://45.12.238.224:8181/ru/prod/sberbankid/v2.1/userInfo"
)
// SberbankIdClient represents the main struct of a client for Sbebank ID API
type SberbankIdClient struct {
HttpCient *http.Client
creds *SberCredentials
config *Config
}
// SberCredentials is a struct to store user credentials for Sberbank ID API
type SberCredentials struct {
ClientId string
ClientSecret string
}
// TokenResponse represents OAuth token response
type TokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in,omitempty"`
Scope string `json:"scope"`
IdToken string `json:"id_token"`
}
// PersonData represents Personal Data response. JSON formatted
type PersonData map[string]interface{}
// Config is a structure to keep instance parameters for httpClient requests
type Config struct {
Scope string
RedirectUrl string
state string
nonce string
DebugMode bool
}
func New(clientId, clientSecret string, config *Config) *SberbankIdClient {
return &SberbankIdClient{
HttpCient: &http.Client{
// prevents redirects follow
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
},
config: &Config{
Scope: config.Scope,
RedirectUrl: config.RedirectUrl,
state: generateStateHash(),
nonce: generateNonce(),
DebugMode: config.DebugMode,
},
creds: &SberCredentials{
ClientId: clientId,
ClientSecret: clientSecret,
},
}
}
func (c *SberbankIdClient) GetToken(authcode string) (*TokenResponse, error) {
rm := map[string]string{
"grant_type": "authorization_code",
"scope": c.config.Scope,
"redirect_uri": c.config.RedirectUrl,
"code": authcode,
"client_id": c.creds.ClientId,
"client_secret": c.creds.ClientSecret,
}
req, _ := http.NewRequest("POST", TokenAuthorizeUrl, bytes.NewBufferString(buildUrl(rm)))
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("X-IBM-Client-ID", c.creds.ClientId)
req.Header.Add("X-IBM-Client-Secret", c.creds.ClientSecret)
req.Header.Add("RqUID", generateRandomRqUID(rqUIDlen))
resp, err := c.HttpCient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if c.config.DebugMode {
fmt.Println("--------------------")
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
fmt.Println("response Body:", string(body))
}
tr := &TokenResponse{}
if err := json.Unmarshal(body, &tr); err != nil {
return nil, err
}
return tr, nil
}
func (c *SberbankIdClient) AuthRequest() (string, error) {
var userCredMap = map[string]string{
"login": "Q0002",
"password": "Password2",
}
var queryMap = map[string]string{
"response_type": "code",
"client_type": "PRIVATE",
"scope": c.config.Scope,
"client_id": c.creds.ClientId,
"state": c.config.state,
"nonce": c.config.nonce,
"redirect_uri": c.config.RedirectUrl,
}
jsonCreds, err := json.Marshal(userCredMap)
if err != nil {
return "", err
}
req, _ := http.NewRequest("POST", AuthorizeAccessTokenUrl+"?"+buildUrl(queryMap), bytes.NewBuffer(jsonCreds))
req.Header.Set("Content-Type", "application/json")
resp, err := c.HttpCient.Do(req)
defer resp.Body.Close()
if err != nil {
return "", err
}
if c.config.DebugMode {
fmt.Println(string(jsonCreds))
fmt.Println("---")
fmt.Println("req", req)
fmt.Println("--------------------")
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
// We need to catch code 200
if resp.StatusCode == http.StatusOK {
loc := resp.Header.Get("Location")
if loc != "" {
authCode, _ := parseUrl(resp.Header.Get("Location"), "code")
return authCode, nil
}
}
return "", errors.New("auth request failed")
}
func (c *SberbankIdClient) GetPersonalData(token *TokenResponse) (*PersonData, error) {
req, err := http.NewRequest("GET", PersonalDataUrl, nil)
if err != nil {
return nil, err
}
req.Header.Add("x-introspect-rquid", generateRandomRqUID(32))
req.Header.Add("X-IBM-Client-ID", c.creds.ClientId)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %v", token.AccessToken))
req.Header.Add("Accept", "application/json")
req.Header.Add("RqUID", generateRandomRqUID(rqUIDlen))
res, err := c.HttpCient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if c.config.DebugMode {
fmt.Println(string(body))
}
if err != nil {
return nil, err
}
var pd PersonData
if err := json.Unmarshal(body, &pd); err != nil {
return nil, errors.New("failed to fetch personal data")
}
return &pd, nil
}