當前位置: 首頁>>代碼示例>>Golang>>正文


Golang sessions.Session類代碼示例

本文整理匯總了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]
}
開發者ID:cleesmith,項目名稱:gowebapp,代碼行數:28,代碼來源:token.go

示例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
}
開發者ID:guilherme-santos,項目名稱:mongostore,代碼行數:34,代碼來源:mongostore.go

示例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)
}
開發者ID:nguyenducnhaty,項目名稱:hero,代碼行數:30,代碼來源:session_store.go

示例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
}
開發者ID:miquella,項目名稱:rethinkdb_session_store,代碼行數:34,代碼來源:store.go

示例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)
	}
}
開發者ID:vonwenm,項目名稱:csrfbanana,代碼行數:8,代碼來源:token.go

示例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
}
開發者ID:WimLotz,項目名稱:induco,代碼行數:25,代碼來源:googleAuth.go

示例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")
	}
}
開發者ID:michielbdejong,項目名稱:FindMyDevice,代碼行數:29,代碼來源:handlers_test.go

示例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
}
開發者ID:michielbdejong,項目名稱:FindMyDevice,代碼行數:28,代碼來源:handlers_test.go

示例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
}
開發者ID:TheOnly92,項目名稱:morioka,代碼行數:28,代碼來源:sessionredishandler.go

示例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
}
開發者ID:EricLagergren,項目名稱:pnwconference,代碼行數:26,代碼來源:auth.go

示例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
}
開發者ID:avdienko,項目名稱:gorilla-sessions-memcache,代碼行數:9,代碼來源:gsmstub.go

示例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...)
}
開發者ID:jwulf,項目名稱:zedlist,代碼行數:9,代碼來源:store.go

示例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...)
}
開發者ID:nguyenducnhaty,項目名稱:hero,代碼行數:9,代碼來源:session_store.go

示例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)
}
開發者ID:nguyenducnhaty,項目名稱:hero,代碼行數:9,代碼來源:session_store.go

示例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
}
開發者ID:patrickjr,項目名稱:poker2,代碼行數:9,代碼來源:users.go


注:本文中的github.com/gorilla/sessions.Session類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。