-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
96 lines (74 loc) · 1.88 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
package place
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
)
const loginBaseURL = "https://www.reddit.com/api/login/"
func Login(username, password string) (*Client, error) {
jar, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
transport := &uaTransport{}
client := &http.Client{
Transport: transport,
Jar: jar,
}
res, err := client.PostForm(loginBaseURL+username,
url.Values{
"op": {"login"},
"user": {username},
"passwd": {password},
"api_type": {"json"},
})
if res.StatusCode != http.StatusOK {
return nil, err
}
defer res.Body.Close()
var reply redditJSON
if err := json.NewDecoder(res.Body).Decode(&reply); err != nil {
return nil, err
}
if len(reply.JSON.Errors) != 0 {
return nil, errors.New(fmt.Sprintf("error: %s", reply.JSON.Errors))
}
var dataJSON struct {
ModHash string `json:"modhash"`
}
if err := json.Unmarshal(reply.JSON.Data, &dataJSON); err != nil {
return nil, err
}
transport.modHash = dataJSON.ModHash
log.Println(dataJSON.ModHash)
log.Printf("[DEBUG] %s\n", reply)
return &Client{client}, nil
}
type redditJSON struct {
JSON struct {
Errors []json.RawMessage `json:"errors"`
Data json.RawMessage `json:"data"`
} `json:"json"`
}
func main() {
}
type uaTransport struct {
modHash string
}
func (t *uaTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("User-Agent", "go:vallon.me/place:v0.0.1 (by /u/neilvallon)")
if t.modHash != "" {
req.Header.Set("x-modhash", t.modHash)
}
resp, err := http.DefaultTransport.RoundTrip(req)
if err == nil {
log.Println("[INFO] X-Ratelimit-Used", resp.Header["X-Ratelimit-Used"])
log.Println("[INFO] X-Ratelimit-Remaining", resp.Header["X-Ratelimit-Remaining"])
log.Println("[INFO] X-Ratelimit-Reset", resp.Header["X-Ratelimit-Reset"])
}
return resp, err
}