-
Notifications
You must be signed in to change notification settings - Fork 2
/
webserver.go
348 lines (323 loc) · 9.28 KB
/
webserver.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
package gidbig
import (
"bufio"
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"html/template"
"log/slog"
"net"
"net/http"
"os"
"strconv"
"github.com/bwmarrin/discordgo"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"github.com/simplesurance/go-ip-anonymizer/ipanonymizer"
"github.com/toksikk/gidbig/pkg/cfg"
"golang.org/x/oauth2"
)
const (
header string = "web/templates/header.html"
footer string = "web/templates/footer.html"
templateDir string = "web/templates/"
)
var (
discordOauthConfig = &oauth2.Config{
RedirectURL: "",
ClientID: "",
ClientSecret: "",
Scopes: []string{"identify", "guilds"},
Endpoint: *endp,
}
// Some random string, random for each request
oauthStateString string
endp = &oauth2.Endpoint{
AuthURL: "https://discordapp.com/api/oauth2/authorize",
TokenURL: "https://discordapp.com/api/oauth2/token",
}
tmpls = map[string]*template.Template{}
// TODO change secret
store *sessions.CookieStore
ipAnonymizer = ipanonymizer.NewWithMask(
net.CIDRMask(16, 32),
net.CIDRMask(64, 128),
)
)
// startWebServer
func startWebServer(config *cfg.Config) {
tmpls["home.html"] = template.Must(template.ParseFiles(templateDir+"home.html", header, footer))
tmpls["internal.html"] = template.Must(template.ParseFiles(templateDir+"internal.html", header, footer))
tmpls["item.html"] = template.Must(template.ParseFiles(templateDir + "item.html"))
tmpls["itemrowstart.html"] = template.Must(template.ParseFiles(templateDir + "itemrowstart.html"))
tmpls["itemrowend.html"] = template.Must(template.ParseFiles(templateDir + "itemrowend.html"))
tmpls["collwrapstart.html"] = template.Must(template.ParseFiles(templateDir + "collwrapstart.html"))
tmpls["collwrapend.html"] = template.Must(template.ParseFiles(templateDir + "collwrapend.html"))
store = sessions.NewCookieStore([]byte(config.Cs))
discordOauthConfig.ClientID = strconv.Itoa(config.Ci)
discordOauthConfig.ClientSecret = config.Cs
discordOauthConfig.RedirectURL = config.RedirectURL + "/discordCallback"
r := mux.NewRouter()
r.HandleFunc("/", handleMain)
r.HandleFunc("/logout", handleLogout)
r.HandleFunc("/discordLogin", handleDiscordLogin)
r.HandleFunc("/discordCallback", handleDiscordCallback)
r.HandleFunc("/playsound", handlePlaySound)
http.Handle("/", r)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("web/static"))))
err := http.ListenAndServe(":"+strconv.Itoa(config.Port), nil)
if err != nil {
slog.Error("could not start webserver", "error", err)
os.Exit(1)
}
}
func handlePlaySound(w http.ResponseWriter, r *http.Request) {
slog.Info("WebUI /playsound Request", "Requesting IP", r.RemoteAddr)
err := r.ParseForm()
if err != nil {
slog.Error("could not ParseForm", "error", err)
return
}
sound, soundCollection := findSoundAndCollection(r.FormValue("command"), r.FormValue("soundname"))
session, _ := store.Get(r, "gidbig-session")
var guild *discordgo.Guild
user, _ := discord.User(session.Values["discordUserID"].(string))
for _, g := range discord.State.Guilds {
for _, vs := range g.VoiceStates {
if vs.UserID == session.Values["discordUserID"].(string) {
guild = g
}
}
}
if user != nil && guild != nil && soundCollection != nil {
if sound != nil {
go enqueuePlay(user, guild, soundCollection, sound)
} else {
go enqueuePlay(user, guild, soundCollection, soundCollection.Random())
}
http.Error(w, http.StatusText(200), 200)
} else {
http.Error(w, http.StatusText(500), 500)
}
}
func handleMain(w http.ResponseWriter, r *http.Request) {
logWebRequests(r)
session, _ := store.Get(r, "gidbig-session")
if session.Values["discordUsername"] != nil {
var prefixes []string
var si []soundItem
for _, sc := range COLLECTIONS {
newSoundItemRandom := soundItem{
Itemprefix: sc.Prefix,
Itemcommand: "!" + sc.Prefix,
Itemsoundname: "",
Itemtext: "random",
Itemshorttext: "random",
}
prefixes = append(prefixes, sc.Prefix)
si = append(si, newSoundItemRandom)
for _, snd := range sc.Sounds {
newSoundItem := soundItem{
Itemprefix: sc.Prefix,
Itemcommand: "!" + sc.Prefix,
Itemsoundname: snd.Name,
Itemtext: "!" + sc.Prefix + " " + snd.Name,
Itemshorttext: "!" + sc.Prefix + " " + snd.Name,
}
file, e := os.Open(fmt.Sprintf("audio/%v_%v.txt", sc.Prefix, snd.Name))
if e == nil {
scanner := bufio.NewScanner(file)
scanner.Scan()
text := scanner.Text()
newSoundItem.Itemtext = text
if len(text) > 20 {
text = text[0:20]
text += "..."
}
newSoundItem.Itemshorttext = text
}
si = append(si, newSoundItem)
}
}
err := tmpls["internal.html"].ExecuteTemplate(w, "header", prefixes)
if err != nil {
fmt.Println(err)
return
}
var currentPrefix string = ""
var i int = 0
for _, snd := range si {
if snd.Itemprefix != currentPrefix {
if i != 0 {
err = tmpls["itemrowend.html"].Execute(w, nil)
if err != nil {
fmt.Println(err)
return
}
err = tmpls["collwrapend.html"].Execute(w, nil)
if err != nil {
fmt.Println(err)
return
}
i = 0
}
err = tmpls["collwrapstart.html"].Execute(w, snd)
if err != nil {
fmt.Println(err)
return
}
currentPrefix = snd.Itemprefix
}
if i%4 == 0 {
err = tmpls["itemrowstart.html"].Execute(w, nil)
if err != nil {
fmt.Println(err)
return
}
}
err = tmpls["item.html"].Execute(w, snd)
if err != nil {
fmt.Println(err)
return
}
if i%4 == 3 {
err = tmpls["itemrowend.html"].Execute(w, nil)
if err != nil {
fmt.Println(err)
return
}
}
i++
}
err = tmpls["internal.html"].ExecuteTemplate(w, "footer", map[string]interface{}{})
if err != nil {
fmt.Println(err)
return
}
return
}
err := tmpls["home.html"].ExecuteTemplate(w, "header", map[string]interface{}{})
if err != nil {
slog.Error("unable to execute template", "error", err)
return
}
err = tmpls["home.html"].ExecuteTemplate(w, "footer", map[string]interface{}{})
if err != nil {
slog.Error("unable to execute template", "error", err)
return
}
}
func handleLogout(w http.ResponseWriter, r *http.Request) {
slog.Info("WebUI /logout Request", "Requesting IP", r.RemoteAddr)
cookie := &http.Cookie{
Name: "gidbig-session",
Value: "",
Path: "/",
MaxAge: -1,
}
http.SetCookie(w, cookie)
http.Redirect(w, r, "/", http.StatusFound)
}
func handleDiscordLogin(w http.ResponseWriter, r *http.Request) {
logWebRequests(r)
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
slog.Error("unable to Read", "error", err)
return
}
oauthStateString = base64.URLEncoding.EncodeToString(b)
session, _ := store.Get(r, "gidbig-session")
session.Values["state"] = oauthStateString
err = session.Save(r, w)
if err != nil {
slog.Error("unable to Save", "error", err)
}
url := discordOauthConfig.AuthCodeURL(oauthStateString)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func handleDiscordCallback(w http.ResponseWriter, r *http.Request) {
logWebRequests(r)
session, err := store.Get(r, "gidbig-session")
if err != nil {
fmt.Fprintln(w, "aborted")
return
}
if r.URL.Query().Get("state") != session.Values["state"] {
fmt.Fprintln(w, "no state match; possible csrf OR cookies not enabled")
return
}
state := r.FormValue("state")
if state != oauthStateString {
fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
token, err := discordOauthConfig.Exchange(context.Background(), r.FormValue("code"))
if err != nil {
fmt.Fprintln(w, "Code exchange (could not get token) failed with ", err)
return
}
if !token.Valid() {
fmt.Fprintln(w, "retrieved invalid token")
return
}
dg, err := discordgo.New("Bearer " + token.AccessToken)
if err != nil {
fmt.Println("Error while creating discord session: ", err)
return
}
user, _ := dg.User("@me")
session.Values["discordUserID"] = user.ID
session.Values["discordUsername"] = user.Username
session.Values["accessToken"] = token.AccessToken
err = session.Save(r, w)
if err != nil {
slog.Error("unable to Save", "error", err)
return
}
dg.Close()
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
func parseIPPort(s string) (ip net.IP, port, space string, err error) {
ip = net.ParseIP(s)
if ip == nil {
var host string
host, port, err = net.SplitHostPort(s)
if err != nil {
return
}
if port != "" {
// This check only makes sense if service names are not allowed
if _, err = strconv.ParseUint(port, 10, 16); err != nil {
return
}
}
ip = net.ParseIP(host)
}
if ip == nil {
err = errors.New("invalid address format")
} else {
space = "IPv6"
if ip4 := ip.To4(); ip4 != nil {
space = "IPv4"
ip = ip4
}
}
return
}
func logWebRequests(r *http.Request) {
ip, port, _, err := parseIPPort(r.RemoteAddr)
if err != nil {
slog.Warn("Error parsing IP address for WebUI Request ", "Request URI", r.RequestURI)
return
}
anonIP, err := ipAnonymizer.IPString(ip.String())
if err != nil {
slog.Warn("Could not anonymize IP address for WebUI Request ", "Request URI", r.RequestURI)
} else {
slog.Info("WebUI Request", "Request URI", r.RequestURI, "Requesting IP / Port", anonIP+port)
}
}