session

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	FeatureId = security.FeatureId("Session", security.FeatureOrderSession)
)
View Source
var Module = &bootstrap.Module{
	Name:       "session",
	Precedence: security.MinSecurityPrecedence + 10,
	Options: []fx.Option{
		fx.Provide(security.BindSessionProperties),
		fx.Provide(provideSessionStore),
		fx.Invoke(register),
	},
}

Functions

func Deserialize

func Deserialize(src io.Reader, dst interface{}) error

func GobRegister

func GobRegister()

func MustSet

func MustSet(c context.Context, s *Session)

MustSet is the panicking version of Set

func NewCookie

func NewCookie(name, value string, options *Options, r *http.Request) *http.Cookie

NewCookie returns an http.Cookie with the options set. It also sets the Expires field calculated based on the MaxAge value, for Internet Explorer compatibility.

func Serialize

func Serialize(src interface{}) ([]byte, error)

func Set

func Set(c context.Context, s *Session) error

Set given Session into given context. The function returns error if the given context is not backed by utils.MutableContext.

Types

type ChangeSessionHandler

type ChangeSessionHandler struct{}

ChangeSessionHandler *

This is a high priority handler because it writes to the header.
Therefore, it must be before any other success handler that may write the response status (e.g. redirect handler)

func (*ChangeSessionHandler) HandleAuthenticationSuccess

func (h *ChangeSessionHandler) HandleAuthenticationSuccess(c context.Context, r *http.Request, rw http.ResponseWriter, from, to security.Authentication)

func (*ChangeSessionHandler) PriorityOrder

func (h *ChangeSessionHandler) PriorityOrder() int

type ConcurrentSessionHandler

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

ConcurrentSessionHandler This handler runs after ChangeSessionHandler so that the updated session id is indexed to the principal

func (*ConcurrentSessionHandler) HandleAuthenticationSuccess

func (h *ConcurrentSessionHandler) HandleAuthenticationSuccess(c context.Context, _ *http.Request, _ http.ResponseWriter, from, to security.Authentication)

func (*ConcurrentSessionHandler) PriorityOrder

func (h *ConcurrentSessionHandler) PriorityOrder() int

type Configurer

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

func (*Configurer) Apply

func (sc *Configurer) Apply(feature security.Feature, ws security.WebSecurity) error

type DebugAuthErrorHandler

type DebugAuthErrorHandler struct{}

func (*DebugAuthErrorHandler) HandleAuthenticationError

func (h *DebugAuthErrorHandler) HandleAuthenticationError(_ context.Context, _ *http.Request, _ http.ResponseWriter, err error)

type DebugAuthSuccessHandler

type DebugAuthSuccessHandler struct{}

func (*DebugAuthSuccessHandler) HandleAuthenticationSuccess

func (h *DebugAuthSuccessHandler) HandleAuthenticationSuccess(
	_ context.Context, _ *http.Request, _ http.ResponseWriter, from, to security.Authentication)

type DefaultSettingService

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

func (*DefaultSettingService) GetMaximumSessions

func (d *DefaultSettingService) GetMaximumSessions(ctx context.Context) int

type DeleteSessionOnLogoutHandler

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

func (*DeleteSessionOnLogoutHandler) HandleAuthenticationSuccess

func (h *DeleteSessionOnLogoutHandler) HandleAuthenticationSuccess(c context.Context, _ *http.Request, _ http.ResponseWriter, from, to security.Authentication)

type Feature

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

Feature holds session configuration

func Configure

func Configure(ws security.WebSecurity) *Feature

Configure Standard security.Feature entrypoint

func New

func New() *Feature

New Standard security.Feature entrypoint, DSL style. Used with security.WebSecurity

func (*Feature) Identifier

func (f *Feature) Identifier() security.FeatureIdentifier

func (*Feature) SessionName

func (f *Feature) SessionName(sessionName string) *Feature

func (*Feature) SettingService

func (f *Feature) SettingService(settingService SettingService) *Feature

type Manager

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

func NewManager

func NewManager(sessionName string, store Store) *Manager

func (*Manager) AuthenticationPersistenceHandlerFunc

func (m *Manager) AuthenticationPersistenceHandlerFunc() gin.HandlerFunc

AuthenticationPersistenceHandlerFunc provide middleware to load security from session and save it at end

func (*Manager) SessionHandlerFunc

func (m *Manager) SessionHandlerFunc() gin.HandlerFunc

SessionHandlerFunc provide middleware for basic session management

type Options

type Options struct {
	Path   string
	Domain string

	// Determines how the cookie's "Max-Age" attribute will be set
	// MaxAge=0 means no 'Max-Age' attribute specified.
	// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
	// MaxAge>0 means Max-Age attribute present and given in seconds
	MaxAge   int
	Secure   bool
	HttpOnly bool
	// Defaults to http.SameSiteDefaultMode
	SameSite http.SameSite

	IdleTimeout     time.Duration
	AbsoluteTimeout time.Duration
}

type RedisStore

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

RedisStore *

	Session is implemented as a HSET in redis.
	Session is expired using Redis TTL. The TTL is slightly longer than the expiration time so that when the session is
	expired, we can still get the session details (if necessary).

	Currently we don't have a need for "on session expired" event. If we do have a need for this in the future,
	we can use https://redis.io/topics/notifications and listen on the TTL event. Once caveat of using the redis
	notification is that it may not generate a event until the key is being accessed. So if we want to have deterministic
	behaviour on when the event is fired, we would need to implement a scheduler ourselves that access these keys that
	are expired which will force redis to generate the event.

	For each session:
	1. HSET with key in the form of "LANAI:SESSION:SESSION:{sessionId}"
	This stores session.values, session.options and session.lastAccessedTime as separate fields in the hash set

	2. SET with key in the form of "LANAI:SESSION:INDEX:SESSION:{principal}"
	This stores the set of session Id for this user. The session Id stored in this set may have been expired or deleted.

	if we don't clean up the keys in this set, then that means on each successful login, we need to go through the
	content of this set and find the corresponding session - sscan for the set entries, and then hgetall for each entry.
	and filter the expired entries.

	if we want to clean up the keys in this set, we need to do so with scheduled tasks. We cannot depend on the redis expiring
	event, because when we get the event, the session is not available anymore. Therefore we need to introduce other data structures
	to keep track of the expiration separately.

	The worst case scenario if we don't clean up this set
	is when a user opens multiple session without logging out - this will result in these sessions remain in the set even
	when they expires. This will result in a penalty when the user logs on the next time.
	But if we don't expect a user to have millions of concurrent sessions, this should be insignificant.
	If concurrent user limit is set, we don't expect the number of entries to be more than the concurrent user limit
    which should be reasonably small.

	If concurrent user limit is not set, it can grow large, but that is not a problem due to expiration - i.e. the
	set can grow unbounded before any expiration event occurs. And the remedy to that is to apply a concurrent user limit.

	The application can use redis SCAN family of commands to make sure that redis is not blocked by a single user's request.

func NewRedisStore

func NewRedisStore(redisClient redis.Client, options ...StoreOptions) *RedisStore

func (*RedisStore) AddToPrincipalIndex

func (s *RedisStore) AddToPrincipalIndex(principal string, session *Session) error

func (*RedisStore) ChangeId

func (s *RedisStore) ChangeId(session *Session) error

func (*RedisStore) FindByPrincipalName

func (s *RedisStore) FindByPrincipalName(principal string, sessionName string) ([]*Session, error)

func (*RedisStore) Get

func (s *RedisStore) Get(id string, name string) (*Session, error)

func (*RedisStore) Invalidate

func (s *RedisStore) Invalidate(sessions ...*Session) error

func (*RedisStore) InvalidateByPrincipalName

func (s *RedisStore) InvalidateByPrincipalName(principal, sessionName string) error

func (*RedisStore) New

func (s *RedisStore) New(name string) (*Session, error)

New will create a new session.

func (*RedisStore) Options

func (s *RedisStore) Options() *Options

func (*RedisStore) RemoveFromPrincipalIndex

func (s *RedisStore) RemoveFromPrincipalIndex(principal string, session *Session) error

func (*RedisStore) Save

func (s *RedisStore) Save(session *Session) error

Save adds a single session to the persistence layer

func (*RedisStore) WithContext

func (s *RedisStore) WithContext(ctx context.Context) Store

type Session

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

func CreateSession

func CreateSession(store Store, name string) *Session

func Get

func Get(c context.Context) *Session

Get returns Session stored in given context. May return nil

func NewSession

func NewSession(store Store, name string) *Session

func (*Session) AddFlash

func (s *Session) AddFlash(value interface{}, flashKey ...string)

AddFlash adds a flash message to the session.

A single variadic argument is accepted, and it is optional: it defines the flash key. If not defined "_flash" is used by default.

func (*Session) ChangeId

func (s *Session) ChangeId() error

func (*Session) Clear

func (s *Session) Clear()

Clear deletes all values in the session.

func (*Session) Delete

func (s *Session) Delete(key interface{})

Delete removes the session value associated to the given key.

func (*Session) ExpireNow

func (s *Session) ExpireNow(ctx context.Context) error

func (*Session) Flash

func (s *Session) Flash(key string) (ret interface{})

Flash get the last flash message of given key. It internally uses Flashes

func (*Session) Flashes

func (s *Session) Flashes(flashKey ...string) []interface{}

Flashes returns a slice of flash messages from the session.

A single variadic argument is accepted, and it is optional: it defines the flash key. If not defined "_flash" is used by default.

func (*Session) Get

func (s *Session) Get(key interface{}) interface{}

Get returns the session value associated to the given key.

func (*Session) GetID

func (s *Session) GetID() string

GetID returns the name used to register the session.

func (*Session) IsDirty

func (s *Session) IsDirty() bool

func (*Session) Name

func (s *Session) Name() string

Name returns the name used to register the session.

func (*Session) Save

func (s *Session) Save() (err error)

Save is a convenience method to save this session. It is the same as calling store.Save(request, response, session).

func (*Session) Set

func (s *Session) Set(key interface{}, val interface{})

Set sets the session value associated to the given key.

func (*Session) SetDirty

func (s *Session) SetDirty()

type SettingService

type SettingService interface {
	GetMaximumSessions(ctx context.Context) int
}

func NewDefaultSettingService

func NewDefaultSettingService(p security.SessionProperties) SettingService

type Store

type Store interface {
	// Get should return a cached session.
	Get(id string, name string) (*Session, error)

	// New should create and return a new session.
	New(name string) (*Session, error)

	// Save should persist session to the underlying store implementation.
	Save(s *Session) error

	// Invalidate sessions from store.
	// It will also remove associations between sessions and its stored principal via RemoveFromPrincipalIndex
	Invalidate(sessions ...*Session) error

	Options() *Options

	ChangeId(s *Session) error

	AddToPrincipalIndex(principal string, session *Session) error

	RemoveFromPrincipalIndex(principal string, sessions *Session) error

	FindByPrincipalName(principal string, sessionName string) ([]*Session, error)

	// InvalidateByPrincipalName invalidate all sessions associated with given principal name
	InvalidateByPrincipalName(principal, sessionName string) error

	// WithContext make a shallow copy of the store with given ctx
	WithContext(ctx context.Context) Store
}

type StoreOption

type StoreOption struct {
	Options
	SettingReader security.GlobalSettingReader
}

type StoreOptions

type StoreOptions func(opt *StoreOption)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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