forked from guitmz/n26
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
109 lines (93 loc) · 2.5 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 n26
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
func createRequest(path string, body io.Reader) (*http.Request, error) {
u, _ := url.ParseRequestURI(apiURL)
u.Path = path
urlStr := fmt.Sprintf("%v", u)
req, err := http.NewRequest("POST", urlStr, body)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Basic YW5kcm9pZDpzZWNyZXQ=")
return req, nil
}
func (t *Token) GetMFAToken(username, password string) error {
data := url.Values{}
data.Set("grant_type", "password")
data.Set("username", username)
data.Set("password", password)
path := "/oauth/token"
req, err := createRequest(path, strings.NewReader(data.Encode()))
check(err)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res, err := http.DefaultClient.Do(req)
check(err)
if res.StatusCode != 403 {
return errors.New("Unexpected response from authentication request")
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
check(err)
err = json.Unmarshal(body, t)
check(err)
return nil
}
func (t *Token) requestMfaApproval() error {
data, err := json.Marshal(map[string]string{
"challengeType": "oob",
"mfaToken": t.MfaToken,
})
check(err)
path := "/api/mfa/challenge"
req, err := createRequest(path, bytes.NewBuffer(data))
check(err)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36")
res, err := http.DefaultClient.Do(req)
check(err)
if res.StatusCode != 201 {
return errors.New("Failed to request MFA approval")
}
// retries 12 times every 5 seconds (60 seconds total wait time)
// until the login is approved in a authorized device (like the users phone)
for i := 0; i <= 12; i++ {
status := t.CompleteMfaApproval()
if status == 400 {
time.Sleep(5 * time.Second)
} else {
break
}
}
return nil
}
func (t *Token) CompleteMfaApproval() int {
data := url.Values{}
data.Set("grant_type", "mfa_oob")
data.Set("mfaToken", t.MfaToken)
path := "/oauth/token"
req, err := createRequest(path, strings.NewReader(data.Encode()))
check(err)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res, err := http.DefaultClient.Do(req)
check(err)
if res.StatusCode == 400 {
return res.StatusCode
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
check(err)
err = json.Unmarshal(body, t)
check(err)
return res.StatusCode
}