-
Notifications
You must be signed in to change notification settings - Fork 23
/
webapi.go
102 lines (82 loc) · 2.1 KB
/
webapi.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
package steam
import (
"errors"
"io/ioutil"
"net/http"
"net/url"
"regexp"
)
const (
apiKeyURL = "https://steamcommunity.com/dev/apikey"
apiKeyRegisterURL = "https://steamcommunity.com/dev/registerkey"
apiKeyRevokeURL = "https://steamcommunity.com/dev/revokekey"
accessDeniedPattern = "<h2>Access Denied</h2>"
)
var (
keyRegExp = regexp.MustCompile("<p>Key: ([0-9A-F]+)</p>")
ErrCannotRegisterKey = errors.New("unable to register API key")
ErrCannotRevokeKey = errors.New("unable to revoke API key")
ErrAccessDenied = errors.New("access is denied")
ErrKeyNotFound = errors.New("key not found")
)
func (session *Session) parseKey(resp *http.Response) (string, error) {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if m, err := regexp.Match(accessDeniedPattern, body); err != nil {
return "", err
} else if m {
return "", ErrAccessDenied
}
submatch := keyRegExp.FindStringSubmatch(string(body))
if len(submatch) != 2 {
return "", ErrKeyNotFound
}
session.apiKey = submatch[1]
return submatch[1], nil
}
func (session *Session) RegisterWebAPIKey(domain string) (string, error) {
resp, err := session.client.PostForm(apiKeyRegisterURL, url.Values{
"domain": {domain},
"agreeToTerms": {"agreed"},
"sessionid": {session.sessionID},
"Submit": {"Register"},
})
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", ErrCannotRegisterKey
}
return session.parseKey(resp)
}
func (session *Session) GetWebAPIKey() (string, error) {
resp, err := session.client.Get(apiKeyURL)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return "", err
}
return session.parseKey(resp)
}
func (session *Session) RevokeWebAPIKey() error {
resp, err := session.client.PostForm(apiKeyRevokeURL, url.Values{
"Revoke": {"Revoke My Steam Web API Key"},
"sessionid": {session.sessionID},
})
if resp != nil {
resp.Body.Close()
}
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return ErrCannotRevokeKey
}
return nil
}