本文整理匯總了Golang中github.com/gorilla/sessions.Session.Save方法的典型用法代碼示例。如果您正苦於以下問題:Golang Session.Save方法的具體用法?Golang Session.Save怎麽用?Golang Session.Save使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/gorilla/sessions.Session
的用法示例。
在下文中一共展示了Session.Save方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: 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
}
示例2: 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)
}
}
示例3: 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]
}
示例4: 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
}
示例5: 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
}
示例6: 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)
}
}
示例7: 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)
}
示例8: removeCurrentUserFromSession
// Remove all current user information from the session object
func (c *CAS) removeCurrentUserFromSession(w http.ResponseWriter, req *http.Request, session *sessions.Session) *CASServerError {
// Delete current user from session
delete(session.Values, "currentUser")
// Save the modified session
err := session.Save(req, w)
if err != nil {
return &FailedToDeleteSessionError
}
return nil
}
示例9: TokenWithPath
// Token will return a token for the specified URL. SingleToken is ignored.
func TokenWithPath(w http.ResponseWriter, r *http.Request, sess *sessions.Session, urlPath string) string {
// Generate the map if it doesn't exist
if _, ok := sess.Values[TokenName]; !ok {
sess.Values[TokenName] = make(StringMap)
}
sessMap := sess.Values[TokenName].(StringMap)
if _, ok := sessMap[urlPath]; !ok {
sessMap[urlPath] = generate(TokenLength)
sess.Save(r, w)
}
return sessMap[urlPath]
}
示例10: loginHandler
func loginHandler(res http.ResponseWriter, r *http.Request, session *sessions.Session, ctx *pongo2.Context) (*string, error) {
var (
username = strings.ToLower(r.FormValue("username"))
password = fmt.Sprintf("%x", sha1.Sum([]byte(cfg.PasswordSalt+r.FormValue("password"))))
)
if !storage.IsPresent(createUserFilename(username)) {
(*ctx)["error"] = true
return stringPointer("login.html"), nil
}
userFileRaw, err := storage.Read(createUserFilename(username))
if err != nil {
fmt.Printf("ERR: Unable to read user file: %s\n", err)
(*ctx)["error"] = true
return stringPointer("login.html"), nil
}
userFile, _ := readDataObject(userFileRaw)
if userFile.MetaData.Password != password {
(*ctx)["error"] = true
return stringPointer("login.html"), nil
}
auth, ok := session.Values["authorizedAccounts"].(authorizedAccounts)
if !ok {
auth = authorizedAccounts{}
}
for i, v := range auth {
if v.Name == username {
http.Redirect(res, r, fmt.Sprintf("u/%d/overview", i), http.StatusFound)
return nil, nil
}
}
auth = append(auth, authorizedAccount{
Name: username,
UserFile: createUserFilename(username),
})
session.Values["authorizedAccounts"] = auth
if err := session.Save(r, res); err != nil {
return nil, err
}
http.Redirect(res, r, fmt.Sprintf("u/%d/overview", len(auth)-1), http.StatusFound)
return nil, nil
}
示例11: HomeHandler
func HomeHandler(w http.ResponseWriter, r *http.Request) {
var session *sessions.Session
s, err := store.Get(r, "session-name")
if err != nil {
log.Println("error fetching session:", err)
s, _ := store.New(r, "session-name")
session = s
} else {
session = s
}
state := randomString(64)
session.Values["state"] = state
session.Save(r, w)
if err := Views.Lookup("home.ghtml").Execute(w, struct{}{}); err != nil {
log.Printf("error executing view template: %v", err)
}
}
示例12: SaveSession
func (sc SessionController) SaveSession(w http.ResponseWriter, r *http.Request, s *sessions.Session) {
err := s.Save(r, w)
if err != nil {
log.Println("ERROR: SessionController: SaveSession: " + err.Error())
}
}
示例13: ExtendExpiration
//ExtendExpiration pushes out the expiration of the session cookie to a further time
//this is done to keep a user logged in automatically if they use the app frequently
func ExtendExpiration(session *sessions.Session, w http.ResponseWriter, r *http.Request) {
session.Options = options
session.Save(r, w)
return
}
示例14: Save
//Save saves any new session data to an existing session
//write the new values to it (after using AddValue)
func Save(session *sessions.Session, w http.ResponseWriter, r *http.Request) {
session.Save(r, w)
return
}
示例15: endSession
func endSession(s *sessions.Session, w http.ResponseWriter, r *http.Request) {
s.Options = &sessions.Options{MaxAge: -1}
s.Save(r, w)
}