diff options
author | René 'Necoro' Neumann <necoro@necoro.eu> | 2024-02-14 00:23:02 +0100 |
---|---|---|
committer | René 'Necoro' Neumann <necoro@necoro.eu> | 2024-02-14 00:23:02 +0100 |
commit | 24c2071fcaa8065d450dae78a80a671697f0e873 (patch) | |
tree | 7c301de897b0b51079090fdc10560fc52f4f97ed /session | |
parent | 4c98ab6a3a1f41ebaa5360a6a4615cd705a94db0 (diff) | |
download | gosten-24c2071fcaa8065d450dae78a80a671697f0e873.tar.gz gosten-24c2071fcaa8065d450dae78a80a671697f0e873.tar.bz2 gosten-24c2071fcaa8065d450dae78a80a671697f0e873.zip |
Restructure: Move auth and session to their own files
Make auth handling nicer.
Diffstat (limited to '')
-rw-r--r-- | session.go | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/session.go b/session.go new file mode 100644 index 0000000..f495cdd --- /dev/null +++ b/session.go @@ -0,0 +1,70 @@ +package main + +import ( + "context" + "encoding/gob" + "log" + "net/http" + + "github.com/gorilla/securecookie" + "github.com/gorilla/sessions" +) + +const ( + sessionCookie = "sessionKeks" + sessionContextKey = "_session" + dataKey = "data" +) + +var sessionStore sessions.Store + +func init() { + gob.Register(SessionData{}) + sessionStore = sessions.NewCookieStore(securecookie.GenerateRandomKey(32)) +} + +type Session struct { + *SessionData + s *sessions.Session +} + +type SessionData struct { + UserID int64 + Authenticated bool +} + +func (s *Session) Save(w http.ResponseWriter, r *http.Request) { + s.s.Values[dataKey] = *s.SessionData + if err := s.s.Save(r, w); err != nil { + log.Panic("Storing session: ", err) + } +} + +func (s *Session) MaxAge(maxAge int) { + s.s.Options.MaxAge = maxAge +} + +func (s *Session) Invalidate() { + s.MaxAge(-1) + s.Authenticated = false +} + +func session(r *http.Request) Session { + s := r.Context().Value(sessionContextKey).(*sessions.Session) + s.Options.HttpOnly = true + + sd, ok := s.Values[dataKey].(SessionData) + if !ok { + sd = SessionData{} + } + return Session{&sd, s} +} + +func sessionHandler(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + session, _ := sessionStore.Get(r, sessionCookie) + + ctx := context.WithValue(r.Context(), sessionContextKey, session) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} |