本文整理匯總了Golang中github.com/gorilla/sessions.Session類的典型用法代碼示例。如果您正苦於以下問題:Golang Session類的具體用法?Golang Session怎麽用?Golang Session使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Session類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Token
// Token will return a token. If SingleToken = true, it will return the same token for every page.
func Token(w http.ResponseWriter, r *http.Request, sess *sessions.Session) string {
// Generate the map if it doesn't exist
if _, ok := sess.Values[TokenName]; !ok {
sess.Values[TokenName] = make(StringMap)
}
path := r.URL.Path
if SingleToken {
path = "/"
}
sessMap := sess.Values[TokenName].(StringMap)
if _, ok := sessMap[path]; !ok {
if len(sessMap) >= MaxTokens {
for i, _ := range sessMap {
delete(sessMap, i)
}
}
sessMap[path] = generate(TokenLength)
sess.Save(r, w)
}
return sessMap[path]
}
示例2: upsert
func (m *MongoStore) upsert(session *sessions.Session) error {
if !bson.IsObjectIdHex(session.ID) {
return ErrInvalidId
}
var modified time.Time
if val, ok := session.Values["modified"]; ok {
modified, ok = val.(time.Time)
if !ok {
return errors.New("mongostore: invalid modified value")
}
} else {
modified = time.Now()
}
encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
m.Codecs...)
if err != nil {
return err
}
s := Session{
Id: bson.ObjectIdHex(session.ID),
Data: encoded,
Modified: modified,
}
_, err = m.coll.UpsertId(s.Id, &s)
if err != nil {
return err
}
return nil
}
示例3: save
func (s *Store) save(session *sessions.Session) error {
encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
s.codecs...)
if err != nil {
return err
}
var expiresOn time.Time
exOn := session.Values["expires_on"]
if exOn == nil {
expiresOn = time.Now().Add(time.Second * time.Duration(session.Options.MaxAge))
} else {
expiresOn = exOn.(time.Time)
if expiresOn.Sub(time.Now().Add(time.Second*time.Duration(session.Options.MaxAge))) < 0 {
expiresOn = time.Now().Add(time.Second * time.Duration(session.Options.MaxAge))
}
}
ss := &Session{
Key: session.ID,
Data: encoded,
ExpiresOn: expiresOn,
}
if session.IsNew {
return s.q.SaveSession(ss)
}
return s.q.UpdateSession(ss)
}
示例4: save
func (s *RethinkDBStore) save(session *sessions.Session) error {
values := map[string]interface{}{}
for k, v := range session.Values {
kstr, ok := k.(string)
if !ok {
return errors.New("cannot serialize non-string value key")
}
values[kstr] = v
}
json := map[string]interface{}{
"name": session.Name(),
"values": values,
}
var write gorethink.WriteResponse
var err error
if session.ID != "" {
write, err = s.term.Get(session.ID).Update(json).RunWrite(s.rethinkdbSession)
if err == nil && write.Updated == 0 {
json["id"] = session.ID
}
}
if write.Updated == 0 {
write, err = s.term.Insert(json).RunWrite(s.rethinkdbSession)
if err == nil && len(write.GeneratedKeys) > 0 {
session.ID = write.GeneratedKeys[0]
}
}
return err
}
示例5: Clear
// Clear will remove all the tokens. Call after a permission change.
func Clear(w http.ResponseWriter, r *http.Request, sess *sessions.Session) {
// Delete the map if it doesn't exist
if _, ok := sess.Values[TokenName]; ok {
delete(sess.Values, TokenName)
sess.Save(r, w)
}
}
示例6: googleDisconnect
func googleDisconnect(w http.ResponseWriter, r *http.Request, session *sessions.Session) *appError {
token := session.Values["accessToken"]
if token == nil {
m := "Current user not connected"
return &appError{errors.New(m), m, 401}
}
// Execute HTTP GET request to revoke current token
url := "https://accounts.google.com/o/oauth2/revoke?token=" + token.(string)
resp, err := http.Get(url)
if err != nil {
m := "Failed to revoke token for a given user"
return &appError{errors.New(m), m, 400}
}
defer resp.Body.Close()
// Reset the user's session
session.Values["accessToken"] = nil
session.Values["userId"] = nil
session.Values["gplusID"] = nil
session.Save(r, w)
return nil
}
示例7: Test_Handler_clearSession
func Test_Handler_clearSession(t *testing.T) {
var ok bool
config := util.NewMzConfig()
h, _ := testHandler(config, t)
sess := new(sessions.Session)
sess.Values = make(map[interface{}]interface{})
sess.Values[SESSION_USERID] = true
sess.Values[SESSION_DEVICEID] = true
sess.Values[SESSION_EMAIL] = true
sess.Values[SESSION_TOKEN] = true
sess.Values[SESSION_CSRFTOKEN] = true
h.clearSession(sess)
if _, ok = sess.Values[SESSION_USERID]; ok {
t.Errorf("Userid not cleared")
}
if _, ok = sess.Values[SESSION_DEVICEID]; ok {
t.Errorf("Deviceid not cleared")
}
if _, ok = sess.Values[SESSION_EMAIL]; ok {
t.Errorf("Email not cleared")
}
if _, ok = sess.Values[SESSION_TOKEN]; ok {
t.Errorf("Token not cleared")
}
if _, ok = sess.Values[SESSION_CSRFTOKEN]; ok {
t.Errorf("CSRFToken not cleared")
}
}
示例8: fakeCookies
func fakeCookies(req *http.Request, email, userid, token, csrftoken string) error {
var err error
var session *sessions.Session
resp := httptest.NewRecorder()
session, err = sessionStore.Get(req, SESSION_NAME)
if len(email) > 0 {
session.Values[SESSION_EMAIL] = email
}
if len(userid) > 0 {
session.Values[SESSION_USERID] = userid
}
if len(token) > 0 {
session.Values[SESSION_TOKEN] = token
}
if len(csrftoken) > 0 {
session.Values[SESSION_CSRFTOKEN] = csrftoken
}
if err = session.Save(req, resp); err != nil {
return fmt.Errorf("Could not set cookie! %s", err.Error())
}
fcookies, ok := resp.HeaderMap["Set-Cookie"]
if !ok {
return fmt.Errorf("Cookie not set in header")
}
req.Header.Add("Cookie", strings.Split(fcookies[0], ";")[0])
return nil
}
示例9: save
func (s *RedisStore) save(session *sessions.Session) error {
encoded, err := securecookie.EncodeMulti(session.Name(), session.Values, s.Codecs...)
if err != nil {
return err
}
c := s.storeHandler.GetRedisConnection()
defer c.Close()
if session.ID == "" {
// Because the ID is used in the filename, encode it to
// use alphanumeric characters only.
session.ID = strings.TrimRight(base32.StdEncoding.EncodeToString(securecookie.GenerateRandomKey(32)), "=")
}
c.Send("SET", "morioka_sess_"+session.ID, encoded)
if err = c.Flush(); err != nil {
return err
}
if _, err = c.Receive(); err != nil {
return err
}
c.Send("EXPIRE", "morioka_sess_"+session.ID, 86400)
if err = c.Flush(); err != nil {
return err
}
if _, err = c.Receive(); err != nil {
return err
}
return nil
}
示例10: createSession
func createSession(w http.ResponseWriter, r *http.Request, session *sessions.Session) *ServerSession {
// Each session needs a unique ID in order to be saved.
if session.ID == "" {
session.ID = tokens.NewSessionID()
}
ss := &ServerSession{
CSRFToken: tokens.NewCSRFToken(session.ID),
}
// Attempt to store the session. Remove the session if it's not stored
// correctly.
if err := ss.StoreSession(session.ID); err != nil {
RemoveSession(session.ID)
glog.Fatalln(err)
}
// Similarly, save it in our FS storage and set the user's cookie.
if err := session.Save(r, w); err != nil {
RemoveSession(session.ID)
glog.Fatalln(err)
}
return ss
}
示例11: load
// load reads a file and decodes its content into session.Values.
func (s *DumbMemoryStore) load(session *sessions.Session) error {
if err := securecookie.DecodeMulti(session.Name(), string(s.Data[session.ID]),
&session.Values, s.Codecs...); err != nil {
return err
}
return nil
}
示例12: load
//load fetches a session by ID from the database and decodes its content into session.Values
func (db *PGStore) load(session *sessions.Session) error {
s, err := query.GetSessionByKey(session.ID)
if err != nil {
return err
}
return securecookie.DecodeMulti(session.Name(), string(s.Data),
&session.Values, db.Codecs...)
}
示例13: load
//load fetches a session by ID from the database and decodes its content into session.Values
func (s *Store) load(session *sessions.Session) error {
ss, err := s.q.GetSessionByKey(session.ID)
if err != nil {
return err
}
return securecookie.DecodeMulti(session.Name(), string(ss.Data),
&session.Values, s.codecs...)
}
示例14: destroy
func (s *Store) destroy(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
options := *s.options
options.MaxAge = -1
http.SetCookie(w, sessions.NewCookie(session.Name(), "", &options))
for k := range session.Values {
delete(session.Values, k)
}
return s.q.DeleteSession(session.ID)
}
示例15: saveCookie
func saveCookie(w http.ResponseWriter, s *sessions.Session, store *sessions.CookieStore) (string, error) {
encoded, err := securecookie.EncodeMulti(s.Name(), s.Values, store.Codecs...)
if err != nil {
return "", err
}
cookie := sessions.NewCookie(s.Name(), encoded, s.Options)
http.SetCookie(w, cookie)
return cookie.Value, nil
}