diff options
author | GrailFinder <wohilas@gmail.com> | 2024-05-05 08:57:23 +0300 |
---|---|---|
committer | GrailFinder <wohilas@gmail.com> | 2024-05-05 08:57:23 +0300 |
commit | ff86222fc9ab85fb4c5c5e8a063083595b323761 (patch) | |
tree | 01dbec5503bfabc21af93acdbfe3d1000e2386a0 /internal/handlers/middleware.go | |
parent | 8d66ec58e2256412a2fd50ad9e651c09af1ea8cc (diff) |
Enha: protected cookies
Diffstat (limited to 'internal/handlers/middleware.go')
-rw-r--r-- | internal/handlers/middleware.go | 37 |
1 files changed, 32 insertions, 5 deletions
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go index 28ccdbc..8b871a2 100644 --- a/internal/handlers/middleware.go +++ b/internal/handlers/middleware.go @@ -2,24 +2,51 @@ package handlers import ( "context" + "crypto/hmac" + "crypto/sha256" + "encoding/base64" "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") + cookieName := "session_token" + sessionCookie, err := r.Cookie(cookieName) 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 + cookieValueB, err := base64.URLEncoding. + DecodeString(sessionCookie.Value) + if err != nil { + msg := "auth failed; failed to decode b64 cookie" + h.log.Debug(msg, "error", err) + next.ServeHTTP(w, r) + return + } + cookieValue := string(cookieValueB) + if len(cookieValue) < sha256.Size { + h.log.Warn("small cookie", "size", len(cookieValue)) + next.ServeHTTP(w, r) + return + } + // Split apart the signature and original cookie value. + signature := cookieValue[:sha256.Size] + sessionToken := cookieValue[sha256.Size:] + //verify signature + mac := hmac.New(sha256.New, []byte(h.cfg.CookieSecret)) + mac.Write([]byte(cookieName)) + mac.Write([]byte(sessionToken)) + expectedSignature := mac.Sum(nil) + if !hmac.Equal([]byte(signature), expectedSignature) { + h.log.Debug("cookie with an invalid sign") + next.ServeHTTP(w, r) + return } - userSession, err := h.cacheGetSession(sessionCookie.Value) + userSession, err := h.cacheGetSession(sessionToken) if err != nil { msg := "auth failed; session does not exists" err = errors.New(msg) |