-
Notifications
You must be signed in to change notification settings - Fork 0
/
authorizations.go
81 lines (65 loc) · 1.5 KB
/
authorizations.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
)
type AuthorizationRequest struct {
Scopes []string `json:"scopes"`
Note string `json:"note"`
NoteUrl string `json:"note_url"`
}
type AuthorizationResponse struct {
Token string
}
func Authorize(username, password string) (string, error) {
payload := AuthorizationRequest{
[]string{"gist"},
fmt.Sprintf("go-gist (%d)", time.Now().Format(time.RFC822)),
"https://github.com/khrt/go-gist",
}
buf := bytes.NewBuffer(nil)
e := json.NewEncoder(buf)
if err := e.Encode(payload); err != nil {
return "", err
}
req, err := http.NewRequest("POST", GitHubAPIURL+"/authorizations", buf)
if err != nil {
return "", err
}
req.Header.Add("Content-type", "application/json")
req.SetBasicAuth(username, password)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
if resp.StatusCode == 401 && resp.Header.Get("X-GitHub-OTP") != "" {
fmt.Print("2-factor auth code: ")
var code string
fmt.Scanf("%s", &code)
req.Header.Add("X-GitHub-OTP", code)
resp, err = client.Do(req)
if err != nil {
return "", err
}
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != 201 {
return "", GistParseError(body)
}
var auth AuthorizationResponse
d := json.NewDecoder(strings.NewReader(string(body)))
if err := d.Decode(&auth); err != nil {
return "", err
}
return auth.Token, nil
}