oauth2

package
v1.0.1-0...-8e9dff6 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2018 License: MIT Imports: 28 Imported by: 2

README

oauth2

This is a OAuth2 helper library.

This library implements osin storage with upper.io as storage layer. So it supports all storage that upper.io supports (i.e. MySQL, PostgreSQL, SQLite3, MongoDB).

Structs are defined to be as generic as possible. Data layer is generated with gourd and hence implementing the gourd's store interface.

Documentation

Index

Constants

View Source
const (
	KeyClient storeKey = iota
	KeyAuth
	KeyAccess
	KeyUser
)

Keys for Storage to access different stores from provided context

View Source
const DefaultLoginTpl = `` /* 1387-byte string literal not displayed */

DefaultLoginTpl is the HTML template for login form by default

Variables

This section is empty.

Functions

func AccessDataStoreProvider

func AccessDataStoreProvider(sess interface{}) (s store.Store, err error)

AccessDataStoreProvider implements store.Provider interface provides raw AccessDataStore

func AuthorizeDataStoreProvider

func AuthorizeDataStoreProvider(sess interface{}) (s store.Store, err error)

AuthorizeDataStoreProvider implements store.Provider interface provides raw AuthorizeDataStore

func ClientStoreProvider

func ClientStoreProvider(sess interface{}) (s store.Store, err error)

ClientStoreProvider implements store.Provider interface provides raw ClientStore

func DefaultOsinConfig

func DefaultOsinConfig() (cfg *osin.ServerConfig)

DefaultOsinConfig returns a preset config suitable for most generic oauth2 usage

func GetToken

func GetToken(ctx context.Context) (token string)

GetToken reads the token from context

func LoadTokenAccess

func LoadTokenAccess(ctx context.Context) context.Context

LoadTokenAccess reads token information from header ("Authority") and, if AccessData found for the given token, add to context

func Middleware

func Middleware(inner endpoint.Endpoint) endpoint.Endpoint

Middleware retrieves token from context with GetToken(), then set the AccessData to the context with WithAccess().

Inner endpoint may retrieve the AccessData using GetAccess().

func Route

func Route(rfn httpservice.RouterFunc, base string, ep *Endpoints) (err error)

Route adds manager's endpoint to a router with httpservice.RouterFunc

func SetErrorLogger

func SetErrorLogger(v log.Logger)

SetErrorLogger setup the error logger for all oauth2 operations

func SetLogger

func SetLogger(v log.Logger)

SetLogger setup the default logger for all oauth2 operations

func UseToken

func UseToken(ctx context.Context, r *http.Request) context.Context

UseToken reads the token information from header ("Authority") and add to the context. Implements go-kit httptransport BeforeFunc

func UserDataID

func UserDataID(UserData interface{}) (strID string, err error)

UserDataID reads UserData field for AccessData / AuthorizeData then retrieve the ID string or return error

func UserRest

func UserRest(rf httpservice.RouterFunc, paths httpservice.Paths, patches ...httpservice.ServicesPatch)

UserRest binds store to pat router

func UserStoreEndpoints

func UserStoreEndpoints(noun, nounp string) (endpoints map[string]endpoint.Endpoint)

UserStoreEndpoints return CURD endpoints for UserStore

func UserStoreProvider

func UserStoreProvider(sess interface{}) (s store.Store, err error)

UserStoreProvider implements store.Provider interface provides raw UserStore

func UserStoreServices

func UserStoreServices(paths httpservice.Paths, endpoints map[string]endpoint.Endpoint) (handlers httpservice.Services)

func WithAccess

func WithAccess(parent context.Context, ad *AccessData) context.Context

WithAccess implements go-kit httptransport RequestFunc Adds the current HTTP Request to context.Context

Types

type AccessData

type AccessData struct {

	// ID is the primary key of AccessData
	ID string `db:"id,omitempty" json:"id"`

	// ClientId is the client which this AccessData is linked to
	ClientID string `db:"client_id" json:"client_id"`

	// Client information
	Client *Client `db:"-" json:"-"`

	// Authorize data, for authorization code
	AuthorizeData *AuthorizeData `db:"-" json:"-"`

	// Authorize data, for authorization code
	AuthorizeDataJSON string `db:"auth_data_json,omitempty" json:"-"`

	// Previous access data, for refresh token
	AccessData *AccessData `db:"-" json:"-"`

	// AccessDataJSON stores the previous access data in JSON string
	AccessDataJSON string `db:"access_data_json,omitempty" json:"-"`

	// Access token
	AccessToken string `db:"access_token" json:"access_token"`

	// Refresh Token. Can be blank
	RefreshToken string `db:"refresh_token" json:"refresh_token"`

	// Token expiration in seconds
	ExpiresIn int32 `db:"expires_in" json:"expires_in"`

	// Requested scope
	Scope string `db:"scope" json:"scope"`

	// RedirectUri from request
	RedirectURI string `db:"redirect_uri" json:"redirect_uri"`

	// Date created
	CreatedAt time.Time `db:"created_at" json:"created_at"`

	// User Id the data is linked to
	UserID string `db:"user_id" json:"user_id"`

	// Data to be passed to storage. Not used by the osin library.
	UserData interface{} `db:"-"`
}

AccessData interfacing database to osin storage I/O of same name

func GetAccess

func GetAccess(ctx context.Context) (d *AccessData)

GetAccess returns oauth2 AccessData stored in session

func (*AccessData) ReadOsin

func (d *AccessData) ReadOsin(od *osin.AccessData) (err error)

ReadOsin reads an osin's AccessData into the AccessData instance

func (*AccessData) Scopes

func (d *AccessData) Scopes() *Scopes

Scopes read the scope field into Scopes type

func (*AccessData) ToOsin

func (d *AccessData) ToOsin() (od *osin.AccessData)

ToOsin returns an osin version of the struct of osin I/O

type AccessDataStore

type AccessDataStore struct {
	Db db.Database
	// contains filtered or unexported fields
}

AccessDataStore serves generic CURD for type AccessData Generated by gourd CLI tool

func (*AccessDataStore) AllocEntity

func (s *AccessDataStore) AllocEntity() store.EntityPtr

AllocEntity allocate memory for an entity

func (*AccessDataStore) AllocEntityList

func (s *AccessDataStore) AllocEntityList() store.EntityListPtr

AllocEntityList allocate memory for an entity list

func (*AccessDataStore) Close

func (s *AccessDataStore) Close() error

Close would not close database connection at all. Please use store.CloseAllIn(ctx) to wrap up connections in a context

func (*AccessDataStore) Coll

func (s *AccessDataStore) Coll() (coll db.Collection, err error)

Coll return the raw upper.io collection

func (*AccessDataStore) Create

func (s *AccessDataStore) Create(
	cond store.Conds, ep store.EntityPtr) (err error)

Create a AccessData in the database, of the parent

func (*AccessDataStore) Delete

func (s *AccessDataStore) Delete(
	c store.Conds) (err error)

Delete AccessData on condition(s)

func (*AccessDataStore) Len

Len inspect the length of an entity list

func (*AccessDataStore) One

func (s *AccessDataStore) One(
	c store.Conds, ep store.EntityPtr) (err error)

One returns the first AccessData matches condition(s)

func (*AccessDataStore) Search

func (s *AccessDataStore) Search(
	q store.Query) store.Result

Search a AccessData by its condition(s)

func (*AccessDataStore) SetLogger

func (s *AccessDataStore) SetLogger(logger log.Logger)

SetLogger set the logger fotr the AccessDataStore

func (*AccessDataStore) Update

func (s *AccessDataStore) Update(
	c store.Conds, ep store.EntityPtr) (err error)

Update AccessData on condition(s)

type AuthorizeData

type AuthorizeData struct {

	// Authorize Data Id
	ID string `db:"id,omitempty" json:"id,omitempty"`

	// Client Id the data is linked to
	ClientID string `db:"client_id" json:"client_id"`

	// Client information
	Client *Client `db:"-" json:"-"`

	// Authorization code
	Code string `db:"code" json:"code"`

	// Token expiration in seconds
	ExpiresIn int32 `db:"expires_in" json:"expires_in"`

	// Requested scope
	Scope string `db:"scope" json:"scope"`

	// Redirect Uri from request
	RedirectURI string `db:"redirect_uri" json:"redirect_uri"`

	// State data from request
	State string `db:"state" json:"state"`

	// Date created
	CreatedAt time.Time `db:"created_at" json:"created_at"`

	// User Id the data is linked to
	UserID string `db:"user_id" json:"user_id"`

	// Data to be passed to storage. Not used by the osin library.
	UserData interface{} `db:"-"`
}

AuthorizeData interfacing database to osin storage I/O of same name

func (*AuthorizeData) ReadOsin

func (d *AuthorizeData) ReadOsin(od *osin.AuthorizeData) (err error)

ReadOsin reads a *osin.AuthorizeData, takes its value then set to itself

func (*AuthorizeData) ToOsin

func (d *AuthorizeData) ToOsin() (od *osin.AuthorizeData)

ToOsin returns an osin version of the struct of osin I/O

type AuthorizeDataStore

type AuthorizeDataStore struct {
	Db db.Database
	// contains filtered or unexported fields
}

AuthorizeDataStore serves generic CURD for type AuthorizeData Generated by gourd CLI tool

func (*AuthorizeDataStore) AllocEntity

func (s *AuthorizeDataStore) AllocEntity() store.EntityPtr

AllocEntity allocate memory for an entity

func (*AuthorizeDataStore) AllocEntityList

func (s *AuthorizeDataStore) AllocEntityList() store.EntityListPtr

AllocEntityList allocate memory for an entity list

func (*AuthorizeDataStore) Close

func (s *AuthorizeDataStore) Close() error

Close would not close database connection at all. Please use store.CloseAllIn(ctx) to wrap up connections in a context

func (*AuthorizeDataStore) Coll

func (s *AuthorizeDataStore) Coll() (coll db.Collection, err error)

Coll return the raw upper.io collection

func (*AuthorizeDataStore) Create

func (s *AuthorizeDataStore) Create(
	cond store.Conds, ep store.EntityPtr) (err error)

Create a AuthorizeData in the database, of the parent

func (*AuthorizeDataStore) Delete

func (s *AuthorizeDataStore) Delete(
	c store.Conds) (err error)

Delete AuthorizeData on condition(s)

func (*AuthorizeDataStore) Len

Len inspect the length of an entity list

func (*AuthorizeDataStore) One

func (s *AuthorizeDataStore) One(
	c store.Conds, ep store.EntityPtr) (err error)

One returns the first AuthorizeData matches condition(s)

func (*AuthorizeDataStore) Search

func (s *AuthorizeDataStore) Search(
	q store.Query) store.Result

Search a AuthorizeData by its condition(s)

func (*AuthorizeDataStore) SetLogger

func (s *AuthorizeDataStore) SetLogger(logger log.Logger)

SetLogger set the logger fotr the AuthorizeDataStore

func (*AuthorizeDataStore) Update

func (s *AuthorizeDataStore) Update(
	c store.Conds, ep store.EntityPtr) (err error)

Update AuthorizeData on condition(s)

type Client

type Client struct {
	ID          string      `db:"id,omitempty" json:"id"`
	Secret      string      `db:"secret" json:"-"`
	RedirectURI string      `db:"redirect_uri" json:"redirect_uri"`
	UserID      string      `db:"user_id" json:"user_id"`
	UserData    interface{} `db:"-" json:"-"`
}

Client implements the osin Client interface

func (*Client) GetId

func (c *Client) GetId() string

func (*Client) GetRedirectUri

func (c *Client) GetRedirectUri() string

func (*Client) GetSecret

func (c *Client) GetSecret() string

func (*Client) GetUserData

func (c *Client) GetUserData() interface{}

type ClientStore

type ClientStore struct {
	Db db.Database
	// contains filtered or unexported fields
}

ClientStore serves generic CURD for type Client Generated by gourd CLI tool

func (*ClientStore) AllocEntity

func (s *ClientStore) AllocEntity() store.EntityPtr

AllocEntity allocate memory for an entity

func (*ClientStore) AllocEntityList

func (s *ClientStore) AllocEntityList() store.EntityListPtr

AllocEntityList allocate memory for an entity list

func (*ClientStore) Close

func (s *ClientStore) Close() error

Close would not close database connection at all. Please use store.CloseAllIn(ctx) to wrap up connections in a context

func (*ClientStore) Coll

func (s *ClientStore) Coll() (coll db.Collection, err error)

Coll return the raw upper.io collection

func (*ClientStore) Create

func (s *ClientStore) Create(
	cond store.Conds, ep store.EntityPtr) (err error)

Create a Client in the database, of the parent

func (*ClientStore) Delete

func (s *ClientStore) Delete(
	c store.Conds) (err error)

Delete Client on condition(s)

func (*ClientStore) Len

func (s *ClientStore) Len(pl store.EntityListPtr) int64

Len inspect the length of an entity list

func (*ClientStore) One

func (s *ClientStore) One(
	c store.Conds, ep store.EntityPtr) (err error)

One returns the first Client matches condition(s)

func (*ClientStore) Search

func (s *ClientStore) Search(
	q store.Query) store.Result

Search a Client by its condition(s)

func (*ClientStore) SetLogger

func (s *ClientStore) SetLogger(logger log.Logger)

SetLogger set the logger fotr the ClientStore

func (*ClientStore) Update

func (s *ClientStore) Update(
	c store.Conds, ep store.EntityPtr) (err error)

Update Client on condition(s)

type Endpoints

type Endpoints struct {
	Auth  http.HandlerFunc
	Token http.HandlerFunc
	Info  http.HandlerFunc
}

Endpoints contains http handler func of different endpoints

type LoginFormContext

type LoginFormContext struct {
	Context        context.Context
	ResponseWriter http.ResponseWriter
	Request        *http.Request
	LoginErr       error
	ActionURL      *url.URL
	Logger         log.Logger
}

LoginFormContext represents the context of the login form rendering

type LoginFormFunc

type LoginFormFunc func(lctx *LoginFormContext) (err error)

LoginFormFunc handles GET request of the authorize endpoint and displays a login form for user to login. The action parameter provides a pre-rendered URL to login

func NewLoginFormFunc

func NewLoginFormFunc(idName, tpl string) LoginFormFunc

NewLoginFormFunc creates a LoginFormFunc from given template

type Manager

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

Manager handles oauth2 related request Also provide middleware for other http handler function to access scope related information

func NewManager

func NewManager() (m *Manager)

NewManager returns a oauth2 manager with default configs

func (*Manager) GetEndpoints

func (m *Manager) GetEndpoints(factory store.Factory) *Endpoints

GetEndpoints generate endpoints http handers and return

func (*Manager) InitOsin

func (m *Manager) InitOsin(cfg *osin.ServerConfig) *Manager

InitOsin set the OsinServer

func (*Manager) SetLoginFormFunc

func (m *Manager) SetLoginFormFunc(f LoginFormFunc)

SetLoginFormFunc sets the handler to display login form

func (*Manager) SetUserFunc

func (m *Manager) SetUserFunc(f UserFunc)

SetUserFunc sets the parser for login request. Will be called when endpoint POST request

Manager will then search user with `idField` equals to `id`. Then it will check User.HasPassword(`password`) (User should implement OAuth2User interface) to see if the password is correct

type OAuth2User

type OAuth2User interface {
	// PasswordIs matches a string with the stored password.
	// If the stored password is hash, this function will apply to the
	// input before matching.
	PasswordIs(pass string) bool
}

OAuth2User is the generic user interface for OAuth2 login check

type Scopes

type Scopes []string

Scopes represents a list of scope

func ReadScopes

func ReadScopes(str string) (s *Scopes)

ReadScopes read a string and return scopes list

func (*Scopes) Has

func (s *Scopes) Has(search string) bool

Has determine if the scopes list contain the searching scope

func (*Scopes) HasAny

func (s *Scopes) HasAny(searches ...string) bool

HasAny determine if the scopes list contain any of the given scope to search

type Storage

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

Storage implements osin.Storage

func DefaultStorage

func DefaultStorage() (s *Storage)

DefaultStorage returns Storage that attachs to default stores

func (*Storage) Clone

func (storage *Storage) Clone() (c osin.Storage)

Clone implements osin.Storage.Clone

func (*Storage) Close

func (storage *Storage) Close()

Close implements osin.Storage.Close

func (*Storage) GetClient

func (storage *Storage) GetClient(id string) (c osin.Client, err error)

GetClient implements osin.Storage.GetClient

func (*Storage) LoadAccess

func (storage *Storage) LoadAccess(token string) (d *osin.AccessData, err error)

LoadAccess retrieves access data by token. Client information MUST be loaded together. AuthorizeData and AccessData DON'T NEED to be loaded if not easily available. Optionally can return error if expired.

func (*Storage) LoadAuthorize

func (storage *Storage) LoadAuthorize(code string) (d *osin.AuthorizeData, err error)

LoadAuthorize looks up AuthorizeData by a code. Client information MUST be loaded together. Optionally can return error if expired.

func (*Storage) LoadRefresh

func (storage *Storage) LoadRefresh(token string) (d *osin.AccessData, err error)

LoadRefresh retrieves refresh AccessData. Client information MUST be loaded together. AuthorizeData and AccessData DON'T NEED to be loaded if not easily available. Optionally can return error if expired.

func (*Storage) RemoveAccess

func (storage *Storage) RemoveAccess(token string) (err error)

RemoveAccess revokes or deletes an AccessData.

func (*Storage) RemoveAuthorize

func (storage *Storage) RemoveAuthorize(code string) (err error)

RemoveAuthorize revokes or deletes the authorization code.

func (*Storage) RemoveRefresh

func (storage *Storage) RemoveRefresh(token string) (err error)

RemoveRefresh revokes or deletes refresh AccessData.

func (*Storage) SaveAccess

func (storage *Storage) SaveAccess(ad *osin.AccessData) (err error)

SaveAccess writes AccessData. If RefreshToken is not blank, it must save in a way that can be loaded using LoadRefresh.

func (*Storage) SaveAuthorize

func (storage *Storage) SaveAuthorize(d *osin.AuthorizeData) (err error)

SaveAuthorize saves authorize data.

func (*Storage) SetContext

func (storage *Storage) SetContext(ctx context.Context) *Storage

SetContext set the context of the storage clone

type User

type User struct {
	ID       string    `db:"id,omitempty" json:"id"`
	Username string    `db:"username" json:"username"`
	Email    string    `db:"email" json:"email"`
	Password string    `db:"password,omitempty" json:"-"`
	Name     string    `db:"name" json:"name"`
	MetaJSON string    `db:"meta_json" json:"-"`
	Token    string    `db:"token" json:"-"` // token for lost password request
	Created  time.Time `db:"created" json:"created"`
	Updated  time.Time `db:"updated" json:"updated"`
}

User of the API server

func (*User) AddMeta

func (u *User) AddMeta(key, value string)

AddMeta adds Meta value

func (*User) Hash

func (u *User) Hash(password string) string

Hash provide the standard hashing for password

func (User) MarshalDB

func (u User) MarshalDB() (v interface{}, err error)

MarshalDB implement

func (User) MarshalJSON

func (u User) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (User) Meta

func (u User) Meta() (m map[string][]string)

Meta read MetaJSON as map[string][]string

func (*User) PasswordIs

func (u *User) PasswordIs(pass string) bool

PasswordIs matches the hash with database stored password

func (*User) SetPassword

func (u *User) SetPassword(pass string)

SetPassword hashes the input and set to password field

func (*User) UnmarshalJSON

func (u *User) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON implements json.Marshaler

type UserFunc

type UserFunc func(r *http.Request, us store.Store) (u OAuth2User, err error)

UserFunc reads the login form request and returns an OAuth2User for the reqeust. If there is error obtaining the user, an error is returned

func NewUserFunc

func NewUserFunc(idName string) UserFunc

NewUserFunc creates the default parser of login HTTP request

type UserStore

type UserStore struct {
	Db db.Database
	// contains filtered or unexported fields
}

UserStore serves generic CURD for type User Generated by gourd CLI tool

func (*UserStore) AllocEntity

func (s *UserStore) AllocEntity() store.EntityPtr

AllocEntity allocate memory for an entity

func (*UserStore) AllocEntityList

func (s *UserStore) AllocEntityList() store.EntityListPtr

AllocEntityList allocate memory for an entity list

func (*UserStore) Close

func (s *UserStore) Close() error

Close would not close database connection at all. Please use store.CloseAllIn(ctx) to wrap up connections in a context

func (*UserStore) Coll

func (s *UserStore) Coll() (coll db.Collection, err error)

Coll return the raw upper.io collection

func (*UserStore) Create

func (s *UserStore) Create(
	cond store.Conds, ep store.EntityPtr) (err error)

Create a User in the database, of the parent

func (*UserStore) Delete

func (s *UserStore) Delete(
	c store.Conds) (err error)

Delete User on condition(s)

func (*UserStore) Len

func (s *UserStore) Len(pl store.EntityListPtr) int64

Len inspect the length of an entity list

func (*UserStore) One

func (s *UserStore) One(
	c store.Conds, ep store.EntityPtr) (err error)

One returns the first User matches condition(s)

func (*UserStore) Search

func (s *UserStore) Search(
	q store.Query) store.Result

Search a User by its condition(s)

func (*UserStore) SetLogger

func (s *UserStore) SetLogger(logger log.Logger)

SetLogger set the logger fotr the UserStore

func (*UserStore) Update

func (s *UserStore) Update(
	c store.Conds, ep store.EntityPtr) (err error)

Update User on condition(s)

Jump to

Keyboard shortcuts

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