aboutsummaryrefslogtreecommitdiff
path: root/pkg/ext/middleware.go
diff options
context:
space:
mode:
authorGabriel Arakaki Giovanini <mail@gabrielgio.me>2023-02-26 19:54:48 +0100
committerGabriel Arakaki Giovanini <mail@gabrielgio.me>2023-06-18 16:30:36 +0200
commitc8e1328164e9ffbd681c3c0e449f1e6b9856b896 (patch)
treefaee639a4c55c5dc3bfc59a5400026822c40221d /pkg/ext/middleware.go
downloadlens-c8e1328164e9ffbd681c3c0e449f1e6b9856b896.tar.gz
lens-c8e1328164e9ffbd681c3c0e449f1e6b9856b896.tar.bz2
lens-c8e1328164e9ffbd681c3c0e449f1e6b9856b896.zip
feat: Inicial commit
It contains rough template for the server and runners. It contains rough template for the server and runners.
Diffstat (limited to 'pkg/ext/middleware.go')
-rw-r--r--pkg/ext/middleware.go89
1 files changed, 89 insertions, 0 deletions
diff --git a/pkg/ext/middleware.go b/pkg/ext/middleware.go
new file mode 100644
index 0000000..771c0ac
--- /dev/null
+++ b/pkg/ext/middleware.go
@@ -0,0 +1,89 @@
+package ext
+
+import (
+ "encoding/base64"
+ "time"
+
+ "github.com/sirupsen/logrus"
+ "github.com/valyala/fasthttp"
+)
+
+func HTML(next fasthttp.RequestHandler) fasthttp.RequestHandler {
+ return func(ctx *fasthttp.RequestCtx) {
+ ctx.Response.Header.SetContentType("text/html")
+ next(ctx)
+ }
+}
+
+type LogMiddleware struct {
+ entry *logrus.Entry
+}
+
+func NewLogMiddleare(log *logrus.Entry) *LogMiddleware {
+ return &LogMiddleware{
+ entry: log,
+ }
+}
+
+func (l *LogMiddleware) HTTP(next fasthttp.RequestHandler) fasthttp.RequestHandler {
+ return func(ctx *fasthttp.RequestCtx) {
+ start := time.Now()
+ next(ctx)
+ elapsed := time.Since(start)
+ l.entry.
+ WithField("time", elapsed).
+ WithField("code", ctx.Response.StatusCode()).
+ WithField("path", string(ctx.Path())).
+ WithField("bytes", len(ctx.Response.Body())).
+ Info(string(ctx.Request.Header.Method()))
+ }
+}
+
+type AuthMiddleware struct {
+ key []byte
+ entry *logrus.Entry
+}
+
+func NewAuthMiddleware(key []byte, log *logrus.Entry) *AuthMiddleware {
+ return &AuthMiddleware{
+ key: key,
+ entry: log.WithField("context", "auth"),
+ }
+}
+
+func (a *AuthMiddleware) LoggedIn(next fasthttp.RequestHandler) fasthttp.RequestHandler {
+ return func(ctx *fasthttp.RequestCtx) {
+ path := string(ctx.Path())
+ if path == "/login" {
+ next(ctx)
+ return
+ }
+
+ redirectLogin := "/login?redirect=" + path
+ authBase64 := ctx.Request.Header.Cookie("auth")
+ if authBase64 == nil {
+ a.entry.Info("No auth provided")
+ ctx.Redirect(redirectLogin, 307)
+ return
+ }
+
+ auth, err := base64.StdEncoding.DecodeString(string(authBase64))
+ if err != nil {
+ a.entry.Error(err)
+ return
+ }
+
+ token, err := ReadToken(auth, a.key)
+ if err != nil {
+ a.entry.Error(err)
+ ctx.Redirect(redirectLogin, 307)
+ return
+ }
+ ctx.SetUserValue("token", token)
+ a.entry.
+ WithField("userID", token.UserID).
+ WithField("username", token.Username).
+ Info("user recognized")
+ next(ctx)
+ }
+}