diff options
author | Alexander NeonXP Kiryukhin <i@neonxp.ru> | 2024-07-28 19:32:33 +0300 |
---|---|---|
committer | Alexander NeonXP Kiryukhin <i@neonxp.ru> | 2024-07-28 19:32:33 +0300 |
commit | 18a9096684ab0b1468a08d442d38b7b675d94810 (patch) | |
tree | 16e335e56ac0bf7986c3fbcd924f2ac0e00106f8 /session.go | |
parent | 25160ef84704c0f4ef6e8c6cf2e282e216701139 (diff) |
Diffstat (limited to 'session.go')
-rw-r--r-- | session.go | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/session.go b/session.go new file mode 100644 index 0000000..11944d4 --- /dev/null +++ b/session.go @@ -0,0 +1,65 @@ +package middleware + +import ( + "context" + "net/http" + + "go.neonxp.ru/middleware/session" + "go.neonxp.ru/objectid" +) + +type SessionConfig struct { + SessionCookie string + Path string + Domain string + Secure bool + HttpOnly bool + MaxAge int +} + +type SessionManager struct { + SessionID string + Storer session.Store + MaxAge int +} + +func (s *SessionManager) Load(ctx context.Context) session.Value { + return s.Storer.Load(ctx, s.SessionID) +} + +func (s *SessionManager) Save(ctx context.Context, value session.Value) error { + return s.Storer.Save(ctx, s.SessionID, value) +} + +func (s *SessionManager) SetMaxAge(maxAge int) { + s.MaxAge = maxAge +} + +func Session(config *SessionConfig, storer session.Store) Middleware { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + sessionID := objectid.New().String() + cookie, err := r.Cookie(config.SessionCookie) + if err == nil { + sessionID = cookie.Value + } + sessionManager := &SessionManager{SessionID: sessionID, Storer: storer, MaxAge: config.MaxAge} + + h.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), sessionKey, &sessionManager))) + + http.SetCookie(w, &http.Cookie{ + Name: config.SessionCookie, + Value: sessionID, + Path: config.Path, + Domain: config.Domain, + Secure: config.Secure, + HttpOnly: config.HttpOnly, + MaxAge: sessionManager.MaxAge, + }) + }) + } +} + +func SessionFromRequest(r *http.Request) *SessionManager { + return r.Context().Value(sessionKey).(*SessionManager) +} |