Skip to content

Instantly share code, notes, and snippets.

@jfut
Last active October 17, 2024 07:52
Show Gist options
  • Save jfut/51022d66cb2aea8ffba7ea308ab9c912 to your computer and use it in GitHub Desktop.
Save jfut/51022d66cb2aea8ffba7ea308ab9c912 to your computer and use it in GitHub Desktop.
echo + gorilla/sessions: Session Management Utility Functions
// echo + gorilla/sessions: Session Management Utility Functions
//
// Copyright (c) 2024 Jun Futagawa (jfut)
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
package common
import (
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
)
const (
SESSION_KEY string = "SESSIONID"
SET_COOKIE string = "Set-Cookie"
)
// SaveSession saves the session while avoiding duplicate Set-Cookie headers.
func SaveSession(c echo.Context, session *sessions.Session) error {
c.Response().Header().Del(SET_COOKIE)
return session.Save(c.Request(), c.Response())
}
// RefreshSession refreshes the session by invalidating the existing one and generating a new session ID.
// It should be called after each login as a countermeasure against Session Fixation attacks.
func RefreshSession(c echo.Context) error {
session, err := invalidateSession(c)
if err != nil {
return err
}
return SaveSession(c, session)
}
// DestroySession invalidates the existing session and clears the session data.
// It should be used when a user logs out or when you want to completely reset the session.
func DestroySession(c echo.Context) error {
session, err := invalidateSession(c)
if err != nil {
return err
}
// Clear values for the new session, do not save to store
session.Values = make(map[interface{}]interface{})
return nil
}
// invalidateSession is an internal helper function that invalidates the current session.
func invalidateSession(c echo.Context) (*sessions.Session, error) {
session, err := session.Get(SESSION_KEY, c)
if err != nil {
return nil, err
}
oldMaxAge := session.Options.MaxAge
// Delete the value on the server-side store by saving the existing session with MaxAge = -1
session.Options.MaxAge = -1
if err := session.Save(c.Request(), c.Response()); err != nil {
return nil, err
}
// Remove the Set-Cookie header set for the existing session
c.Response().Header().Del(SET_COOKIE)
// Clear values for the new session
session.ID = ""
session.Options.MaxAge = oldMaxAge
return session, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment