• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang sessions.Session类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/gorilla/sessions.Session的典型用法代码示例。如果您正苦于以下问题:Golang Session类的具体用法?Golang Session怎么用?Golang Session使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Session类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: ValidateAuth

// ValidateAuth validates that the user cookie is set up before calling the
// handler passed as parameter.
func ValidateAuth(h httputils.ContextHandler) httputils.ContextHandler {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		var (
			sessionData *httputils.SessionData
			err         error
			ok          bool
			cookieStore *sessions.CookieStore
			session     *sessions.Session
			cfg         = ctx.Value("config").(*config.Config)
		)

		cookieStore, ok = ctx.Value("cookieStore").(*sessions.CookieStore)

		if !ok {
			httputils.WriteError(w, http.StatusInternalServerError, "")
			return fmt.Errorf("validate auth: could not cast value as cookie store: %s", ctx.Value("cookieStore"))
		}

		session, err = cookieStore.Get(r, cfg.SessionCookieName)

		if err != nil {
			log.Println(err)
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return nil
		}

		sessionData, ok = session.Values["data"].(*httputils.SessionData)

		if !ok || sessionData.IsInvalid() {
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return nil
		} else if time.Now().After(sessionData.ExpiresAt) {
			session.Options.MaxAge = -1
			session.Save(r, w)
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)

			return nil
		}

		// Extend the session's lifetime.
		cfg, ok = ctx.Value("config").(*config.Config)

		if !ok {
			httputils.WriteError(w, http.StatusInternalServerError, "")
			return fmt.Errorf("validate auth: error casting config object: %s", ctx.Value("config"))
		}

		// Save session only if the session was extended.
		if extendSessionLifetime(sessionData, cfg.SessionLifeTime) {
			sessionData.ExpiresAt = time.Now().Add(cfg.SessionLifeTime)
			session.Save(r, w)
		}

		authenticatedContext := context.WithValue(ctx, "sessionData", sessionData)
		return h(authenticatedContext, w, r)
	}
}
开发者ID:ab22,项目名称:abcd,代码行数:59,代码来源:middleware.go


示例17: save

// save writes encoded session.Values using the memcache client
func (s *DumbMemoryStore) save(session *sessions.Session) error {
	encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
		s.Codecs...)
	if err != nil {
		return err
	}

	s.Data[session.ID] = encoded

	return nil
}
开发者ID:avdienko,项目名称:gorilla-sessions-memcache,代码行数:12,代码来源:gsmstub.go


示例18: Save

func (s *RethinkDBStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
	if err := s.save(session); err != nil {
		return err
	}
	encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, s.Codecs...)
	if err != nil {
		return err
	}
	http.SetCookie(w, sessions.NewCookie(session.Name(), encoded, session.Options))
	return nil
}
开发者ID:miquella,项目名称:rethinkdb_session_store,代码行数:11,代码来源:store.go


示例19: saveUserToSessionAndSendHome

func saveUserToSessionAndSendHome(w http.ResponseWriter, r *http.Request,
	session *sessions.Session, userName string, id int) {

	session.Values["UserName"] = userName
	session.Values["Id"] = id
	err := session.Save(r, w)
	if err != nil {
		log.Fatal(err)
	}
	http.Redirect(w, r, "/", http.StatusFound)
}
开发者ID:zhuxiaoliang,项目名称:tanks-app,代码行数:11,代码来源:handlers.go


示例20: save

// save writes encoded session.Values to a database record.
// writes to http_sessions table by default.
func (db *DatabaseStore) save(session *sessions.Session) error {
	encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
		db.Codecs...)

	if err != nil {
		return err
	}

	fn := func(dbConn *sql.DB) error {
		// Write record to sessions table.
		var sessionCount int = -1

		// Session exists?
		row := dbConn.QueryRow("SELECT COUNT(key) AS count FROM \""+SESSIONS_TABLE+"\" WHERE key = $1", session.ID)

		err := row.Scan(&sessionCount)
		if err != nil {
			return err
		}

		tx, err := dbConn.Begin()
		if err != nil {
			return err
		}

		if sessionCount > 0 {
			// update
			_, err = tx.Exec("UPDATE \""+SESSIONS_TABLE+"\" SET data = $1 WHERE key = $2",
				encoded, session.ID)
			if err != nil {
				return err
			}
		} else if sessionCount == 0 {
			// insert
			_, err = tx.Exec("INSERT INTO \""+SESSIONS_TABLE+"\" (key, data) VALUES($1,$2)",
				session.ID, encoded)
			if err != nil {
				return err
			}
		} else {
			// error
			err = errors.New("There was an error while trying to lookup a previous session.")
			return err
		}

		if err = tx.Commit(); err != nil {
			return err
		}

		return nil
	}

	return dbLib.ExecuteFn(fn)
}
开发者ID:frazy,项目名称:babou,代码行数:56,代码来源:dbstore.go



注:本文中的github.com/gorilla/sessions.Session类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang sessions.Store类代码示例发布时间:2022-05-23
下一篇:
Golang sessions.CookieStore类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap