forked from aiven/aiven-go-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
75 lines (62 loc) · 1.56 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
package aiven
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
)
type (
// Token represents a user token.
Token struct {
Token string `json:"token"`
State string `json:"state"`
}
authRequest struct {
Email string `json:"email"`
OTP string `json:"otp"`
Password string `json:"password"`
}
authResponse struct {
Errors []Error `json:"errors"`
Message string `json:"message"`
State string `json:"state"`
Token string `json:"token"`
}
)
// UserToken creates an authentication token without Multi Factor auth.
func UserToken(email, password string, client *http.Client) (*Token, error) {
return MFAUserToken(email, "", password, client)
}
// MFAUserToken retrieves a User Auth Token for a given email/password pair.
func MFAUserToken(email, otp, password string, client *http.Client) (*Token, error) {
if client == nil {
client = &http.Client{}
}
bts, err := json.Marshal(authRequest{email, otp, password})
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", endpoint("/userauth"), bytes.NewBuffer(bts))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
rsp, err := client.Do(req)
if err != nil {
return nil, err
}
defer rsp.Body.Close()
bts, err = ioutil.ReadAll(rsp.Body)
if err != nil {
return nil, err
}
var response *authResponse
if err := json.Unmarshal(bts, &response); err != nil {
return nil, err
}
if len(response.Errors) != 0 {
return nil, errors.New(response.Message)
}
return &Token{response.Token, response.State}, nil
}