Nuestro burocrata preferido: Sam Lowry https://lowry.sindominio.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 
lowry/server/session.go

65 lines
1.4 KiB

package server
import (
"encoding/base64"
"math/rand"
"net/http"
"time"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
)
type session struct {
user string
}
type sessionStore struct {
cookies *sessions.CookieStore
sessions map[string]session
}
func initSessionStore() *sessionStore {
rand.Seed(time.Now().UnixNano())
cookies := sessions.NewCookieStore(securecookie.GenerateRandomKey(64))
return &sessionStore{cookies, map[string]session{}}
}
func (store *sessionStore) set(user string, w http.ResponseWriter, r *http.Request) {
sessionID := genID()
store.sessions[sessionID] = session{user}
cookie, _ := store.cookies.Get(r, "session")
cookie.Values["id"] = sessionID
cookie.Save(r, w)
}
func (store *sessionStore) get(w http.ResponseWriter, r *http.Request) *session {
cookie, _ := store.cookies.Get(r, "session")
sessionID, ok := cookie.Values["id"].(string)
if !ok {
return nil
}
session, ok := store.sessions[sessionID]
if !ok {
return nil
}
return &session
}
func (store *sessionStore) del(w http.ResponseWriter, r *http.Request) {
cookie, _ := store.cookies.Get(r, "session")
sessionID, ok := cookie.Values["id"].(string)
if !ok {
return
}
delete(cookie.Values, "id")
cookie.Save(r, w)
delete(store.sessions, sessionID)
}
func genID() string {
buff := make([]byte, 8)
rand.Read(buff)
return base64.StdEncoding.EncodeToString(buff)
}