scs_gin_adapter

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2025 License: MIT Imports: 3 Imported by: 3

README

Gin SCS Adapter

The Gin SCS Adapter allows you to seamlessly use the SCS session manager within a Gin web framework. It provides a simple way to manage session states while adhering to best practices for handling session cookies and data.

Installation

To use this package, import it in your Go application:

go get github.com/39george/scs_gin_adapter

Getting Started

You can create a new session manager and set up the Gin adapter as follows:

import(
  	"github.com/alexedwards/scs/v2"
   	"github.com/gin-gonic/gin"
    gin_adapter "github.com/39george/scs_gin_adapter"
)

func main() {
    sessionManager := scs.New()
    sessionManager.Lifetime = 24 * time.Hour // Set the session lifetime
    sessionAdapter := gin_adapter.New(sessionManager)

    r := gin.Default()
    r.Use(sessionAdapter.LoadAndSave) // Load session for each request

    r.GET("/put", func(c *gin.Context) {
        sessionAdapter.Put(c, "foo", "bar") // Store a value in the session
        c.JSON(http.StatusOK, gin.H{"foo": "bar"}) // Respond with the stored value
    })

    // Start the server
    r.Run()
}

Important Details

Session Handling in Gin

Due to the way Gin handles response writing, it is not possible to use the SCS session manager's LoadAndSave middleware directly without encountering issues. Once the response body or headers are written in a Gin handler, attempting to modify the headers will result in an error stating that headers have already been written.

The Gin SCS Adapter serves as a wrapper around essential SCS functions. It ensures that the session is committed and response headers are written at the appropriate time, within the request handler, rather than within the middleware. This approach avoids conflicts with Gin's response writing mechanism.

The LoadAndSave middleware is responsible solely for loading the session data and injecting the relevant session context into the Gin context. It does not perform any additional actions.

Session Methods

The Gin adapter provides methods that correspond to operations that can be performed with sessions:

  • Put: Adds a key-value pair to the session data. Existing values for the key will be replaced, and the session status will be marked as modified.
  • Get: Retrieves the value associated with a given key from the session data. The retrieved value will need to be type asserted as it returns an interface{}.
  • Destroy: Deletes session data, marking the session as destroyed. Any subsequent operations within the same request cycle will create a new session.
  • RenewToken: Regenerates the session token while retaining existing session data. This is particularly important for mitigating session fixation attacks.
  • RememberMe: Configures whether the session cookie is persistent (retained across browser sessions).

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type GinAdapter

type GinAdapter struct {
	// contains filtered or unexported fields
}

GinAdapter represents the session adapter.

func New

func New(s *scs.SessionManager) *GinAdapter

New returns a new GinAdapter instance that embeds the original SCS session manager.

func (*GinAdapter) Destroy

func (ga *GinAdapter) Destroy(ctx *gin.Context) error

Destroy deletes the session data from the session store and sets the session status to Destroyed. Any further operations in the same request cycle will result in a new session being created.

func (*GinAdapter) Get

func (ga *GinAdapter) Get(ctx *gin.Context, key string) interface{}

Get returns the value for a given key from the session data. The return value has the type interface{} so will usually need to be type asserted before you can use it. For example:

foo, ok := session.Get(r, "foo").(string)
if !ok {
	return errors.New("type assertion to string failed")
}

Also see the GetString(), GetInt(), GetBytes() and other helper methods which wrap the type conversion for common types.

func (*GinAdapter) GetString

func (ga *GinAdapter) GetString(ctx *gin.Context, key string) string

GetString returns the string value for a given key from the session data. The zero value for a string ("") is returned if the key does not exist or the value could not be type asserted to a string.

func (*GinAdapter) LoadAndSave

func (ga *GinAdapter) LoadAndSave(ginCtx *gin.Context)

LoadAndSave provides a Gin middleware which automatically loads and saves session data for the current request, and communicates the session token to and from the client in a cookie.

func (*GinAdapter) Put

func (ga *GinAdapter) Put(ctx *gin.Context, key string, val interface{})

Put adds a key and corresponding value to the session data. Any existing value for the key will be replaced. The session data status will be set to Modified.

func (*GinAdapter) RememberMe

func (ga *GinAdapter) RememberMe(ctx *gin.Context, val bool)

RememberMe controls whether the session cookie is persistent (i.e whether it is retained after a user closes their browser). RememberMe only has an effect if you have set SessionManager.Cookie.Persist = false (the default is true) and you are using the standard LoadAndSave() middleware.

func (*GinAdapter) Remove added in v0.1.3

func (ga *GinAdapter) Remove(ctx *gin.Context, key string)

Remove deletes the given key and corresponding value from the session data. The session data status will be set to Modified. If the key is not present this operation is a no-op.

func (*GinAdapter) RenewToken

func (ga *GinAdapter) RenewToken(ctx *gin.Context) error

RenewToken updates the session data to have a new session token while retaining the current session data. The session lifetime is also reset and the session data status will be set to Modified.

The old session token and accompanying data are deleted from the session store.

To mitigate the risk of session fixation attacks, it's important that you call RenewToken before making any changes to privilege levels (e.g. login and logout operations). See https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#renew-the-session-id-after-any-privilege-level-change for additional information.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL