diff options
author | GrailFinder <wohilas@gmail.com> | 2024-04-28 07:03:36 +0300 |
---|---|---|
committer | GrailFinder <wohilas@gmail.com> | 2024-04-28 07:03:36 +0300 |
commit | 8d66ec58e2256412a2fd50ad9e651c09af1ea8cc (patch) | |
tree | 23ad5c78ba2b2da32628e9004fe932e6fa63e26b /internal/handlers/middleware.go | |
parent | b33be53ea9c0be523988a9412fd8e3f6a24782b3 (diff) |
Feat: auth middleware; login [wip]
Diffstat (limited to 'internal/handlers/middleware.go')
-rw-r--r-- | internal/handlers/middleware.go | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go new file mode 100644 index 0000000..28ccdbc --- /dev/null +++ b/internal/handlers/middleware.go @@ -0,0 +1,48 @@ +package handlers + +import ( + "context" + "errors" + "net/http" +) + +func (h *Handlers) GetSession(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + sessionCookie, err := r.Cookie("session_token") + if err != nil { + msg := "auth failed; failed to get session token from cookies" + h.log.Debug(msg, "error", err) + next.ServeHTTP(w, r) + return + } + sessionToken := "" + if sessionCookie.Value == "" { + sessionToken = sessionCookie.Value + } + userSession, err := h.cacheGetSession(sessionCookie.Value) + if err != nil { + msg := "auth failed; session does not exists" + err = errors.New(msg) + h.log.Debug(msg, "error", err) + next.ServeHTTP(w, r) + return + } + if userSession.IsExpired() { + h.mc.RemoveKey(sessionToken) + msg := "session is expired" + h.log.Debug(msg, "error", err, "token", sessionToken) + next.ServeHTTP(w, r) + return + } + ctx := context.WithValue(r.Context(), + "username", userSession.Username) + if err := h.cacheSetSession(sessionToken, + userSession); err != nil { + msg := "failed to marshal user session" + h.log.Warn(msg, "error", err) + next.ServeHTTP(w, r) + return + } + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} |