jwt_sessions

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: May 28, 2019 License: MIT Imports: 12 Imported by: 0

README

iris-jwt-sessions

A kind of fork of (Golang) Iris sessions that integrate with JWTs instead of cookies.

Yes: this includes a fork of some files existing in the regular sessions and most of it is adapted to a new use. I seriously tried to reuse most of the objects involved in session handler, but they are mostly private and so I had to essentially copy them.

Usage

It is mostly used like Sessions, but instead of:

var sessions *Sessions = sessions.NewSession(a config)
var session *Session = sessions.Start(a context)

You invoke:

var sessions *JWTSessions = sessions.NewSession(a config)
var session *JWTSession = sessions.Start(a context)

This session reads and writes Authorization: Bearer <token> headers instead of cookies. It mostly works like sessions, although an ideal expiration time in backend should be quite longer (or even perhaps no expiration at all).

You can also use the regular custom databases (e.g. redis, boltdb) you use with regular sessions.

Since Start is a func(context.Context) (something) method, it can be used as a hero-like dependency.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound can be returned when calling `UpdateExpiration` on a non-existing or invalid session entry. It can be matched directly, i.e: `isErrNotFound := sessions.ErrNotFound.Equal(err)`.

Functions

func NewMemDB

func NewMemDB() sessions.Database

Types

type Config

type Config struct {
	// Whether to reinject the new/delete the removed jwt token in the authorization
	// header again.
	AllowReclaim bool

	// The JWT session parser.
	Parser JWTParser

	// This is different with respect to cookies: expiration will be on server side,
	// if any. Client token will not expire.
	Expires time.Duration

	// SessionIDGenerator should returns a random session id.
	// By default we will use a uuid impl package to generate
	// that, but developers can change that with simple assignment.
	SessionIDGenerator func() string
}

Config is the configuration for sessions. Please read it before using sessions.

func (Config) Validate

func (c Config) Validate() Config

Validate corrects missing fields configuration fields and returns the right configuration.

type JWTParser

type JWTParser struct {
	// The bidirectional secret to sign/validate a token.
	Secret interface{}
	// The function that will return the Key to sign the JWT.
	// It can be either a shared secret or a public key.
	// Default value: nil
	SigningKeyGetter jwt.Keyfunc
	// The function that will return the Key to validate the JWT.
	// It can be either a shared secret or a public key.
	// Default value: nil
	ValidationKeyGetter jwt.Keyfunc
	// When set, the middelware verifies that tokens are signed with the specific signing algorithm
	// If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
	// Important to avoid security issues described here: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
	// Default: nil
	SigningMethod jwt.SigningMethod
}

func (*JWTParser) Parse

func (jwtParser *JWTParser) Parse(token string) (*jwt.Token, error)

Parses a JWT token from a context.

func (*JWTParser) Serialize

func (jwtParser *JWTParser) Serialize(token *jwt.Token) (string, error)

Serializes a key

func (JWTParser) Validate

func (jwtParser JWTParser) Validate() JWTParser

Validates the parser (adds default key functions if not given) - returns a copy.

type JWTSession

type JWTSession struct {
	Lifetime sessions.LifeTime
	// contains filtered or unexported fields
}

JWTSession should expose the JWTSessions's end-user API. It is the session's storage controller which you can save or retrieve values based on a key.

This is what will be returned when sess := jwtSessions.Start().

func (*JWTSession) Clear

func (s *JWTSession) Clear()

Clear removes all entries.

func (*JWTSession) ClearFlashes

func (s *JWTSession) ClearFlashes()

ClearFlashes removes all flash messages.

func (*JWTSession) Decrement

func (s *JWTSession) Decrement(key string, n int) (newValue int)

Decrement decrements the stored int value saved as "key" by -"n". If value doesn't exist on that "key" then it creates one with the "n" as its value. It returns the new, decremented, value even if it's less than zero.

func (*JWTSession) Delete

func (s *JWTSession) Delete(key string) bool

Delete removes an entry by its key, returns true if actually something was removed.

func (*JWTSession) DeleteFlash

func (s *JWTSession) DeleteFlash(key string)

DeleteFlash removes a flash message by its key.

func (*JWTSession) Destroy

func (s *JWTSession) Destroy()

Destroy destroys this session, it removes its session values and any flashes. This session entry will be removed from the server, the registered session databases will be notified for this deletion as well.

Note that this method does NOT remove the client's cookie, although it should be reseted if new session is attached to that (client).

Use the session's manager `Destroy(ctx)` in order to remove the cookie as well.

func (*JWTSession) Get

func (s *JWTSession) Get(key string) interface{}

Get returns a value based on its "key".

func (*JWTSession) GetAll

func (s *JWTSession) GetAll() map[string]interface{}

GetAll returns a copy of all session's values.

func (*JWTSession) GetBoolean

func (s *JWTSession) GetBoolean(key string) (bool, error)

GetBoolean same as `Get` but returns its boolean representation, if key doesn't exist then it returns false and a non-nil error.

func (*JWTSession) GetBooleanDefault

func (s *JWTSession) GetBooleanDefault(key string, defaultValue bool) bool

GetBooleanDefault same as `Get` but returns its boolean representation, if key doesn't exist then it returns the "defaultValue".

func (*JWTSession) GetFlash

func (s *JWTSession) GetFlash(key string) interface{}

GetFlash returns a stored flash message based on its "key" which will be removed on the next request.

To check for flash messages we use the HasFlash() Method and to obtain the flash message we use the GetFlash() Method. There is also a method GetFlashes() to fetch all the messages.

Fetching a message deletes it from the session. This means that a message is meant to be displayed only on the first page served to the user.

func (*JWTSession) GetFlashString

func (s *JWTSession) GetFlashString(key string) string

GetFlashString same as `GetFlash` but returns its string representation, if key doesn't exist then it returns an empty string.

func (*JWTSession) GetFlashStringDefault

func (s *JWTSession) GetFlashStringDefault(key string, defaultValue string) string

GetFlashStringDefault same as `GetFlash` but returns its string representation, if key doesn't exist then it returns the "defaultValue".

func (*JWTSession) GetFlashes

func (s *JWTSession) GetFlashes() map[string]interface{}

GetFlashes returns all flash messages as map[string](key) and interface{} value NOTE: this will cause at remove all current flash messages on the next request of the same user.

func (*JWTSession) GetFloat32

func (s *JWTSession) GetFloat32(key string) (float32, error)

GetFloat32 same as `Get` but returns its float32 representation, if key doesn't exist then it returns -1 and a non-nil error.

func (*JWTSession) GetFloat32Default

func (s *JWTSession) GetFloat32Default(key string, defaultValue float32) float32

GetFloat32Default same as `Get` but returns its float32 representation, if key doesn't exist then it returns the "defaultValue".

func (*JWTSession) GetFloat64

func (s *JWTSession) GetFloat64(key string) (float64, error)

GetFloat64 same as `Get` but returns its float64 representation, if key doesn't exist then it returns -1 and a non-nil error.

func (*JWTSession) GetFloat64Default

func (s *JWTSession) GetFloat64Default(key string, defaultValue float64) float64

GetFloat64Default same as `Get` but returns its float64 representation, if key doesn't exist then it returns the "defaultValue".

func (*JWTSession) GetInt

func (s *JWTSession) GetInt(key string) (int, error)

GetInt same as `Get` but returns its int representation, if key doesn't exist then it returns -1 and a non-nil error.

func (*JWTSession) GetInt64

func (s *JWTSession) GetInt64(key string) (int64, error)

GetInt64 same as `Get` but returns its int64 representation, if key doesn't exist then it returns -1 and a non-nil error.

func (*JWTSession) GetInt64Default

func (s *JWTSession) GetInt64Default(key string, defaultValue int64) int64

GetInt64Default same as `Get` but returns its int64 representation, if key doesn't exist it returns the "defaultValue".

func (*JWTSession) GetIntDefault

func (s *JWTSession) GetIntDefault(key string, defaultValue int) int

GetIntDefault same as `Get` but returns its int representation, if key doesn't exist then it returns the "defaultValue".

func (*JWTSession) GetString

func (s *JWTSession) GetString(key string) string

GetString same as Get but returns its string representation, if key doesn't exist then it returns an empty string.

func (*JWTSession) GetStringDefault

func (s *JWTSession) GetStringDefault(key string, defaultValue string) string

GetStringDefault same as Get but returns its string representation, if key doesn't exist then it returns the "defaultValue".

func (*JWTSession) HasFlash

func (s *JWTSession) HasFlash() bool

HasFlash returns true if this session has available flash messages.

func (*JWTSession) ID

func (s *JWTSession) ID() string

ID returns the session's ID.

func (*JWTSession) Increment

func (s *JWTSession) Increment(key string, n int) (newValue int)

Increment increments the stored int value saved as "key" by +"n". If value doesn't exist on that "key" then it creates one with the "n" as its value. It returns the new, incremented, value.

func (*JWTSession) IsNew

func (s *JWTSession) IsNew() bool

IsNew returns true if this session is created by the current application's process.

func (*JWTSession) PeekFlash

func (s *JWTSession) PeekFlash(key string) interface{}

PeekFlash returns a stored flash message based on its "key". Unlike GetFlash, this will keep the message valid for the next requests, until GetFlashes or GetFlash("key").

func (*JWTSession) Set

func (s *JWTSession) Set(key string, value interface{})

Set fills the session with an entry "value", based on its "key".

func (*JWTSession) SetFlash

func (s *JWTSession) SetFlash(key string, value interface{})

SetFlash sets a flash message by its key.

A flash message is used in order to keep a message in session through one or several requests of the same user. It is removed from session after it has been displayed to the user. Flash messages are usually used in combination with HTTP redirections, because in this case there is no view, so messages can only be displayed in the request that follows redirection.

A flash message has a name and a content (AKA key and value). It is an entry of an associative array. The name is a string: often "notice", "success", or "error", but it can be anything. The content is usually a string. You can put HTML tags in your message if you display it raw. You can also set the message value to a number or an array: it will be serialized and kept in session like a string.

Flash messages can be set using the SetFlash() Method For example, if you would like to inform the user that his changes were successfully saved, you could add the following line to your Handler:

SetFlash("success", "Data saved!");

In this example we used the key 'success'. If you want to define more than one flash messages, you will have to use different keys.

func (*JWTSession) SetImmutable

func (s *JWTSession) SetImmutable(key string, value interface{})

SetImmutable fills the session with an entry "value", based on its "key". Unlike `Set`, the output value cannot be changed by the caller later on (when .Get) An Immutable entry should be only changed with a `SetImmutable`, simple `Set` will not work if the entry was immutable, for your own safety. Use it consistently, it's far slower than `Set`. Read more about muttable and immutable go types: https://stackoverflow.com/a/8021081

func (*JWTSession) Visit

func (s *JWTSession) Visit(cb func(k string, v interface{}))

Visit loops each of the entries and calls the callback function func(key, value).

type JWTSessions

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

JWT sessions work mostly like normal sessions, but against a context-parsed JWT instead of against a cookie. Aside from that, they should be understood/used pretty much like regular sessions. (Note to myself: hopefully I can take a lot of code from the regular Iris sessions).

func New

func New(cfg Config) *JWTSessions

New returns a new fast, feature-rich sessions manager it can be adapted to an iris station

func (*JWTSessions) Destroy

func (sessions *JWTSessions) Destroy(ctx context.Context)

Destroy removes the session data by context.

func (*JWTSessions) DestroyAll

func (sessions *JWTSessions) DestroyAll()

DestroyAll removes all sessions.

func (*JWTSessions) DestroyByID

func (sessions *JWTSessions) DestroyByID(sid string)

DestroyByID removes the session data by ID.

func (*JWTSessions) OnDestroy

func (sessions *JWTSessions) OnDestroy(listeners ...sessions.DestroyListener)

OnDestroy registers one or more destroy listeners. A destroy listener is fired when a session has been removed entirely from the server (the entry) and client-side (the cookie). Note that if a destroy listener is blocking, then the session manager will delay respectfully, use a goroutine inside the listener to avoid that behavior.

func (*JWTSessions) ShiftExpiration

func (sessions *JWTSessions) ShiftExpiration(ctx context.Context) error

ShiftExpiration move the expire date of a session to a new date by using session default timeout configuration. It will return `ErrNotImplemented` if a database is used and it does not support this feature, yet.

func (*JWTSessions) Start

func (sessions *JWTSessions) Start(ctx context.Context) *JWTSession

Start should start the session for the particular request.

func (*JWTSessions) UpdateExpiration

func (sessions *JWTSessions) UpdateExpiration(ctx context.Context, expires time.Duration) error

UpdateExpiration change expire date of a session to a new date by using timeout value passed by `expires` receiver. It will return `ErrNotFound` when trying to update expiration on a non-existence or not valid session entry. It will return `ErrNotImplemented` if a database is used and it does not support this feature, yet.

func (*JWTSessions) UseDatabase

func (sessions *JWTSessions) UseDatabase(db sessions.Database)

UseDatabase adds a session database to the manager's provider, a session db doesn't have write access

type MemDB

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

func (*MemDB) Acquire

func (s *MemDB) Acquire(sid string, expires time.Duration) sessions.LifeTime

func (*MemDB) Clear

func (s *MemDB) Clear(sid string)

func (*MemDB) Delete

func (s *MemDB) Delete(sid string, key string) (deleted bool)

func (*MemDB) Get

func (s *MemDB) Get(sid string, key string) interface{}

func (*MemDB) Len

func (s *MemDB) Len(sid string) int

func (*MemDB) OnUpdateExpiration

func (s *MemDB) OnUpdateExpiration(string, time.Duration) error

Do nothing, the `LifeTime` of the JWTSession will be managed by the callers automatically on memory-based storage.

func (*MemDB) Release

func (s *MemDB) Release(sid string)

func (*MemDB) Set

func (s *MemDB) Set(sid string, lifetime sessions.LifeTime, key string, value interface{}, immutable bool)

immutable depends on the store, it may not implement it at all.

func (*MemDB) Visit

func (s *MemDB) Visit(sid string, cb func(key string, value interface{}))

Jump to

Keyboard shortcuts

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