1
0
mirror of https://github.com/volatiletech/authboss.git synced 2024-12-10 10:40:07 +02:00
authboss/context.go

82 lines
1.6 KiB
Go
Raw Normal View History

package authboss
2015-01-19 00:35:44 +02:00
import (
"errors"
"strings"
2015-01-19 00:35:44 +02:00
)
2015-03-16 23:42:45 +02:00
// FormValue constants
var (
FormValueRedirect = "redir"
FormValueOAuth2State = "state"
)
// Context provides context for module operations and callbacks. One obvious
// need for context is a request's session store. It is not safe for use by
// multiple goroutines.
type Context struct {
*Authboss
SessionStorer ClientStorerErr
CookieStorer ClientStorerErr
User Attributes
}
2015-03-16 23:42:45 +02:00
// NewContext is exported for testing modules.
func (a *Authboss) NewContext() *Context {
return &Context{
Authboss: a,
}
}
// LoadUser loads the user Attributes if they haven't already been loaded.
func (c *Context) LoadUser(key string) error {
if c.User != nil {
return nil
}
var user interface{}
var err error
if index := strings.IndexByte(key, ';'); index > 0 {
user, err = c.OAuth2Storer.GetOAuth(key[:index], key[index+1:])
} else {
user, err = c.Storer.Get(key)
}
if err != nil {
return err
}
c.User = Unbind(user)
return nil
}
// LoadSessionUser loads the user from the session if the user has not already been
// loaded.
func (c *Context) LoadSessionUser() error {
if c.User != nil {
return nil
}
key, ok := c.SessionStorer.Get(SessionKey)
if !ok {
return ErrUserNotFound
}
return c.LoadUser(key)
}
// SaveUser saves the user Attributes.
func (c *Context) SaveUser() error {
if c.User == nil {
2015-01-19 00:35:44 +02:00
return errors.New("User not initialized.")
}
key, ok := c.User.String(c.PrimaryID)
if !ok {
return errors.New("User improperly initialized, primary ID missing")
}
return c.Storer.Put(key, c.User)
}