diff options
Diffstat (limited to 'internal/handlers/auth.go')
-rw-r--r-- | internal/handlers/auth.go | 23 |
1 files changed, 19 insertions, 4 deletions
diff --git a/internal/handlers/auth.go b/internal/handlers/auth.go index 5ec1c80..e7eca50 100644 --- a/internal/handlers/auth.go +++ b/internal/handlers/auth.go @@ -3,6 +3,9 @@ package handlers import ( "apjournal/internal/models" "apjournal/pkg/utils" + "crypto/hmac" + "crypto/sha256" + "encoding/base64" "encoding/json" "html/template" "net/http" @@ -61,6 +64,7 @@ func (h *Handlers) HandleLogin(w http.ResponseWriter, r *http.Request) { } func (h *Handlers) makeCookie(username string, remote string) (*http.Cookie, error) { + // secret // Create a new random session token // sessionToken := xid.New().String() sessionToken := "token" @@ -70,10 +74,18 @@ func (h *Handlers) makeCookie(username string, remote string) (*http.Cookie, err Username: username, Expiry: expiresAt, } - // TODO: write session to db + cookieName := "session_token" + // hmac to protect cookies + hm := hmac.New(sha256.New, []byte(h.cfg.CookieSecret)) + hm.Write([]byte(cookieName)) + hm.Write([]byte(sessionToken)) + signature := hm.Sum(nil) + // b64 enc to avoid non-ascii + cookieValue := base64.URLEncoding.EncodeToString([]byte( + string(signature) + sessionToken)) cookie := &http.Cookie{ - Name: "session_token", - Value: sessionToken, + Name: cookieName, + Value: cookieValue, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode, @@ -86,7 +98,10 @@ func (h *Handlers) makeCookie(username string, remote string) (*http.Cookie, err cookie.Domain = "192.168.0.101" } // set ctx? - // c.Set("username", username) + // set user in session + if err := h.cacheSetSession(sessionToken, session); err != nil { + return nil, err + } return cookie, nil } |