forked from peterbe/autocompeter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
352 lines (310 loc) · 9.46 KB
/
server.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package main
import (
"fmt"
"github.com/codegangsta/negroni"
"github.com/fzzy/radix/extra/pool"
"github.com/fzzy/radix/redis"
"github.com/google/go-github/github"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"github.com/namsral/flag"
"github.com/unrolled/render"
"golang.org/x/oauth2"
githuboauth "golang.org/x/oauth2/github"
"math/rand"
"net/http"
"runtime"
"strings"
"time"
)
// func QueryScore(terms []string, title) float32 {
// return 1.0
// }
func errHndlr(err error) {
if err != nil {
fmt.Println("error:", err)
panic(err)
}
}
func isOnHTTPS(req *http.Request) bool {
if req.Header.Get("is-secure") == "true" {
return true
}
// default is to use the flag
// which is only really useful for local development
return usingHTTPS
}
type domainRow struct {
Key string
Domain string
}
func indexHandler(w http.ResponseWriter, req *http.Request) {
context := map[string]interface{}{
"staticPrefix": staticPrefix,
"isNotDebug": !debug,
"Username": "",
"domains": make([]string, 0),
}
cookie, err := req.Cookie("username")
if err == nil {
var username string
if err = sCookie.Decode("username", cookie.Value, &username); err == nil {
// Yay! You're signed in!
context["Username"] = username
c, err := redisPool.Get()
errHndlr(err)
defer redisPool.CarefullyPut(c, &err)
userdomainsKey := fmt.Sprintf("$userdomains$%v", cookie.Value)
replies, err := c.Cmd("SMEMBERS", userdomainsKey).List()
errHndlr(err)
domains := make([]domainRow, len(replies))
var domain string
for i, key := range replies {
reply := c.Cmd("HGET", "$domainkeys", key)
if reply.Type != redis.NilReply {
domain, err = reply.Str()
errHndlr(err)
domains[i] = domainRow{
Key: key,
Domain: domain,
}
}
}
context["domains"] = domains
}
}
// this assumes there's a `templates/index.tmpl` file
renderer.HTML(w, http.StatusOK, "index", context)
}
func logoutHandler(w http.ResponseWriter, req *http.Request) {
expire := time.Now().AddDate(0, 0, -1)
secureCookie := isOnHTTPS(req)
cookie := &http.Cookie{
Name: "username",
Value: "*deleted*",
Path: "/",
Expires: expire,
MaxAge: -1,
Secure: secureCookie,
HttpOnly: true,
}
http.SetCookie(w, cookie)
http.Redirect(w, req, "/#loggedout", http.StatusTemporaryRedirect)
}
func handleGitHubLogin(w http.ResponseWriter, req *http.Request) {
url := oauthConf.AuthCodeURL(oauthStateString, oauth2.AccessTypeOnline)
http.Redirect(w, req, url, http.StatusTemporaryRedirect)
}
func handleGitHubCallback(w http.ResponseWriter, req *http.Request) {
state := req.FormValue("state")
if state != oauthStateString {
fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
http.Redirect(w, req, "/", http.StatusTemporaryRedirect)
return
}
code := req.FormValue("code")
token, err := oauthConf.Exchange(oauth2.NoContext, code)
if err != nil {
fmt.Printf("oauthConf.Exchange() failed with '%s'\n", err)
http.Redirect(w, req, "/", http.StatusTemporaryRedirect)
return
}
oauthClient := oauthConf.Client(oauth2.NoContext, token)
client := github.NewClient(oauthClient)
// the second item here is the github.Rate config
user, _, err := client.Users.Get("")
if err != nil {
fmt.Printf("client.Users.Get() faled with '%s'\n", err)
http.Redirect(w, req, "/", http.StatusTemporaryRedirect)
return
}
fmt.Printf("Logged in as GitHub user: %s\n", *user.Login)
// fmt.Printf("Logged in as GitHub user: %s\n", *user)
encoded, err := sCookie.Encode("username", *user.Login)
errHndlr(err)
expire := time.Now().AddDate(0, 0, 1) // how long is this?
secureCookie := isOnHTTPS(req)
cookie := &http.Cookie{
Name: "username",
Value: encoded,
Path: "/",
Expires: expire,
MaxAge: 60 * 60 * 24 * 30, // 30 days
Secure: secureCookie,
HttpOnly: true,
}
http.SetCookie(w, cookie)
http.Redirect(w, req, "/#auth", http.StatusTemporaryRedirect)
}
var letters = []rune(
"abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ123456789",
)
func randString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func domainkeyNewHandler(w http.ResponseWriter, req *http.Request) {
domain := strings.Trim(req.FormValue("domain"), " ")
if domain != "" {
cookie, err := req.Cookie("username")
if err == nil {
var username string
if err = sCookie.Decode("username", cookie.Value, &username); err == nil {
c, err := redisPool.Get()
errHndlr(err)
defer redisPool.CarefullyPut(c, &err)
key := randString(24)
userdomainsKey := fmt.Sprintf("$userdomains$%v", cookie.Value)
err = c.Cmd("SADD", userdomainsKey, key).Err
errHndlr(err)
err = c.Cmd("HSET", "$domainkeys", key, domain).Err
errHndlr(err)
}
}
}
// http.Redirect(w, req, "/", http.StatusTemporaryRedirect)
http.Redirect(w, req, "/#auth", http.StatusFound)
}
func domainkeyDeleteHandler(w http.ResponseWriter, req *http.Request) {
key := strings.Trim(req.FormValue("key"), " ")
if key != "" {
cookie, err := req.Cookie("username")
if err == nil {
var username string
if err = sCookie.Decode("username", cookie.Value, &username); err == nil {
// Yay! You're signed in!
c, err := redisPool.Get()
errHndlr(err)
defer redisPool.CarefullyPut(c, &err)
userdomainsKey := fmt.Sprintf("$userdomains$%v", cookie.Value)
err = c.Cmd("SREM", userdomainsKey, key).Err
errHndlr(err)
err = c.Cmd("HDEL", "$domainkeys", key).Err
errHndlr(err)
} // else, we should yield some sort of 403 message maybe
}
}
http.Redirect(w, req, "/#auth", http.StatusFound)
}
var (
redisPool *pool.Pool
procs int
debug = true
renderer = render.New()
redisURL = "127.0.0.1:6379"
staticPrefix = ""
usingHTTPS = false
sCookie *securecookie.SecureCookie
)
var (
// You must register the app at https://github.com/settings/applications
// Set callback to http://127.0.0.1:7000/github_oauth_cb
// Set ClientId and ClientSecret to
oauthConf = &oauth2.Config{
ClientID: "",
ClientSecret: "",
Scopes: []string{"user:email"},
Endpoint: githuboauth.Endpoint,
}
// random string for oauth2 API calls to protect against CSRF
oauthStateString = randString(24)
)
func main() {
var (
port = 3001
redisDatabase = 0
redisPoolSize = 10
clientID = ""
clientSecret = ""
hashKey = "randomishstringthatsi32charslong"
blockKey = "randomishstringthatsi32charslong"
)
flag.IntVar(&port, "port", port, "Port to start the server on")
flag.IntVar(&procs, "procs", 1, "Number of CPU processors (0 to use max)")
flag.BoolVar(&debug, "debug", false, "Debug mode")
flag.StringVar(
&redisURL, "redisURL", redisURL,
"Redis URL to tcp connect to")
flag.StringVar(
&staticPrefix, "staticPrefix", staticPrefix,
"Prefix in front of static assets in HTML")
flag.IntVar(&redisDatabase, "redisDatabase", redisDatabase,
"Redis database number to connect to")
flag.StringVar(
&clientID, "clientID", clientID,
"OAuth Client ID")
flag.StringVar(
&clientSecret, "clientSecret", clientSecret,
"OAuth Client Secret")
flag.BoolVar(&usingHTTPS, "usingHTTPS", usingHTTPS,
"Whether requests are made under HTTPS")
flag.StringVar(
&hashKey, "hashKey", hashKey,
"HMAC hash key to use for encoding cookies")
flag.StringVar(
&blockKey, "blockKey", blockKey,
"Block key to encrypt cookie values")
flag.Parse()
oauthConf.ClientID = clientID
oauthConf.ClientSecret = clientSecret
sCookie = securecookie.New([]byte(hashKey), []byte(blockKey))
fmt.Println("REDIS DATABASE:", redisDatabase)
fmt.Println("DEBUG MODE:", debug)
fmt.Println("STATIC PREFIX:", staticPrefix)
if !debug {
redisPoolSize = 100
}
// Figuring out how many processors to use.
maxProcs := runtime.NumCPU()
if procs == 0 {
procs = maxProcs
} else if procs < 0 {
panic("PROCS < 0")
} else if procs > maxProcs {
panic(fmt.Sprintf("PROCS > max (%v)", maxProcs))
}
fmt.Println("PROCS:", procs)
runtime.GOMAXPROCS(procs)
renderer = render.New(render.Options{
IndentJSON: debug,
IsDevelopment: debug,
})
df := func(network, addr string) (*redis.Client, error) {
client, err := redis.Dial(network, addr)
if err != nil {
return nil, err
}
err = client.Cmd("SELECT", redisDatabase).Err
if err != nil {
return nil, err
}
// if err = client.Cmd("AUTH", "SUPERSECRET").Err; err != nil {
// client.Close()
// return nil, err
// }
return client, nil
}
var err error
redisPool, err = pool.NewCustomPool("tcp", redisURL, redisPoolSize, df)
errHndlr(err)
mux := mux.NewRouter()
mux.HandleFunc("/", indexHandler).Methods("GET", "HEAD")
mux.HandleFunc("/v1/ping", pingHandler).Methods("GET", "HEAD")
mux.HandleFunc("/v1", fetchHandler).Methods("GET", "HEAD")
mux.HandleFunc("/v1", updateHandler).Methods("POST", "PUT")
mux.HandleFunc("/v1", deleteHandler).Methods("DELETE")
mux.HandleFunc("/v1/stats", privateStatsHandler).Methods("GET")
mux.HandleFunc("/v1/flush", flushHandler).Methods("DELETE")
mux.HandleFunc("/v1/bulk", bulkHandler).Methods("POST", "PUT")
mux.HandleFunc("/login", handleGitHubLogin).Methods("GET")
mux.HandleFunc("/logout", logoutHandler).Methods("GET", "POST")
mux.HandleFunc("/github_oauth_cb", handleGitHubCallback).Methods("GET")
mux.HandleFunc("/domainkeys/new", domainkeyNewHandler).Methods("POST")
mux.HandleFunc("/domainkeys/delete", domainkeyDeleteHandler).Methods("POST")
n := negroni.Classic()
n.UseHandler(mux)
n.Run(fmt.Sprintf(":%d", port))
}