all repos — felt @ main

virtual tabletop for dungeons and dragons (and similar) using Go, MongoDB, and websockets

admin/admin.go (raw)

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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package admin

import (
	"encoding/json"
	"fmt"
	"hacklab.nilfm.cc/felt/admin/util"
	"hacklab.nilfm.cc/felt/models"
	"hacklab.nilfm.cc/felt/mongodb"
	"hacklab.nilfm.cc/quartzgun/auth"
	. "hacklab.nilfm.cc/quartzgun/middleware"
	"hacklab.nilfm.cc/quartzgun/renderer"
	"hacklab.nilfm.cc/quartzgun/router"
	. "hacklab.nilfm.cc/quartzgun/util"
	"html/template"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

func apiGetTableList(next http.Handler, udb auth.UserStore) http.Handler {
	handlerFunc := func(w http.ResponseWriter, req *http.Request) {

		user := util.GetUserFromToken(req)
		self, err := util.GetTablesByUser(user, udb)
		if err != nil {
			w.WriteHeader(404)
		} else {
			AddContextValue(req, "tableList", self)
		}
		next.ServeHTTP(w, req)
	}

	return http.HandlerFunc(handlerFunc)
}

func apiGetTableData(next http.Handler, udb auth.UserStore, dbAdapter mongodb.DbAdapter) http.Handler {
	handlerFunc := func(w http.ResponseWriter, req *http.Request) {

		urlParams := req.Context().Value("params").(map[string]string)
		tableName := urlParams["Slug"]
		tableKey := models.TableKey{
			Name:     tableName,
			Passcode: req.FormValue("passcode"),
		}

		if dbAdapter.CheckTable(tableKey) {
			mapUrl, _ := dbAdapter.GetMapImageUrl(tableKey)
			auxMessage, _ := dbAdapter.GetAuxMessage(tableKey)
			tokens, _ := dbAdapter.GetTokens(tableKey, false)
			diceRolls, _ := dbAdapter.GetDiceRolls(tableKey)

			AddContextValue(req, "tableData", models.Table{
				Name:        tableKey.Name,
				Passcode:    tableKey.Passcode,
				DiceRolls:   diceRolls,
				MapImageUrl: mapUrl,
				Tokens:      tokens,
				AuxMessage:  auxMessage,
			})
		} else {
			w.WriteHeader(404)
		}

		next.ServeHTTP(w, req)
	}

	return http.HandlerFunc(handlerFunc)
}

func apiCreateTable(next http.Handler, udb auth.UserStore, dbAdapter mongodb.DbAdapter) http.Handler {
	handlerFunc := func(w http.ResponseWriter, req *http.Request) {
		tableKey := models.TableKey{}
		err := json.NewDecoder(req.Body).Decode(&tableKey)
		if err != nil {
			w.WriteHeader(400)
			next.ServeHTTP(w, req)
			return
		}

		r := regexp.MustCompile("^[a-zA-Z0-9_]+$")
		if !r.MatchString(tableKey.Name) || !r.MatchString(tableKey.Passcode) {
			w.WriteHeader(422)
			next.ServeHTTP(w, req)
			return
		}

		// table name is primary key so w edon't need to check
		err = dbAdapter.CreateTable(tableKey)

		if err != nil {
			AddContextValue(req, "result", err.Error())
			// TODO: parse error and change the status
			w.WriteHeader(500)
		} else {
			user := util.GetUserFromToken(req)
			tables, err := util.GetTablesByUser(user, udb)
			tables = append(tables, tableKey)
			err = util.SetTablesForUser(user, tables, udb)
			if err != nil {
				w.WriteHeader(500)
			} else {
				w.WriteHeader(201)
			}
		}
		next.ServeHTTP(w, req)
	}

	return http.HandlerFunc(handlerFunc)
}

func apiDestroyTable(next http.Handler, udb auth.UserStore, dbAdapter mongodb.DbAdapter, uploads string) http.Handler {
	handlerFunc := func(w http.ResponseWriter, req *http.Request) {
		// check table actually belongs to this user
		user := util.GetUserFromToken(req)
		tables, err := util.GetTablesByUser(user, udb)

		if err == nil {

			destroy := false
			i := 0

			table := models.TableKey{}
			err = json.NewDecoder(req.Body).Decode(&table)
			if err != nil {
				w.WriteHeader(400)
				return
			}

			for j, t := range tables {
				if t.Name == table.Name && t.Passcode == table.Passcode {

					// try to destroy it
					destroy = dbAdapter.DestroyTable(table) == nil
					i = j
					break
				}
			}

			if destroy {
				os.RemoveAll(filepath.Join(uploads, table.Name))
				newTables := append(tables[:i], tables[i+1:]...)
				util.SetTablesForUser(user, newTables, udb)
				w.WriteHeader(204)
			} else {
				w.WriteHeader(404)
			}
			next.ServeHTTP(w, req)

		} else {
			w.WriteHeader(500)
		}
		next.ServeHTTP(w, req)
	}

	return http.HandlerFunc(handlerFunc)
}

func apiUploadImg(next http.Handler, dbAdapter mongodb.DbAdapter, uploads, uploadType string, uploadMax int) http.Handler {
	handlerFunc := func(w http.ResponseWriter, req *http.Request) {
		// get table from request body
		r, err := req.MultipartReader()
		if err != nil {
			fmt.Println(err.Error())
		}

		f, err := r.ReadForm(int64(uploadMax << 20))
		if err != nil {
			fmt.Println(err.Error())
		}

		tableKey := models.TableKey{
			Name:     f.Value["name"][0],
			Passcode: f.Value["passcode"][0],
		}

		// check if this table exists
		if !dbAdapter.CheckTable(tableKey) {
			w.WriteHeader(404)
			next.ServeHTTP(w, req)
			return
		}

		// ensure data storage dir exists
		info, err := os.Stat(uploads)
		if !info.IsDir() {
			fmt.Println("uploads dir aint no dir")
			w.WriteHeader(500)
			next.ServeHTTP(w, req)
			return
		} else if err != nil {
			err = os.MkdirAll(uploads, 0755)
			if err != nil {
				fmt.Println(err.Error())
				w.WriteHeader(500)
				next.ServeHTTP(w, req)
			}
		}
		err = os.MkdirAll(filepath.Join(uploads, tableKey.Name, uploadType), 0755)
		// check for filename; call create to overwrite regardless
		// get file data from multipart form
		header := f.File["file"][0]
		if strings.Contains(header.Filename, "/") {
		  w.WriteHeader(422)
		  next.ServeHTTP(w, req)
		  return
		}
		file, err := header.Open()
		if err != nil {
			fmt.Println(err.Error())
			w.WriteHeader(500)
			next.ServeHTTP(w, req)
			return
		}
		fileData, err := ioutil.ReadAll(file)
		if err != nil {
			w.WriteHeader(500)
			next.ServeHTTP(w, req)
			return
		}
		// write to file
		destPath := filepath.Join(uploads, tableKey.Name, uploadType, header.Filename)
		fmt.Println(destPath)
		dest, err := os.Create(destPath)
		if err != nil {
			fmt.Println(err.Error())
			w.WriteHeader(500)
			next.ServeHTTP(w, req)
			return
		}
		dest.Write(fileData)
		dest.Close()

		// respond with URL so UI can update
		AddContextValue(req, "location", "/uploads/"+tableKey.Name+"/"+uploadType+"/"+header.Filename)
		next.ServeHTTP(w, req)
	}

	return http.HandlerFunc(handlerFunc)
}

func apiListImages(next http.Handler, uploads string, uploadType string, udb auth.UserStore, dbAdapter mongodb.DbAdapter) http.Handler {
	handlerFunc := func(w http.ResponseWriter, req *http.Request) {
		urlParams := req.Context().Value("params").(map[string]string)
		tableName := urlParams["Slug"]
		tableKey := models.TableKey{
			Name:     tableName,
			Passcode: req.FormValue("passcode"),
		}

		// check table actually belongs to this user
		user := util.GetUserFromToken(req)
		tables, err := util.GetTablesByUser(user, udb)

		if err == nil {

			ok := false

			for _, t := range tables {
				if t.Name == tableKey.Name && t.Passcode == tableKey.Passcode {
					ok = true
				}
			}

			if ok {
				if dbAdapter.CheckTable(tableKey) {
					destPath := filepath.Join(uploads, tableName, uploadType)
					files, err := ioutil.ReadDir(destPath)

					if err != nil {
						w.WriteHeader(500)
						next.ServeHTTP(w, req)
						return
					}

					fileNames := []string{}
					for _, file := range files {
						if !file.IsDir() {
							fileNames = append(fileNames, "/uploads/"+tableName+"/"+uploadType+"/"+file.Name())
						}
					}

					AddContextValue(req, "files", fileNames)
					next.ServeHTTP(w, req)
					return
				}
			}
		}
		w.WriteHeader(422)
		next.ServeHTTP(w, req)
	}

	return http.HandlerFunc(handlerFunc)
}

func apiDeleteImage(next http.Handler, uploads string, uploadType string, udb auth.UserStore, dbAdapter mongodb.DbAdapter) http.Handler {
	handlerFunc := func(w http.ResponseWriter, req *http.Request) {
		// put the path together
		urlParams := req.Context().Value("params").(map[string]string)
		tableName := urlParams["table"]
		tableKey := models.TableKey{
			Name:     tableName,
			Passcode: req.FormValue("passcode"),
		}

		// check table actually belongs to this user
		user := util.GetUserFromToken(req)
		tables, err := util.GetTablesByUser(user, udb)

		if err == nil {

			ok := false

			for _, t := range tables {
				if t.Name == tableKey.Name && t.Passcode == tableKey.Passcode {
					ok = true
				}
			}

			if ok {
				if dbAdapter.CheckTable(tableKey) {
					// if the file exists, delete it and return 201
					filename := urlParams["file"]
					if strings.Contains(filename, "/") {
					  w.WriteHeader(422)
					  next.ServeHTTP(w, req)
					  return
					}
					fullPath := filepath.Join(uploads, tableName, uploadType, filename)
					s, err := os.Stat(fullPath)
					if err == nil && !s.IsDir() {
						err = os.Remove(fullPath)
						if err == nil {
							w.WriteHeader(201)
							next.ServeHTTP(w, req)
							return
						}
					}
				}
			}
		}
		// otherwise, return an error
		w.WriteHeader(500)
		next.ServeHTTP(w, req)
	}

	return http.HandlerFunc(handlerFunc)
}

func CreateAdminInterface(udb auth.UserStore, dbAdapter mongodb.DbAdapter, uploads string, uploadMaxMB int) http.Handler {
	// create quartzgun router
	rtr := &router.Router{Fallback: *template.Must(template.ParseFiles("templates/error.html"))}

	scopes := map[string]string{}

	rtr.Post("/api/auth/", Provision(udb, 84))

	// table management
	rtr.Get("/api/table/", Validate(apiGetTableList(renderer.JSON("tableList"), udb), udb, scopes))
	rtr.Get(`/api/table/(?P<Slug>\S+)`, Validate(apiGetTableData(renderer.JSON("tableData"), udb, dbAdapter), udb, scopes))
	rtr.Post("/api/table/", Validate(apiCreateTable(renderer.JSON("result"), udb, dbAdapter), udb, scopes))
	rtr.Delete(`/api/table/(?P<Slug>\S+)`, Validate(apiDestroyTable(renderer.JSON("result"), udb, dbAdapter, uploads), udb, scopes))

	// asset management
	rtr.Post(`/api/upload/(?P<Slug>\S+)/map/`, Validate(apiUploadImg(renderer.JSON("location"), dbAdapter, uploads, "map", uploadMaxMB), udb, scopes))
	rtr.Get(`/api/upload/(?P<Slug>\S+)/map/`, Validate(apiListImages(renderer.JSON("files"), uploads, "map", udb, dbAdapter), udb, scopes))
	rtr.Delete(`/api/upload/(?P<table>\S+)/map/(?P<file>\S+)`, Validate(apiDeleteImage(renderer.JSON("deleted"), uploads, "map", udb, dbAdapter), udb, scopes))
	rtr.Delete(`/api/upload/(?P<table>\S+)/token/(?P<file>\S+)`, Validate(apiDeleteImage(renderer.JSON("deleted"), uploads, "token", udb, dbAdapter), udb, scopes))
	rtr.Post(`/api/upload/(?P<Slug>\S+)/token/`, Validate(apiUploadImg(renderer.JSON("location"), dbAdapter, uploads, "token", uploadMaxMB), udb, scopes))
	rtr.Get(`/api/upload/(?P<Slug>\S+)/token/`, Validate(apiListImages(renderer.JSON("files"), uploads, "token", udb, dbAdapter), udb, scopes))

	return http.HandlerFunc(rtr.ServeHTTP)
}