-
Notifications
You must be signed in to change notification settings - Fork 4
/
auth.go
200 lines (180 loc) · 4.84 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package disguard // import "go.zeta.pm/disguard"
import (
"encoding/json"
"mime"
"net/http"
"path/filepath"
"strings"
"github.com/GeertJohan/go.rice"
"github.com/gorilla/securecookie"
"github.com/pressly/chi"
)
// Session contains everything OAuth
type Session struct {
config *Config
httpClient *http.Client
cookieHandler *securecookie.SecureCookie
box *rice.Box
}
// HandleLogin ...
func (o *Session) HandleLogin(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, o.config.OAuth.GetAuthorizationURL(), http.StatusFound)
}
// HandleLogout ...
func (o *Session) HandleLogout(w http.ResponseWriter, r *http.Request) {
o.clearSession(w)
http.Redirect(w, r, "/", http.StatusFound)
}
// ObtainToken ...
func (o *Session) ObtainToken(code string) (*TokenResponse, error) {
req, err := http.NewRequest("POST", o.config.OAuth.GetTokenURL(code), nil)
if err != nil {
return nil, err
}
resp, err := o.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, http.ErrAbortHandler
}
var tokenResponse TokenResponse
err = json.NewDecoder(resp.Body).Decode(&tokenResponse)
if err != nil {
return nil, err
}
if !strings.Contains(tokenResponse.Scope, "identify") {
return nil, http.ErrAbortHandler
}
if !strings.Contains(tokenResponse.Scope, "guilds") {
return nil, http.ErrAbortHandler
}
if tokenResponse.TokenType != "Bearer" {
return nil, http.ErrAbortHandler
}
return &tokenResponse, nil
}
// GetUser ...
func (o *Session) GetUser(tokenResponse *TokenResponse) (*User, error) {
req, err := http.NewRequest("GET", "https://discordapp.com/api/users/@me", nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+tokenResponse.AccessToken)
resp, err := o.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, http.ErrAbortHandler
}
var userResponse User
err = json.NewDecoder(resp.Body).Decode(&userResponse)
if err != nil {
return nil, err
}
return &userResponse, nil
}
// GetGuilds ...
func (o *Session) GetGuilds(tokenResponse *TokenResponse) ([]Guild, error) {
req, err := http.NewRequest("GET", "https://discordapp.com/api/users/@me/guilds", nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+tokenResponse.AccessToken)
resp, err := o.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var guildsResponse []Guild
err = json.NewDecoder(resp.Body).Decode(&guildsResponse)
if err != nil {
return nil, http.ErrAbortHandler
}
return guildsResponse, nil
}
func (o *Session) filterWhitelisted(guilds []Guild) []string {
var results []string
mainLabel:
for _, guild := range guilds {
for _, whitelistedID := range o.config.WhitelistedGuilds {
if guild.ID == whitelistedID {
results = append(results, whitelistedID)
}
if len(results) >= len(o.config.WhitelistedGuilds) {
// Found all the whitelisted guilds, no more need, breaking out.
break mainLabel
}
}
}
return results
}
func (o *Session) doCallback(code string) (*User, error) {
tokenResponse, err := o.ObtainToken(code)
if err != nil {
return nil, err
}
userResponse, err := o.GetUser(tokenResponse)
if err != nil {
return nil, err
}
guildsResponse, err := o.GetGuilds(tokenResponse)
if err != nil {
return nil, err
}
whitelisted := o.filterWhitelisted(guildsResponse)
if len(whitelisted) == 0 {
return nil, http.ErrAbortHandler
}
userResponse.Whitelisted = whitelisted
return userResponse, nil
}
// HandleCallback ...
func (o *Session) HandleCallback(w http.ResponseWriter, r *http.Request) {
code, ok := r.URL.Query()["code"]
if !ok {
w.WriteHeader(403)
w.Write(o.box.MustBytes("error403.html"))
return
}
userResponse, err := o.doCallback(code[0])
if err != nil {
w.WriteHeader(403)
w.Write(o.box.MustBytes("error403.html"))
return
}
err = o.setSession(w, *userResponse)
if err != nil {
http.Redirect(w, r, "/", http.StatusFound)
return
}
http.Redirect(w, r, "/", http.StatusFound)
}
// Route ...
func (o *Session) Route(r chi.Router) {
r.Get("/login", o.HandleLogin)
r.Get("/logout", o.HandleLogout)
r.Get("/callback", o.HandleCallback)
r.Mount("/static/", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
path := strings.SplitN(r.URL.Path, "/static/", 2)[1]
if b, err := o.box.Bytes(path); err == nil {
rw.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(path)))
rw.Write(b)
} else {
rw.WriteHeader(404)
}
}))
}
// NewSessionRouter returns handler for session stuff
func NewSessionRouter(c *Config) *Session {
sess := &Session{
config: c,
httpClient: &http.Client{},
cookieHandler: securecookie.New([]byte(c.Session.HashKey), []byte(c.Session.BlockKey)),
box: rice.MustFindBox("static"),
}
return sess
}