sessionup: github.com/swithek/sessionup Index | Files | Directories

package sessionup

import "github.com/swithek/sessionup"

Index

Package Files

manager.go session.go store.go

Variables

var (
    // ErrUnauthorized is returned when no valid session is found.
    ErrUnauthorized = errors.New("unauthorized")

    // ErrNotOwner is returned when session's status is being modified
    // not by its owner.
    ErrNotOwner = errors.New("session can be managed only by its owner")
)
var (
    // ErrDuplicateID should be returned by Store implementations upon
    // ID collision.
    ErrDuplicateID = errors.New("duplicate ID")
)

func CookieName Uses

func CookieName(n string) setter

CookieName sets the name of the cookie. Defaults to the value stored in defaultName.

func DefaultGenID Uses

func DefaultGenID() string

DefaultGenID is the default ID generation function called during session creation.

func DefaultReject Uses

func DefaultReject(err error) http.Handler

DefaultReject is the default rejection function called on error. It produces a response consisting of 401 status code and a JSON body with 'error' field.

func Domain Uses

func Domain(d string) setter

Domain sets the 'Domain' attribute on the session cookie. Defaults to empty string. More at: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Scope_of_cookies

func ExpiresIn Uses

func ExpiresIn(e time.Duration) setter

ExpiresIn sets the duration which will be used to calculate the value of 'Expires' attribute on the session cookie. If unset, 'Expires' attribute will be omitted during cookie creation. By default it is not set. More about Expires at: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Session_cookies

func GenID Uses

func GenID(g func() string) setter

GenID sets the function which will be called when a new session is created and ID is being generated. Defaults to DefaultGenID function.

func HttpOnly Uses

func HttpOnly(h bool) setter

HttpOnly sets the 'HttpOnly' attribute on the session cookie. Defaults to true. More at: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies

func NewContext Uses

func NewContext(ctx context.Context, s Session) context.Context

NewContext creates a new context with the provided Session set as a context value.

func Path Uses

func Path(p string) setter

Path sets the 'Path' attribute on the session cookie. Defaults to "/". More at: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Scope_of_cookies

func Reject Uses

func Reject(r func(error) http.Handler) setter

Reject sets the function which will be called on error in Auth middleware. Defaults to DefaultReject function.

func SameSite Uses

func SameSite(s http.SameSite) setter

SameSite sets the 'SameSite' attribute on the session cookie. Defaults to http.SameSiteStrictMode. More at: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#SameSite_cookies

func Secure Uses

func Secure(s bool) setter

Secure sets the 'Secure' attribute on the session cookie. Defaults to true. More at: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies

func Validate Uses

func Validate(v bool) setter

Validate determines whether IP and User-Agent data should be checked on each request to authenticated routes or not.

func WithAgent Uses

func WithAgent(w bool) setter

WithAgent determines whether User-Agent data should be extracted from the request or not. Defaults to true.

func WithIP Uses

func WithIP(w bool) setter

WithIP determines whether IP should be extracted from the request or not. Defaults to true.

type Manager Uses

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

Manager holds the data needed to properly create sessions and set them in http responses, extract them from http requests, validate them and directly communicate with the store.

func NewManager Uses

func NewManager(s Store, opts ...setter) *Manager

NewManager creates a new Manager with the provided store and options applied to it.

func (*Manager) Auth Uses

func (m *Manager) Auth(next http.Handler) http.Handler

Auth wraps the provided handler, checks whether the session, associated to the ID stored in request's cookie, exists in the store or not and, if former is the case, adds it to the request's context. Wrapped handler will be activated only if there are no errors returned from the store, the session is found and its properties match the ones in the request (if validation is activated), otherwise, the manager's rejection function will be called.

func (*Manager) Clone Uses

func (m *Manager) Clone(opts ...setter) *Manager

Clone copies the manager to its fresh copy and applies provided options.

func (*Manager) Defaults Uses

func (m *Manager) Defaults()

Defaults sets all configuration options to reasonable defaults.

func (*Manager) FetchAll Uses

func (m *Manager) FetchAll(ctx context.Context) ([]Session, error)

FetchAll retrieves all sessions of the same user key as session stored in the context currently has. Session with the same ID as the one stored in the context will have its 'Current' field set to true. If no sessions are found or the context session is not set, both return values will be nil.

func (*Manager) Init Uses

func (m *Manager) Init(w http.ResponseWriter, r *http.Request, key string) error

Init creates a fresh session with the provided user key, inserts it in the store and sets the proper values of the cookie.

func (*Manager) Public Uses

func (m *Manager) Public(next http.Handler) http.Handler

Public wraps the provided handler, checks whether the session, associated to the ID stored in request's cookie, exists in the store or not and, if former is the case, adds it to the request's context. If no valid cookie is provided, session doesn't exist, the properties of the request don't match the ones associated to the session (if validation is activated) or the store returns an error, wrapped handler will be activated nonetheless. Rejection function will be called only for non-http side effects (like error logging), but response/request control will not be passed to it.

func (*Manager) Revoke Uses

func (m *Manager) Revoke(ctx context.Context, w http.ResponseWriter) error

Revoke deletes the current session, stored in the context, from the store and ensures cookie deletion. Function will be no-op and return nil, if context session is not set.

func (*Manager) RevokeAll Uses

func (m *Manager) RevokeAll(ctx context.Context, w http.ResponseWriter) error

RevokeAll deletes all sessions of the same user key as session stored in the context currently has. This includes context session as well. Function will be no-op and return nil, if context session is not set.

func (*Manager) RevokeByID Uses

func (m *Manager) RevokeByID(ctx context.Context, id string) error

RevokeByID deletes session by its ID. Function will be no-op and return nil, if no session is found.

func (*Manager) RevokeByIDExt Uses

func (m *Manager) RevokeByIDExt(ctx context.Context, id string) error

RevokeByIDExt deletes session by its ID after checking if it belongs to the same user as the one in the context. Function will be no-op and return nil, if no session is found.

func (*Manager) RevokeByUserKey Uses

func (m *Manager) RevokeByUserKey(ctx context.Context, key string) error

RevokeByUserKey deletes all sessions under the provided user key. This includes context session as well. Function will be no-op and return nil, if no sessions are found.

func (*Manager) RevokeOther Uses

func (m *Manager) RevokeOther(ctx context.Context) error

RevokeOther deletes all sessions of the same user key as session stored in the context currently has. Context session will be excluded. Function will be no-op and return nil, if context session is not set.

type Session Uses

type Session struct {
    // Current specifies whether this session's ID
    // matches the ID stored in the request's cookie or not.
    // NOTE: this field should be omitted by Store interface
    // implementations when inserting session into the underlying
    // data store.
    Current bool `json:"current"`

    // CreatedAt specifies a point in time when this session
    // was created.
    CreatedAt time.Time `json:"created_at"`

    // ExpiresAt specifies a point in time when this
    // session should become invalid and be deleted
    // from the store.
    ExpiresAt time.Time `json:"-"`

    // ID specifies a unique ID used to find this session
    // in the store.
    ID  string `json:"id"`

    // UserKey specifies a non-unique key used to find all
    // sessions of the same user.
    UserKey string `json:"-"`

    // IP specifies an IP address that was used to create
    // this session
    IP  net.IP `json:"ip"`

    // Agent specifies the User-Agent data that was used
    // to create this session.
    Agent struct {
        OS      string `json:"os"`
        Browser string `json:"browser"`
    }   `json:"agent"`
}

Session holds all the data needed to identify a session.

func FromContext Uses

func FromContext(ctx context.Context) (Session, bool)

FromContext extracts Session from the context.

func (Session) IsValid Uses

func (s Session) IsValid(r *http.Request) bool

IsValid checks whether the incoming request's properties match active session's properties or not.

type Store Uses

type Store interface {
    // Create should insert the new provided session into the store and
    // ensure that it is deleted when expiration time due.
    // Error should be returned on ID collision or other system errors.
    Create(ctx context.Context, s Session) error

    // FetchByID should retrieve the session from the store by the
    // provided ID.
    // The second returned value indicates whether the session was found
    // or not (true == found), error should be nil if session is not found.
    // Error should be returned on system errors only.
    FetchByID(ctx context.Context, id string) (Session, bool, error)

    // FetchByUserKey should retrieve all sessions associated with the
    // provided user key. If none are found, both return values should
    // be nil.
    // Error should be returned on system errors only.
    FetchByUserKey(ctx context.Context, key string) ([]Session, error)

    // DeleteByID should delete the session from the store by the
    // provided ID.
    // If session is not found, this function should be no-op and
    // return nil.
    // Error should be returned on system errors only.
    DeleteByID(ctx context.Context, id string) error

    // DeleteByUserKey should delete all sessions associated with the
    // provided user key, except those whose IDs are provided as the
    // last argument.
    // If none are found, this function should be no-op and return nil.
    // Error should be returned on system errors only.
    DeleteByUserKey(ctx context.Context, key string, expID ...string) error
}

Store provides an easy access to the underlying data store, without exposing any of its internal logic, but providing all the mandatory methods accordingly.

Directories

PathSynopsis
memstore

Package sessionup imports 9 packages (graph) and is imported by 2 packages. Updated 2020-03-29. Refresh now. Tools for package owners.