/
mid.go
88 lines (72 loc) · 2.16 KB
/
mid.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
package web
// Most of this is borrowed from HortBot's own web package.
import (
"database/sql"
"errors"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/holedaemon/bot2/internal/db/models"
"github.com/volatiletech/sqlboiler/v4/queries/qm"
"github.com/zikaeroh/ctxlog"
"go.uber.org/zap"
)
func requestLogger(logger *zap.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := ctxlog.WithLogger(r.Context(), logger)
next.ServeHTTP(w, r.WithContext(ctx))
}
return http.HandlerFunc(fn)
}
}
func (s *Server) recoverer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rvr := recover(); rvr != nil {
ctx := ctxlog.WithOptions(r.Context(), zap.AddStacktrace(zap.ErrorLevel))
ctxlog.Error(ctx, "PANIC", zap.Any("val", rvr))
s.errorPage(w, r, http.StatusInternalServerError, "")
}
}()
next.ServeHTTP(w, r)
})
}
func (s *Server) guildCheck(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
id := s.sessionManager.GetString(ctx, sessionDiscordID)
if id == "" {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
gid := chi.URLParam(r, "id")
if gid == "" {
s.errorPage(w, r, http.StatusBadRequest, "")
return
}
exists, err := models.Guilds(qm.Where("guild_id = ?", gid)).Exists(ctx, s.db)
if err != nil {
ctxlog.Error(ctx, "error checking if guild exists", zap.Error(err))
s.errorPage(w, r, http.StatusInternalServerError, "")
return
}
if !exists {
s.errorPage(w, r, http.StatusNotFound, "That guild ain't real, guy")
return
}
guilds, err := s.fetchGuilds(ctx, id)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
http.Redirect(w, r, "/login", http.StatusOK)
return
}
ctxlog.Error(ctx, "error fetching guilds", zap.Error(err))
s.errorPage(w, r, http.StatusInternalServerError, "")
return
}
if !stringInSlice(gid, guilds) {
s.errorPage(w, r, http.StatusForbidden, "CAN'T LET YOU DO THAT!!!!!")
}
next.ServeHTTP(w, r)
})
}