summaryrefslogtreecommitdiff
path: root/session
diff options
context:
space:
mode:
authorRené 'Necoro' Neumann <necoro@necoro.eu>2024-10-17 00:27:08 +0200
committerRené 'Necoro' Neumann <necoro@necoro.eu>2024-10-17 00:27:08 +0200
commit869fb9691f877116d5b15a92de006d0daf4d70e5 (patch)
tree2493c72172d5817ec9deec36229a84b687eb3190 /session
parent6fc180ba6d9bc5c32340466988d9e26f8d6e3c5c (diff)
downloadgosten-869fb9691f877116d5b15a92de006d0daf4d70e5.tar.gz
gosten-869fb9691f877116d5b15a92de006d0daf4d70e5.tar.bz2
gosten-869fb9691f877116d5b15a92de006d0daf4d70e5.zip
Restructure and change to chi as muxing framework
Diffstat (limited to '')
-rw-r--r--session/session.go (renamed from session.go)36
1 files changed, 22 insertions, 14 deletions
diff --git a/session.go b/session/session.go
index 680f648..5ffd5cd 100644
--- a/session.go
+++ b/session/session.go
@@ -1,4 +1,4 @@
-package main
+package session
import (
"context"
@@ -19,21 +19,21 @@ const (
)
func init() {
- gob.Register(SessionData{})
+ gob.Register(sessionData{})
}
type Session struct {
- *SessionData
+ *sessionData
s *sessions.Session
}
-type SessionData struct {
+type sessionData struct {
UserID int32
Authenticated bool
}
func (s *Session) Save(w http.ResponseWriter, r *http.Request) {
- s.s.Values[dataKey] = *s.SessionData
+ s.s.Values[dataKey] = *s.sessionData
if err := s.s.Save(r, w); err != nil {
log.Panic("Storing session: ", err)
}
@@ -48,18 +48,23 @@ func (s *Session) Invalidate() {
s.Authenticated = false
}
-func session(r *http.Request) Session {
+func (s *Session) IsNew() bool {
+ return s.s.IsNew
+}
+
+// From extracts the `Session` from the `Request`.
+func From(r *http.Request) Session {
s := r.Context().Value(sessionContextKey{}).(*sessions.Session)
s.Options.HttpOnly = true
- sd, ok := s.Values[dataKey].(SessionData)
+ sd, ok := s.Values[dataKey].(sessionData)
if !ok {
- sd = SessionData{}
+ sd = sessionData{}
}
return Session{&sd, s}
}
-func sessionHandler(next http.Handler) http.Handler {
+func Handler() func(next http.Handler) http.Handler {
var key []byte
if envKey := os.Getenv("GOSTEN_SECRET"); len(envKey) >= 32 {
@@ -70,10 +75,13 @@ func sessionHandler(next http.Handler) http.Handler {
sessionStore := sessions.NewCookieStore(key)
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- session, _ := sessionStore.Get(r, sessionCookie)
+ return func(next http.Handler) http.Handler {
+ fn := 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))
- })
+ ctx := context.WithValue(r.Context(), sessionContextKey{}, session)
+ next.ServeHTTP(w, r.WithContext(ctx))
+ }
+ return http.HandlerFunc(fn)
+ }
}