2 changed files with 62 additions and 20 deletions
@ -1,26 +1,65 @@
|
||||
package server |
||||
|
||||
import ( |
||||
"encoding/base64" |
||||
"math/rand" |
||||
"net/http" |
||||
"time" |
||||
|
||||
"github.com/gorilla/securecookie" |
||||
"github.com/gorilla/sessions" |
||||
) |
||||
|
||||
var store = sessions.NewCookieStore(securecookie.GenerateRandomKey(64)) |
||||
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 setUser(user string, w http.ResponseWriter, r *http.Request) { |
||||
session, _ := store.Get(r, "session") |
||||
session.Values["user"] = user |
||||
session.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 getUser(w http.ResponseWriter, r *http.Request) string { |
||||
session, _ := store.Get(r, "session") |
||||
session.Save(r, w) |
||||
user, ok := session.Values["user"].(string) |
||||
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 "" |
||||
return |
||||
} |
||||
return user |
||||
|
||||
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) |
||||
} |
||||
|
Loading…
Reference in new issue