Documentation ¶
Overview ¶
Package session is used to store user data in token based cache. It is normally used as user session or token. This package depands github.com/herb-go/herb/cache.
Index ¶
- Constants
- Variables
- func AESDecrypt(encrypted []byte, key []byte, iv []byte) (decrypted []byte, err error)
- func AESDecryptBase64(encrypted string, key []byte, iv []byte) (decrypted []byte, err error)
- func AESEncrypt(unencrypted []byte, key []byte, iv []byte) (encrypted []byte, err error)
- func AESEncryptBase64(unencrypted []byte, key []byte, iv []byte) (encrypted string, err error)
- func AESNonceDecrypt(encrypted []byte, key []byte) (decrypted []byte, err error)
- func AESNonceDecryptBase64(encrypted string, key []byte) (decrypted []byte, err error)
- func AESNonceEncrypt(unencrypted []byte, key []byte) (encrypted []byte, err error)
- func AESNonceEncryptBase64(unencrypted []byte, key []byte) (encrypted string, err error)
- func AESTokenMarshaler(s *ClientDriver, ts *Session) (err error)
- func AESTokenUnmarshaler(s *ClientDriver, v *Session) (err error)
- func PKCS7Padding(data []byte, blockSize int) []byte
- func PKCS7Unpadding(data []byte) []byte
- type CacheDriver
- func (s *CacheDriver) Close() error
- func (s *CacheDriver) ConvertPrefix(prefix string) (output string, err error)
- func (s *CacheDriver) Delete(token string) (bool, error)
- func (s *CacheDriver) DynamicToken() bool
- func (s *CacheDriver) GenerateToken(prefix string) (token string, err error)
- func (s *CacheDriver) GetSessionToken(ts *Session) (token string, err error)
- func (s *CacheDriver) Init(option CacheDriverOption) error
- func (s *CacheDriver) Load(v *Session) (err error)
- func (s *CacheDriver) Save(ts *Session, ttl time.Duration) (err error)
- type CacheDriverOption
- type CacheDriverOptionConfig
- type ClientDriver
- func (s *ClientDriver) Close() error
- func (s *ClientDriver) Delete(token string) (bool, error)
- func (s *ClientDriver) DynamicToken() bool
- func (s *ClientDriver) GenerateToken(prefix string) (token string, err error)
- func (s *ClientDriver) GetSessionToken(ts *Session) (token string, err error)
- func (s *ClientDriver) Init(option ClientDriverOption) error
- func (s *ClientDriver) Load(v *Session) (err error)
- func (s *ClientDriver) Save(ts *Session, ttl time.Duration) (err error)
- type ClientDriverOption
- type ClientDriverOptionConfig
- type ContextKey
- type Driver
- type Field
- func (f *Field) Flush(r *http.Request) (err error)
- func (f *Field) Get(r *http.Request, v interface{}) (err error)
- func (f *Field) GetSession(r *http.Request) (ts *Session, err error)
- func (f *Field) IdentifyRequest(r *http.Request) (string, error)
- func (f *Field) LoadFrom(ts *Session, v interface{}) (err error)
- func (f *Field) Login(w http.ResponseWriter, r *http.Request, id string) error
- func (f *Field) Logout(w http.ResponseWriter, r *http.Request) error
- func (f *Field) SaveTo(ts *Session, v interface{}) (err error)
- func (f *Field) Set(r *http.Request, v interface{}) (err error)
- type Flag
- type Option
- type OptionConfig
- type ResponseWriter
- type Session
- func (s *Session) Del(name string) (err error)
- func (s *Session) DeleteAndSave() error
- func (s *Session) Destory() (bool, error)
- func (s *Session) Get(name string, v interface{}) (err error)
- func (s *Session) HasFlag(flag Flag) bool
- func (s *Session) IsNotFoundError(err error) bool
- func (s *Session) Load() error
- func (s *Session) Marshal() ([]byte, error)
- func (s *Session) MustToken() string
- func (s *Session) Regenerate()
- func (s *Session) RegenerateToken(owner string) error
- func (s *Session) Save() error
- func (s *Session) Set(name string, v interface{}) (err error)
- func (s *Session) SetCache(name string, v interface{})
- func (s *Session) SetFlag(flag Flag, value bool)
- func (s *Session) SetToken(newToken string)
- func (s *Session) Token() (string, error)
- func (s *Session) Unmarshal(token string, bytes []byte) error
- type Store
- func (s *Store) AutoGenerateMiddleware() func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
- func (s *Store) Close() error
- func (s *Store) CookieMiddleware() func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
- func (s *Store) Del(r *http.Request, fieldName string) (err error)
- func (s *Store) DeleteToken(token string) (bool, error)
- func (s *Store) DestoryMiddleware() func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
- func (s *Store) ExpiredAt(r *http.Request) (ExpiredAt int64, err error)
- func (s *Store) Field(name string) *Field
- func (s *Store) GenerateSession(token string) (ts *Session, err error)
- func (s *Store) GenerateToken(prefix string) (token string, err error)
- func (s *Store) Get(r *http.Request, fieldName string, v interface{}) (err error)
- func (s *Store) GetRequestSession(r *http.Request) (ts *Session, err error)
- func (s *Store) GetSession(token string) (ts *Session)
- func (s *Store) GetSessionToken(ts *Session) (token string, err error)
- func (s *Store) HeaderMiddleware(Name string) func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
- func (s *Store) Init(option Option) error
- func (s *Store) Install(r *http.Request, token string) (ts *Session, err error)
- func (s *Store) InstallMiddleware() func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
- func (s *Store) IsNotFoundError(err error) bool
- func (s *Store) LoadSession(v *Session) error
- func (s *Store) RegenerateToken(prefix string) (ts *Session, err error)
- func (s *Store) SaveRequestSession(r *http.Request) error
- func (s *Store) SaveSession(t *Session) error
- func (s *Store) Set(r *http.Request, fieldName string, v interface{}) (err error)
- type StoreConfig
Constants ¶
const ( //PrefixModeRaw prefix mode which dont convert prefix PrefixModeRaw = "raw" //PrefixModeMd5 prefix mode which convert prefix to md5 sum PrefixModeMd5 = "md5" //PrefixModeEmpty prefix mode which convert prefix to empty string PrefixModeEmpty = "empty" )
const ( //StoreModeCookie which store session token in cookie. StoreModeCookie = "cookie" //StoreModeHeader which store session token in header. StoreModeHeader = "header" )
const DefaultTokenLength = 64
DefaultTokenLength default token length
const DriverNameCacheStore = "cache"
DriverNameCacheStore driver name for data store
const DriverNameClientStore = "cookie"
DriverNameClientStore driver name for client store
const FlagDefault = Flag(1)
FlagDefault default session flag
const FlagTemporay = Flag(3)
FlagTemporay Flag what stands for a Temporay sesson. For example,a login withour "remeber me".
const IVSize = 16
IVSize AES IV size
Variables ¶
var ( //ErrDataNotFound rasied when token data not found. ErrDataNotFound = errors.New("Data not found") //ErrDataTypeWrong rasied when the given model type is different form registered model type. ErrDataTypeWrong = errors.New("Data type wrong") //ErrNilPointer raised when data point to nil. ErrNilPointer = errors.New("Data point to nil") )
var ( //ErrTokenNotValidated raised when the given token is not validated(for example: token is empty string) ErrTokenNotValidated = errors.New("Token not validated") //ErrRequestTokenNotFound raised when token is not found in context.You should use cookiemiddle or headermiddle or your our function to install the token. ErrRequestTokenNotFound = errors.New("Request token not found.Did you forget use install middleware?") //ErrFeatureNotSupported raised when fearture is not supoprted. ErrFeatureNotSupported = errors.New("Feature is not supported") )
var DefaultMarshaler = "msgpack"
DefaultMarshaler default session Marshaler
Functions ¶
func AESDecrypt ¶
AESDecrypt decrypt data with given key and iv. Data will be unpadding with PKCS7Unpadding. Return decrypted data and any error if raised.
func AESDecryptBase64 ¶
AESDecryptBase64 decrypt base64 encoded data with given key and iv. Data will be unpadding with PKCS7Unpadding. Return decrypted data and any error if raised.
func AESEncrypt ¶
AESEncrypt aes encrypt with given data,key and iv. Data will be padding with PKCS7Padding Return encrytped data and any error if raised.
func AESEncryptBase64 ¶
AESEncryptBase64 aes encrypt with given data,key and iv. Data will be padding with PKCS7Padding Return base64 encoded encrytped data and any error if raised.
func AESNonceDecrypt ¶
AESNonceDecrypt decrypt data with given key. IV will load form first bytes of data. Data will be unpadding with PKCS7Unpadding. Return decrypted data and any error if raised.
func AESNonceDecryptBase64 ¶
AESNonceDecryptBase64 decrypt base64 encoded data with given key. IV will load form first bytes of data. Data will be unpadding with PKCS7Unpadding. Return decrypted data and any error if raised.
func AESNonceEncrypt ¶
AESNonceEncrypt aes encrypt data with given key and random bytes as IV. Data will be padding with PKCS7Padding Random IV will prefix encryped data return encrypted data and any error if raisd.
func AESNonceEncryptBase64 ¶
AESNonceEncryptBase64 aes encrypt data with given key and random bytes as IV. Data will be padding with PKCS7Padding Random IV will prefix encryped data return base64 encoded encrypted data and any error if raisd.
func AESTokenMarshaler ¶
func AESTokenMarshaler(s *ClientDriver, ts *Session) (err error)
AESTokenMarshaler token marshaler which crypt data with AES Return error if raised
func AESTokenUnmarshaler ¶
func AESTokenUnmarshaler(s *ClientDriver, v *Session) (err error)
AESTokenUnmarshaler token unmarshaler which crypt data with AES Return error if raised
func PKCS7Padding ¶
PKCS7Padding padding data as PKCS7 Reference http://blog.studygolang.com/167.html
func PKCS7Unpadding ¶
PKCS7Unpadding unpadding data as PKCS7 Reference http://blog.studygolang.com/167.html
Types ¶
type CacheDriver ¶
type CacheDriver struct { Cache *cache.Cache //Cache which stores token data Length int PrefixMode string TokenGenerater func(s *CacheDriver, prefix string) (token string, err error) //Token name generate func }
CacheDriver CacheDriver is the stuct store token data in cache.
func (*CacheDriver) Close ¶
func (s *CacheDriver) Close() error
Close Close cachestore and return any error if raised
func (*CacheDriver) ConvertPrefix ¶
func (s *CacheDriver) ConvertPrefix(prefix string) (output string, err error)
ConvertPrefix convert prefix by driver prefix mode
func (*CacheDriver) Delete ¶
func (s *CacheDriver) Delete(token string) (bool, error)
Delete delete the token with given name. Return any error if raised.
func (*CacheDriver) DynamicToken ¶
func (s *CacheDriver) DynamicToken() bool
func (*CacheDriver) GenerateToken ¶
func (s *CacheDriver) GenerateToken(prefix string) (token string, err error)
GenerateToken generate new token name with given prefix. Return the new token name and error.
func (*CacheDriver) GetSessionToken ¶
func (s *CacheDriver) GetSessionToken(ts *Session) (token string, err error)
GetSessionToken Get the token string from token data. Return token and any error raised.
func (*CacheDriver) Init ¶
func (s *CacheDriver) Init(option CacheDriverOption) error
Init init cache driver with given option
func (*CacheDriver) Load ¶
func (s *CacheDriver) Load(v *Session) (err error)
Load load a given session with token from store.
type CacheDriverOption ¶
type CacheDriverOption interface {
ApplyTo(*CacheDriver) error
}
CacheDriverOption cache driver init option interface.
type CacheDriverOptionConfig ¶
CacheDriverOptionConfig cache driver init option
func NewCacheDriverOptionConfig ¶
func NewCacheDriverOptionConfig() *CacheDriverOptionConfig
NewCacheDriverOptionConfig create new cache driver init option
func (*CacheDriverOptionConfig) ApplyTo ¶
func (o *CacheDriverOptionConfig) ApplyTo(d *CacheDriver) error
ApplyTo apply cache driver option config to cache driver. return any error if raised.
type ClientDriver ¶
type ClientDriver struct { Key []byte //Crypt key TokenMarshaler func(*ClientDriver, *Session) error //Marshler data to Session.token TokenUnmarshaler func(*ClientDriver, *Session) error //Unmarshler data from Session.token }
ClientDriver ClientDriver is the stuct store token data in Client side.
func NewClientDriver ¶
func NewClientDriver() *ClientDriver
NewClientDriver New create a new client side token store with given key and token lifetime. Key the key used to encrpty data TokenLifeTime is the token initial expired tome. Return a new token store. All other property of the store can be set after creation.
func (*ClientDriver) Close ¶
func (s *ClientDriver) Close() error
Close Close cachestore and return any error if raised
func (*ClientDriver) Delete ¶
func (s *ClientDriver) Delete(token string) (bool, error)
Delete delete the token with given name. Return any error if raised.
func (*ClientDriver) DynamicToken ¶
func (s *ClientDriver) DynamicToken() bool
func (*ClientDriver) GenerateToken ¶
func (s *ClientDriver) GenerateToken(prefix string) (token string, err error)
GenerateToken generate new token name with given prefix. Return the new token name and error.
func (*ClientDriver) GetSessionToken ¶
func (s *ClientDriver) GetSessionToken(ts *Session) (token string, err error)
GetSessionToken Get the token string from token data. Return token and any error raised.
func (*ClientDriver) Init ¶
func (s *ClientDriver) Init(option ClientDriverOption) error
Init init client driver with given option. Return any error if raised.
func (*ClientDriver) Load ¶
func (s *ClientDriver) Load(v *Session) (err error)
Load Load Session form the Session.token. Return any error if raised
type ClientDriverOption ¶
type ClientDriverOption interface {
ApplyTo(*ClientDriver) error
}
ClientDriverOption client driver init option interface.
type ClientDriverOptionConfig ¶
type ClientDriverOptionConfig struct {
Key []byte
}
ClientDriverOptionConfig client driver init option.
func NewClientDriverOptionConfig ¶
func NewClientDriverOptionConfig() *ClientDriverOptionConfig
NewClientDriverOptionConfig create new client driver init option.
func (*ClientDriverOptionConfig) ApplyTo ¶
func (o *ClientDriverOptionConfig) ApplyTo(d *ClientDriver) error
ApplyTo apply client driver option config to cache driver. return any error if raised.
type Driver ¶
type Driver interface { GetSessionToken(ts *Session) (token string, err error) GenerateToken(owner string) (token string, err error) DynamicToken() bool Load(v *Session) error Save(t *Session, ttl time.Duration) error Delete(token string) (bool, error) Close() error }
Driver store driver.
type Field ¶
Field session field struct
func (*Field) Get ¶
Get get value from session store in given http request and save to v. Return any error if raised.
func (*Field) GetSession ¶
GetSession get Session from http request. Return session and any error if raised.
func (*Field) IdentifyRequest ¶
IdentifyRequest indentify request with field. Return id and any error if raised.
type OptionConfig ¶
OptionConfig store init config
func NewOptionConfig ¶
func NewOptionConfig() *OptionConfig
NewOptionConfig create new store init config
func (*OptionConfig) ApplyTo ¶
func (o *OptionConfig) ApplyTo(s *Store) error
ApplyTo apply config to sessoion store
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter http.Hijacker }
ResponseWriter http response writer
type Session ¶
type Session struct { ExpiredAt int64 //Timestamp when the token expired. CreatedTime int64 //Timestamp when the token created. LastActiveTime int64 //Timestamp when the token Last Active. Store *Store Nonce []byte Flag Flag Mutex *sync.RWMutex //Read write mutex. // contains filtered or unexported fields }
Session Token data in every request.
func NewSession ¶
NewSession create new token data in store with given name. token the token name. s the store which token data belongs to. return new Session.
func (*Session) Get ¶
Get load data model from given token data. Parameter v should be pointer to empty data model which data filled in. Return any error raised.
func (*Session) IsNotFoundError ¶
IsNotFoundError return if given error if a not found error.
func (*Session) Load ¶
Load the token data from cache. Repeat call Load will only load data once. Return any error raised.
func (*Session) Marshal ¶
Marshal convert Session to bytes. Return Converted bytes and any error raised.
func (*Session) Regenerate ¶
func (s *Session) Regenerate()
Regenerate reset all session values except token
func (*Session) RegenerateToken ¶
RegenerateToken create new token and token data with given owner. Return any error raised.
func (*Session) Save ¶
Save Save token data to cache. Won't do anything if token data not changed. You should call Save manually in your token binding func or non http request usage.
type Store ¶
type Store struct { Driver Driver Marshaler cache.Marshaler TokenLifetime time.Duration //Token initial expired time.Token life time can be refreshed when accessed if UpdateActiveInterval is greater than 0. TokenMaxLifetime time.Duration //Token max life time.Token can't live more than TokenMaxLifetime if TokenMaxLifetime if greater than 0. TokenContextName ContextKey //Name in request context store the token data.Default Session is "token". CookieName string //Cookie name used in CookieMiddleware.Default Session is "herb-session". CookiePath string //Cookie path used in cookieMiddleware.Default Session is "/". CookieSecure bool //Cookie secure value used in cookie middleware. AutoGenerate bool //Whether auto generate token when guest visit.Default Session is false. Mode string //Mode used in auto install middleware. UpdateActiveInterval time.Duration //The interval between what token active time refreshed.If less than or equal to 0,the token life time will not be refreshed. DefaultSessionFlag Flag //Default flag when creating session. }
Store Basic token store interface
func MustCacheStore ¶
MustCacheStore create new data store with given token lifetime. Return store created. Panic if any error raised.
func MustClientStore ¶
MustClientStore create new client store with given key and ttl. Return store created. Panic if any error raised.
func (*Store) AutoGenerateMiddleware ¶
func (s *Store) AutoGenerateMiddleware() func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
AutoGenerateMiddleware middleware that auto generate session.
func (*Store) CookieMiddleware ¶
func (s *Store) CookieMiddleware() func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
CookieMiddleware return a Middleware which install the token which special by cookie. This middleware will save token after request finished if the token changed,and update cookie if necessary.
func (*Store) Del ¶
Del delete value from request with given field name. Return any error if raised.
func (*Store) DeleteToken ¶
DeleteToken delete the token with given name. Return any error if raised.
func (*Store) DestoryMiddleware ¶
func (s *Store) DestoryMiddleware() func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
DestoryMiddleware return a middleware clear the token in request.
func (*Store) ExpiredAt ¶
ExpiredAt get session expired timestamp from rerquest. Return expired timestamp and any error if raised.
func (*Store) GenerateSession ¶
GenerateSession generate new token data with given token. Return a new Session and error.
func (*Store) GenerateToken ¶
GenerateToken generate new token name with given prefix. Return the new token name and error.
func (*Store) GetRequestSession ¶
GetRequestSession get stored token data from request. Return the stored token data and any error raised.
func (*Store) GetSession ¶
GetSession get the token data with give token . Return the Session
func (*Store) GetSessionToken ¶
GetSessionToken Get the token string from token data. Return token and any error raised.
func (*Store) HeaderMiddleware ¶
func (s *Store) HeaderMiddleware(Name string) func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
HeaderMiddleware return a Middleware which install the token which special by Header with given name. This middleware will save token after request finished if the token changed.
func (*Store) Install ¶
Install install the give token to request. Session will be stored in request context which named by TokenContextName of store. You should use this func when use your own token binding func instead of CookieMiddleware or HeaderMiddleware Return the loaded Session and any error raised.
func (*Store) InstallMiddleware ¶
func (s *Store) InstallMiddleware() func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
InstallMiddleware middleware which auto install session depand on store mode. Cookie middleware will be installed if no valid store mode given.
func (*Store) IsNotFoundError ¶
IsNotFoundError return if given error if a not found error.
func (*Store) LoadSession ¶
LoadSession Load Session form the Session.token. Return any error if raised
func (*Store) RegenerateToken ¶
RegenerateToken regenerate session token with given prefix. Return session and any error if raised.
func (*Store) SaveRequestSession ¶
SaveRequestSession save the request token data.
func (*Store) SaveSession ¶
SaveSession Save Session if necessary. Return any error raised.
type StoreConfig ¶
type StoreConfig struct { DriverName string Marshaler string Mode string TokenLifetime string //Token initial expired time.Token life time can be update when accessed if UpdateActiveInterval is greater than 0. TokenMaxLifetime string //Token max life time.Token can't live more than TokenMaxLifetime if TokenMaxLifetime if greater than 0. TokenContextName string //Name in request context store the token data.Default Session is "token". CookieName string //Cookie name used in CookieMiddleware.Default Session is "herb-session". CookiePath string //Cookie path used in cookieMiddleware.Default Session is "/". CookieSecure bool //Cookie secure value used in cookie middleware. AutoGenerate bool //Whether auto generate token when guset visit.Default Session is false. UpdateActiveIntervalInSecond int64 //The interval between which token active time update.If less than or equal to 0,the token life time will not be refreshed. DefaultSessionFlag Flag //Default flag when creating session. ClientStoreKey string TokenPrefixMode string TokenLength int Cache cache.OptionConfig }
StoreConfig store config struct.
func (*StoreConfig) ApplyTo ¶
func (s *StoreConfig) ApplyTo(store *Store) error
ApplyTo apply config to store. Return any error if raised.