-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
1176 lines (975 loc) · 27 KB
/
handlers.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"errors"
"io"
"net/http"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"git.sr.ht/~aqtrans/gohttputils"
"github.com/go-chi/chi/v5"
fuzzy2 "github.com/lithammer/fuzzysearch/fuzzy"
"github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
)
func (env *wikiEnv) setFavoriteHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "setFavoriteHandler")
name := chi.URLParam(r, "*")
if !wikiExistsFromContext(r.Context()) {
http.Redirect(w, r, "/"+name, http.StatusFound)
return
}
p := env.loadWikiPage(r, name)
if p.Wiki.Frontmatter.Favorite {
p.Wiki.Frontmatter.Favorite = false
env.authState.SetFlash(name+" has been un-favorited.", r)
log.Println(name + " page un-favorited!")
} else {
p.Wiki.Frontmatter.Favorite = true
env.authState.SetFlash(name+" has been favorited.", r)
log.Println(name + " page favorited!")
}
err := p.Wiki.save(env)
if err != nil {
log.WithFields(logrus.Fields{
"page": name,
"error": err,
}).Errorln("error saving wiki page")
http.Error(w, "error saving wiki page. check logs for more information", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/"+name, http.StatusSeeOther)
}
func (env *wikiEnv) deleteHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "deleteHandler")
name := chi.URLParam(r, "*")
if !wikiExistsFromContext(r.Context()) {
http.Redirect(w, r, "/"+name, http.StatusFound)
return
}
err := env.gitRmFilepath(name)
if err != nil {
log.WithFields(logrus.Fields{
"page": name,
"error": err,
}).Errorln("error deleting file from git repo")
http.Redirect(w, r, "/", http.StatusSeeOther)
}
err = env.gitCommitWithMessage(name + " has been removed from git repo.")
if err != nil {
log.WithFields(logrus.Fields{
"page": name,
"error": err,
}).Errorln("error commiting to git repo,")
http.Redirect(w, r, "/", http.StatusSeeOther)
}
env.authState.SetFlash(name+" page successfully deleted.", r)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
type result struct {
Name string
Result string
}
type searchPage struct {
page
Results []result
}
func (env *wikiEnv) searchHandler(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "*")
// If this is a POST request, and searchwiki form is not blank,
// redirect to /search/$(searchform)
if r.Method == "POST" {
r.ParseForm()
if r.PostFormValue("searchwiki") != "" {
http.Redirect(w, r, "/search/"+r.PostFormValue("searchwiki"), http.StatusSeeOther)
return
//name = r.PostFormValue("searchwiki")
}
}
p := make(chan page, 1)
go env.loadPage(r, p)
user := env.authState.GetUser(r)
var fileList string
theCache := env.loadCache()
for _, v := range theCache.Cache {
if env.authState.IsLoggedIn(r) {
if v.Permission == privatePermission {
//log.Println("priv", v.Filename)
fileList = fileList + " " + `"` + v.Filename + `"`
}
if user.IsAdmin() {
if v.Permission == adminPermission {
//log.Println("admin", v.Filename)
fileList = fileList + " " + `"` + v.Filename + `"`
}
}
}
if v.Permission == publicPermission {
//log.Println("pubic", v.Filename)
fileList = fileList + " " + `"` + v.Filename + `"`
}
}
//log.Println(fileList)
results := env.gitSearch(name, strings.TrimSpace(fileList))
s := &searchPage{
page: <-p,
Results: results,
}
renderTemplate(r.Context(), env, w, "search_results.tmpl", s)
}
func (env *wikiEnv) loginPageHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "loginPageHandler")
title := "login"
p := make(chan page, 1)
go env.loadPage(r, p)
gp := &genPage{
<-p,
title,
}
renderTemplate(r.Context(), env, w, "login.tmpl", gp)
}
func (env *wikiEnv) signupPageHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "signupPageHandler")
title := "signup"
p := make(chan page, 1)
go env.loadPage(r, p)
anyUsers := env.authState.AnyUsers()
gp := struct {
page
Title string
AnyUsers bool
}{
<-p,
title,
anyUsers,
}
renderTemplate(r.Context(), env, w, "signup.tmpl", gp)
}
func (env *wikiEnv) adminUsersHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "adminUsersHandler")
title := "admin-users"
p := make(chan page, 1)
go env.loadPage(r, p)
userlist, err := env.authState.Userlist()
if err != nil {
panic(err)
}
data := struct {
page
Title string
Users []string
}{
<-p,
title,
userlist,
}
/*gp := &genPage{
p,
title,
}*/
renderTemplate(r.Context(), env, w, "admin_users.tmpl", data)
}
func (env *wikiEnv) adminUserHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "adminUserHandler")
title := "admin-user"
p := make(chan page, 1)
go env.loadPage(r, p)
userlist, err := env.authState.Userlist()
if err != nil {
panic(err)
}
//ctx := r.Context()
selectedUser := chi.URLParam(r, "username")
data := struct {
page
Title string
Users []string
User string
}{
<-p,
title,
userlist,
selectedUser,
}
/*gp := &genPage{
p,
title,
}*/
renderTemplate(r.Context(), env, w, "admin_user.tmpl", data)
}
// Function to take a <select><option> value and redirect to a URL based on it
func adminUserPostHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
selectedUser := r.FormValue("user")
http.Redirect(w, r, "/admin/user/"+selectedUser, http.StatusSeeOther)
}
func (env *wikiEnv) adminMainHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "adminMainHandler")
title := "admin-main"
p := make(chan page, 1)
go env.loadPage(r, p)
data := struct {
page
Title string
GitSha1 string
BuildDate string
}{
<-p,
title,
sha1ver,
buildTime,
}
renderTemplate(r.Context(), env, w, "admin_main.tmpl", data)
}
func (env *wikiEnv) gitCheckinHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "gitCheckinHandler")
title := "Git Checkin"
p := make(chan page, 1)
go env.loadPage(r, p)
var s string
if r.URL.Query().Get("file") != "" {
file := r.URL.Query().Get("file")
s = file
} else {
err := env.gitIsClean()
s = err.Error()
/*
if err != nil && err != ErrGitDirty {
panic(err)
}
*/
//owithnewlines = bytes.Replace(o, []byte{0}, []byte(" <br>"), -1)
}
gp := &gitPage{
<-p,
title,
s,
env.cfg.RemoteGitRepo,
}
renderTemplate(r.Context(), env, w, "git_checkin.tmpl", gp)
}
func (env *wikiEnv) gitCheckinPostHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "gitCheckinPostHandler")
var path string
if r.URL.Query().Get("file") != "" {
//file := r.URL.Query().Get("file")
//log.Println(action)
path = r.URL.Query().Get("file")
} else {
path = "."
}
err := env.gitAddFilepath(path)
if err != nil {
panic(err)
}
err = env.gitCommitEmpty()
if err != nil {
panic(err)
}
if path != "." {
http.Redirect(w, r, "/"+path, http.StatusSeeOther)
} else {
http.Redirect(w, r, "/", http.StatusSeeOther)
}
}
func (env *wikiEnv) gitPushPostHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "gitPushPostHandler")
err := env.gitPush()
if err != nil {
panic(err)
}
http.Redirect(w, r, r.Referer(), http.StatusSeeOther)
}
func (env *wikiEnv) gitPullPostHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "gitPullPostHandler")
err := env.gitPull()
if err != nil {
panic(err)
}
http.Redirect(w, r, r.Referer(), http.StatusSeeOther)
}
func (env *wikiEnv) adminGitHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "adminGitHandler")
title := "Git Management"
p := make(chan page, 1)
go env.loadPage(r, p)
//var owithnewlines []byte
err := env.gitIsClean()
if err == nil {
err = errors.New("Git repo is clean")
}
/*
if err != nil && err != ErrGitDirty {
panic(err)
}
owithnewlines = bytes.Replace(o, []byte{0}, []byte(" <br>"), -1)
*/
gp := &gitPage{
<-p,
title,
err.Error(),
env.cfg.RemoteGitRepo,
}
renderTemplate(r.Context(), env, w, "admin_git.tmpl", gp)
}
type tagMapPage struct {
page
TagKeys map[string][]string
}
func (env *wikiEnv) tagMapHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "tagMapHandler")
p := make(chan page, 1)
go env.loadPage(r, p)
list := env.tags.GetAll()
tagpage := &tagMapPage{
page: <-p,
TagKeys: list,
}
renderTemplate(r.Context(), env, w, "tag_list.tmpl", tagpage)
}
type tagPage struct {
page
TagName string
Results []string
}
func (env *wikiEnv) tagHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "tagHandler")
name := chi.URLParam(r, "*")
p := make(chan page, 1)
go env.loadPage(r, p)
results := env.tags.GetOne(name)
tagpage := &tagPage{
page: <-p,
TagName: name,
Results: results,
}
renderTemplate(r.Context(), env, w, "tag_view.tmpl", tagpage)
}
func (env *wikiEnv) createWiki(w http.ResponseWriter, r *http.Request, name string) {
w.WriteHeader(404)
//title := "Create " + name + "?"
p := make(chan page, 1)
go env.loadPage(r, p)
wp := &wikiPage{
page: <-p,
Wiki: wiki{
Title: name,
Filename: name,
Frontmatter: frontmatter{
Title: name,
},
},
}
renderTemplate(r.Context(), env, w, "wiki_create.tmpl", wp)
return
}
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
// A very simple health check.
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
// In the future we could report back on the status of our DB, or our cache
// (e.g. Redis) by performing a simple PING, and include them in the response.
io.WriteString(w, `{"alive": true}`)
}
func (env *wikiEnv) editHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "editHandler")
name := chi.URLParam(r, "*")
p := env.loadWikiPage(r, name)
renderTemplate(r.Context(), env, w, "wiki_edit.tmpl", p)
}
func (env *wikiEnv) saveHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "saveHandler")
name := chi.URLParam(r, "*")
err := r.ParseForm()
if err != nil {
log.WithFields(logrus.Fields{
"page": name,
"error": err,
}).Errorln("error parsing request form")
http.Error(w, "error parsing form. check logs for more information", http.StatusInternalServerError)
return
}
content := r.FormValue("editor")
/*
// Strip out CRLF here,
// as I cannot figure out if it's the browser or what inserting them...
if strings.Contains(content, "\r\n") {
log.Println("crlf detected in saveHandler; replacing with just newlines.")
content = strings.Replace(content, "\r\n", "\n", -1)
//log.Println(strings.Contains(content, "\r\n"))
}
*/
// Check for and install required YAML frontmatter
title := r.FormValue("title")
// This is the separate input that tagdog.js throws new tags into
tags := r.FormValue("tags_all")
favorite := r.FormValue("favorite")
permission := r.FormValue("permission")
favoritebool := false
if favorite == "on" {
favoritebool = true
}
if title == "" {
title = name
}
var tagsA []string
if tags != "" {
tagsA = strings.Split(tags, ",")
}
fm := frontmatter{
Title: title,
Tags: tagsA,
Favorite: favoritebool,
Permission: permission,
}
thewiki := &wiki{
Title: title,
Filename: name,
Frontmatter: fm,
Content: []byte(content),
}
err = thewiki.save(env)
if err != nil {
log.WithFields(logrus.Fields{
"page": name,
"error": err,
}).Errorln("error saving wiki page")
http.Error(w, "error saving wiki page. check logs for more information", http.StatusInternalServerError)
return
}
env.authState.SetFlash("Wiki page successfully saved.", r)
http.Redirect(w, r, "/"+name, http.StatusSeeOther)
log.Println(name + " page saved!")
}
func (env *wikiEnv) indexHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "indexHandler")
if !env.authState.AnyUsers() {
log.Println("Need to signup...")
env.authState.SetFlash("Welcome! Sign up to start creating and editing pages.", r)
http.Redirect(w, r, "/signup", http.StatusSeeOther)
return
}
http.Redirect(w, r, "/index", http.StatusSeeOther)
//viewHandler(w, r, "index")
}
func (env *wikiEnv) viewHandler(w http.ResponseWriter, r *http.Request) {
defer httputils.TimeTrack(time.Now(), "viewHandler")
name := chi.URLParam(r, "*")
/*
nameStat, err := os.Stat(filepath.Join(dataDir, "wikidata", name))
if err != nil {
log.Println("viewHandler error reading", name, err)
}
if err == nil {
if nameStat.IsDir() {
// Check if name/index exists, and if it does, serve it
_, err := os.Stat(filepath.Join(dataDir, "wikidata", name, "index"))
if err == nil {
http.Redirect(w, r, "/"+filepath.Join(name, "index"), http.StatusFound)
return
}
if os.IsNotExist(err) {
// TODO: List directory
log.Println("TODO: List directory")
}
}
}
*/
wikiExists := wikiExistsFromContext(r.Context())
if !wikiExists {
httputils.Debugln("wikiExists false: No such file...creating one.")
//http.Redirect(w, r, "/edit/"+name, http.StatusTemporaryRedirect)
env.createWiki(w, r, name)
return
}
// If this is a commit, pass along the SHA1 to that function
if r.URL.Query().Get("commit") != "" {
// Only allow logged in users to view past pages, in case information had to be redacted on a now-public page
if env.authState.IsLoggedIn(r) {
commit := r.URL.Query().Get("commit")
//utils.Debugln(r.URL.Query().Get("commit"))
env.viewCommitHandler(w, r, commit, name)
return
}
mitigateWiki(true, env, r, w)
return
}
if !isWiki(filepath.Join(env.cfg.WikiDir, name)) {
http.ServeFile(w, r, filepath.Join(env.cfg.WikiDir, name))
return
}
// Get Wiki
p := env.loadWikiPage(r, name)
// Build a list of filenames to be fed to closestmatch, for similarity matching
var filelist []string
user := env.authState.GetUser(r)
theCache := env.loadCache()
// TODO: Replace this with a call to listDir() somehow
for _, v := range theCache.Cache {
if v.Permission == publicPermission {
//log.Println("pubic", v.Filename)
filelist = append(filelist, v.Filename)
}
if env.authState.IsLoggedIn(r) {
if v.Permission == privatePermission {
//log.Println("priv", v.Filename)
filelist = append(filelist, v.Filename)
}
}
if user.IsAdmin() {
if v.Permission == adminPermission {
//log.Println("admin", v.Filename)
filelist = append(filelist, v.Filename)
}
}
}
// Check for similar filenames
/*
var similarPages []string
for _, match := range fuzzy.Find(name, filelist) {
similarPages = append(similarPages, match.Str)
}
*/
similarPages := fuzzy2.FindFold(name, filelist)
p.SimilarPages = similarPages
renderTemplate(r.Context(), env, w, "wiki_view.tmpl", p)
return
/*
var html template.HTML
if strings.Contains(fileType, "image") {
html = template.HTML(`<img src="/` + name + `">`)
}
p := loadPage(env, r)
data := struct {
*page
Title string
TheHTML template.HTML
}{
p,
name,
html,
}
renderTemplate(r.Context(), env, w, "file_view.tmpl", data)
*/
}
type historyPage struct {
page
Wiki wiki
Filename string
FileHistory []commitLog
}
func (env *wikiEnv) historyHandler(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "*")
if !wikiExistsFromContext(r.Context()) {
http.Redirect(w, r, "/"+name, http.StatusSeeOther)
return
}
wikip := env.loadWikiPage(r, name)
history, err := env.gitGetFileLog(name)
if err != nil {
panic(err)
}
hp := &historyPage{
wikip.page,
wikip.Wiki,
name,
history,
}
renderTemplate(r.Context(), env, w, "wiki_history.tmpl", hp)
}
// Need to get content of the file at specified commit
// > git show [commit sha1]:[filename]
// As well as the date
// > git log -1 --format=%at [commit sha1]
// TODO: need to find a way to detect sha1s
type commitPage struct {
page
Wiki wiki
Commit string
Rendered string
Diff string
}
func (env *wikiEnv) viewCommitHandler(w http.ResponseWriter, r *http.Request, commit, name string) {
var fm frontmatter
var pageContent string
//commit := vars["commit"]
p := make(chan page, 1)
go env.loadPage(r, p)
body, err := env.gitGetFileCommit(name, commit)
if err != nil {
panic(err)
}
ctime, err := env.gitGetCtime(name)
if err != nil && err != errNotInGit {
panic(err)
}
mtime, err := env.gitGetFileCommitMtime(commit)
if err != nil {
panic(err)
}
diff, err := env.gitGetFileCommitDiff(name, commit)
if err != nil {
panic(err)
}
// Read YAML frontmatter into fm
reader := bytes.NewReader(body)
fm, content := readWikiPage(reader)
if err != nil {
panic(err)
}
// Render remaining content after frontmatter
md := markdownRender(content)
//md := commonmarkRender(content)
pagetitle := setPageTitle(fm.Title, name)
diffstring := string(diff)
pageContent = md
cp := &commitPage{
page: <-p,
Wiki: wiki{
Title: pagetitle,
Filename: name,
Frontmatter: fm,
Content: content,
CreateTime: ctime,
ModTime: mtime,
},
Commit: commit,
Rendered: pageContent,
Diff: diffstring,
}
renderTemplate(r.Context(), env, w, "wiki_commit.tmpl", cp)
}
type recent struct {
Date int64
Commit string
Filenames []string
}
type recentsPage struct {
page
Recents []recent
}
// TODO: Fix this
func (env *wikiEnv) recentHandler(w http.ResponseWriter, r *http.Request) {
p := make(chan page, 1)
go env.loadPage(r, p)
gh, err := env.gitHistory()
if err != nil {
log.WithFields(logrus.Fields{
"error": err,
}).Errorln("error getting git history")
http.Error(w, "Unable to fetch git history", 500)
return
}
/*
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(200)
*/
var split []string
var split2 []string
var recents []recent
for _, v := range gh {
split = strings.Split(strings.TrimSpace(v), " ")
date, err := strconv.ParseInt(split[0], 0, 64)
if err != nil {
panic(err)
}
// If there is a filename (initial one will not have it)...
split2 = strings.Split(split[1], "\n")
if len(split2) >= 2 {
r := recent{
Date: date,
Commit: split2[0],
Filenames: strings.Split(split2[1], "\n"),
}
//w.Write([]byte(v + "<br>"))
recents = append(recents, r)
}
}
s := recentsPage{
page: <-p,
Recents: recents,
}
renderTemplate(r.Context(), env, w, "recents.tmpl", s)
}
type listPage struct {
page
Wikis []gitDirList
}
func (env *wikiEnv) listHandler(w http.ResponseWriter, r *http.Request) {
p := make(chan page, 1)
go env.loadPage(r, p)
var list []gitDirList
user := env.authState.GetUser(r)
theCache := env.loadCache()
for _, v := range theCache.Cache {
if v.Permission == publicPermission {
//log.Println("pubic", v.Filename)
list = append(list, v)
}
if env.authState.IsLoggedIn(r) {
if v.Permission == privatePermission {
//log.Println("priv", v.Filename)
list = append(list, v)
}
}
if user.IsAdmin() {
if v.Permission == adminPermission {
//log.Println("admin", v.Filename)
list = append(list, v)
}
}
}
l := listPage{
page: <-p,
Wikis: list,
}
renderTemplate(r.Context(), env, w, "list.tmpl", l)
}
func (env *wikiEnv) securityCheck(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Security check; ensure we are not serving any files from wikidata/.git
// If so, toss them to the index, no hints given
if strings.Contains(r.URL.EscapedPath(), ".git") {
http.Error(w, "unable to access that", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func (env *wikiEnv) wikiMiddle(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "*")
user := env.authState.GetUser(r)
pageExists, relErr := env.checkName(&name)
fullfilename := filepath.Join(env.cfg.WikiDir, name)
//wikiDir := filepath.Join(dataDir, "wikidata")
if relErr != nil {
if relErr == errBaseNotDir {
http.Error(w, "Cannot create subdir of a file.", 500)
return
}
// If we have a directory, do some stuff:
if relErr == errIsDir {
// If we have a ?list query string, just list it
if r.URL.Query().Get("list") != "" {
env.listDirHandler(name, w, r)
return
}
// If the given name is a directory, and URL is just /name/, check for /name/index
// If name/index exists, redirect to it
if r.URL.Path[:len("/"+name)] == "/"+name {
// Check if name/index exists, and if it does, serve it
_, err := os.Stat(filepath.Join(env.cfg.WikiDir, name, "index"))
if err == nil {
http.Redirect(w, r, "/"+path.Join(name, "index"), http.StatusFound)
return
}
}
// Otherwise fallback to just listing it
env.listDirHandler(name, w, r)
return
}
httpErrorHandler(w, r, relErr)
return
}
nameCtx := newNameContext(r.Context(), name)
ctx := newWikiExistsContext(nameCtx, pageExists)
r = r.WithContext(ctx)
if wikiRejected(fullfilename, pageExists, user.IsAdmin(), env.authState.IsLoggedIn(r)) {
mitigateWiki(true, env, r, w)
} else {
next.ServeHTTP(w, r)
return
}
})
}
/*
// wikiHandler wraps around all wiki page handlers
// Currently it retrieves the page name from params, checks for file existence, and checks for private pages
func wikiHandler(fn wHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Here we will extract the page title from the Request,
// and call the provided handler 'fn'
params := httptreemux.ContextParams(r.Context())
name := params["name"]
username, isAdmin := auth.GetUsername(r.Context())
// Check if file exists before doing anything else
name, feErr := checkName(name)
fullname := filepath.Join(viper.GetString("WikiDir"), name)
isWikiPage(fullname)
if name != "" && feErr == errNoFile {
//log.Println(r.URL.RequestURI())
// If editing or saving, bypass create page
if r.URL.RequestURI() == "/edit/"+name {
fn(w, r, name)
return
}
if r.URL.RequestURI() == "/save/"+name {
fn(w, r, name)
return
}
createWiki(w, r, name)
return
} else if feErr != nil {
httpErrorHandler(w, r, feErr)
return
}
// Detect filetypes
// filetype := checkFiletype(fullname)