authkit

package
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2016 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package authkit is an attempt to extract oauth2 logic from application so that it would be possible to reuse it in different applications.

Package provides interfaces for app to be implemented to supply them into handler.NewHandler() and middleware.AccessToken(), which return authkit.Handler and echo.MiddlewareFunc, respectively. These two objects are suitable to implement authorization logic in the application. Application will need to setup Echo routes and middleware with methods of returned objects to use them.

Another option, is to reuse any helper from subpackages of package authkit directly in the application's code.

Index

Constants

View Source
const ConfirmEmailTemplateName = "authkit-ConfirmEmail-response.html"

ConfirmEmailTemplateName is a template name for ConfirmEmail response.

Variables

This section is empty.

Functions

func IsDuplicateUser

func IsDuplicateUser(err error) bool

IsDuplicateUser checks whether error is or caused by the DuplicateUserError.

func IsRequestConfirmationError

func IsRequestConfirmationError(err error) bool

IsRequestConfirmationError checks whether error is or caused by the RequestConfirmationError.

func IsUserNotFound

func IsUserNotFound(err error) bool

IsUserNotFound checks whether error is or caused by the UserNotFoundError.

Types

type AuthService

type AuthService interface {
	HandlerAuthService
	TokenValidator
}

AuthService provides a low-level auth implemetation.

type Confirmer

type Confirmer interface {
	// RequestEmailConfirmation requests user to confirm email address.
	RequestEmailConfirmation(login, email, name string) UserServiceError

	// RequestPasswordChangeConfirmation requests user confirmation to change password (via email).
	RequestPasswordChangeConfirmation(login, email, name, passwordHash string) UserServiceError
}

Confirmer provides methods to request confirmations.

type ContextCreator

type ContextCreator interface {

	// CreateContext returns context to be used in http requests to
	// OAuth2 providers. It allows to provide specific settings for different
	// providers. For example, application may switch off TLS for debugging.
	// Application may provide context caching, using providerID as a key.
	// Application may populate context with OAuth2 token from persistent storage.
	CreateContext(providerID string) context.Context
}

ContextCreator used by the Handler to prepare context for http calls.

func NewCustomHTTPClientContextCreator

func NewCustomHTTPClientContextCreator(
	clients map[string]*http.Client) ContextCreator

NewCustomHTTPClientContextCreator returns new CustomHTTPClientContextCreator.

type CustomHTTPClientContextCreator

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

CustomHTTPClientContextCreator used to provide custom http.Client for some of providers. It holds a map of http.Clients for providerIDs. If there is no providerID in the map, then context.Background() returned for this providerID.

func (CustomHTTPClientContextCreator) CreateContext

func (c CustomHTTPClientContextCreator) CreateContext(
	providerID string) context.Context

CreateContext returns context with custom http.Client, if it is provided in the map during CustomHTTPClientContextCreator creation. It returns context.Background() otherwise.

type DefaultContextCreator

type DefaultContextCreator struct{}

DefaultContextCreator returns context.Background().

func (DefaultContextCreator) CreateContext

func (c DefaultContextCreator) CreateContext(string) context.Context

CreateContext returns context.Background().

type DuplicateUserError

type DuplicateUserError interface {
	UserServiceError

	IsDuplicateUser() bool
	// contains filtered or unexported methods
}

DuplicateUserError indicates that user already exists.

func NewDuplicateUserError

func NewDuplicateUserError(cause error) DuplicateUserError

NewDuplicateUserError returns new DuplicateUserError.

type ErrorCustomizer

type ErrorCustomizer interface {
	InvalidRequestParameterError(error) interface{}
	UserCreationError(error) interface{}
	UserAuthenticationError(error) interface{}
}

ErrorCustomizer used to transform low-level errors before render them to http response. It could be used to provide app-specific error code or i18n. Values returned by interface methods are marshalled into response. Note, that with current implementation, JSON marshaller used to marshall errors. Errors may be any structures, not necessary implement error interface. ErrorCustomizer implementation should hide low-level details (stack trace, technical error details) from the end user.

type Handler

type Handler interface {

	// AuthCodeURLs responds with auth code URLs for OAuth2.
	// Handler takes slice of oauth2.Config from configuration supplied
	// to NewHandler() func and renders list of URLs to response body.
	// Web UI could use this request to update its list of providers with
	// fresh URLs (re-generate state query parameter in them).
	// Response should not be cached.
	AuthCodeURLs(echo.Context) error

	// AuthProviders responds with list of OAuth2 providers, configured by the
	// application. Response could be used by web UI to represent a list of
	// providers with names and icons. Response could be cached.
	AuthProviders(echo.Context) error

	// ConsentLogin handles login requests from the consent page.
	ConsentLogin(echo.Context) error

	// Login handles login requests from the application's login page.
	Login(echo.Context) error

	// Logout handles logout requests and revokes access token.
	Logout(echo.Context) error

	// RestorePassword handles request to restore password
	// ("forgot password" link in the login form).
	RestorePassword(echo.Context) error

	// ChangePassword handles request to actually change password from the
	// confirmation form.
	ChangePassword(echo.Context) error

	// ConfirmEmail handles request to confirm email (which is produced
	// by the link sent to the user in the confirmation email).
	// Response for the user created with template named
	// "authkit.EmailConfirm.response". This template should be registered
	// in the echo.Context. I18n can be achieved with custom renderer.
	ConfirmEmail(echo.Context) error

	// SendConfirmationEmail handles request to send confirmation email (email
	// with link to confirm email address). This handler may be used by app to
	// allow user to repeat confirmation email from web UI.
	SendConfirmationEmail(echo.Context) error

	// Callback handles OAuth2 code flow callback requests.
	Callback(echo.Context) error
}

Handler combines http-handlers useful to create login logic.

type HandlerAuthService

type HandlerAuthService interface {

	// GenerateConsentToken returns consent token used to create redirect
	// URL, which is used to redirect to OAuth2 backend from consent page.
	GenerateConsentToken(
		subj string,
		scopes []string,
		challenge string) (string, error)

	// GenerateConsentTokenPriv returns consent token used to create redirect
	// URL, which is used to redirect to OAuth2 backend from web app's own
	// login page (that is suffix "Priv" means "private" or "privileged" use).
	GenerateConsentTokenPriv(
		subj string,
		scopes []string,
		clientID string) (string, error)

	// IssueToken returns a token from OAuth2 backend for own web app
	// in case of form-based login within app.
	// Used for already authorized users.
	IssueToken(login string) (*oauth2.Token, error)

	// RevokeAccessToken revokes access token.
	RevokeAccessToken(accessToken string) error
}

HandlerAuthService provides a low-level auth implemetation, specific to the handler package. Interface is based on Hydra OAuth2 provider and may not fit to be used with another providers, of which we are currently are not aware.

type HandlerUserService

type HandlerUserService interface {
	TokenStore

	Confirmer
	// contains filtered or unexported methods
}

HandlerUserService provides methods to persist user. Methods of this interface are specific to handler package. This interface is a handler's "view" of the UserService, subset of methods, which handler requires from it.

type MiddlewareUserService

type MiddlewareUserService interface {
	TokenStore
	// contains filtered or unexported methods
}

MiddlewareUserService provides methods to persist user. Methods of this interface are specific to middleware package. This interface is a middleware's "view" of the UserService, subset of methods, which middleware requires from it.

type OAuth2Config

type OAuth2Config interface {
	TokenSource(ctx context.Context, t *oauth2.Token) oauth2.TokenSource
	AuthCodeURL(state string, opts ...oauth2.AuthCodeOption) string
	PasswordCredentialsToken(ctx context.Context, username, password string) (*oauth2.Token, error)
	Exchange(ctx context.Context, code string) (*oauth2.Token, error)
	Client(ctx context.Context, t *oauth2.Token) *http.Client
}

OAuth2Config is an interface extracted from the "golang.org/x/oauth2".Config. This interface extracted for testability.

type OAuth2Provider

type OAuth2Provider struct {
	ID           string
	Name         string
	IconURL      string
	OAuth2Config OAuth2Config

	// PrivateOAuth2Config used to access private provider via private network.
	// So, URLs may be accessible only within DMZ, hence different config.
	PrivateOAuth2Config OAuth2Config
}

OAuth2Provider holds OAuth2 provider's configuraton.

type OAuth2State

type OAuth2State struct {
	TokenIssuer  string
	TokenSignKey []byte
	Expiration   time.Duration
}

OAuth2State holds configuration parameters for OAuth2 code flow state token.

type PermissionMapper

type PermissionMapper interface {

	// RequiredPermissioin returns permission descriptor to be passed to
	// TokenValidator. It may return an error to prevent access to resource
	// without request to TokenValidator.
	RequiredPermissioin(method, path string) (interface{}, error)
}

PermissionMapper used to map method and path of http request to desirable permission descriptor. Permission descriptor is an interface, passed to the TokenValidator. For example, in case of Hydra-backed TokenValidator, permission descriptor contains resource name, action and scope.

type Profile

type Profile interface {
	GetLogin() string
	SetLogin(string)
	GetEmail() string
	IsEmailConfirmed() bool
	GetFormattedName() string
}

Profile is an interface representing user's profile (social and local). Actually, it's assumed that application maps social profiles to local ones in the SocialProfileService.

type ProfileService

type ProfileService interface {

	// EnsureExists creates new empty profile if it is not exists already.
	EnsureExists(login, email string) error

	// Save saves profile.
	Save(Profile) error

	// SetEmailConfirmed sets email confirmed flag.
	SetEmailConfirmed(login, email string, confirmed bool) error

	// Email returns (confirmed or not) email address (and user name) by login.
	Email(login string) (email, name string, err error)

	// ConfirmedEmail returns confirmed email address (and user name) by login.
	ConfirmedEmail(login string) (email, name string, err error)
}

ProfileService provides methods to persist user profiles (locally).

type RequestConfirmationError

type RequestConfirmationError interface {
	UserServiceError

	IsRequestConfirmationError() bool
	// contains filtered or unexported methods
}

RequestConfirmationError indicates request confirmation failure.

func NewRequestConfirmationError

func NewRequestConfirmationError(cause error) RequestConfirmationError

NewRequestConfirmationError returns new RequestConfirmationError.

type SocialProfileService

type SocialProfileService interface {
	SocialProfile(client *http.Client) (Profile, error)
}

SocialProfileService allows to retrieve social profile from the social network or other OAuth2 provider and map it to the local user's profile.

type SocialProfileServices

type SocialProfileServices interface {
	SocialProfileService(providerID string) (SocialProfileService, error)
}

SocialProfileServices allows to discover SocialProfileService by provider ID.

type TokenStore

type TokenStore interface {
	// OAuth2Token returns OAuth2 token by login and OAuth2 provider ID.
	OAuth2Token(login, providerID string) (*oauth2.Token, UserServiceError)

	// OAuth2TokenAndLoginByAccessToken returns OAuth2 token and login
	// by accessToken and OAuth2 provider ID.
	OAuth2TokenAndLoginByAccessToken(
		accessToken, providerID string) (*oauth2.Token, string, UserServiceError)

	// UpdateOAuth2Token saves or updates oauth2 token for user and provider.
	UpdateOAuth2Token(login, providerID string, token *oauth2.Token) UserServiceError

	// RevokeAccessToken revokes access token (or, rather, informs store
	// about revoked token, because token should be revoked by call to
	// AuthService).
	RevokeAccessToken(providerID, accessToken string) UserServiceError
}

TokenStore provides methods to persist OAuth2 token in the custom store.

type TokenValidator

type TokenValidator interface {

	// Validate checks if token is valid and has required permission.
	// Valideate returns subject related to provided access token.
	Validate(
		accessToken string,
		permissionDescriptor interface{}) (subj string, err error)
}

TokenValidator used to validate token and to check if token has required permission. TokenValidator works in pair with PermissionMapper. PermissionMapper takes http method and path and converts them to permissionDescriptor, which TokenValidator used to validate token against. Type of permissionDescriptor is specific to application's OAuth2 provider.

type User

type User interface {
	Login() string
	PasswordHash() string
}

User provides basic information about user, required for login logic.

type UserNotFoundError

type UserNotFoundError interface {
	UserServiceError

	IsUserNotFound() bool
	// contains filtered or unexported methods
}

UserNotFoundError indicates that user not found.

func NewUserNotFoundError

func NewUserNotFoundError(cause error) UserNotFoundError

NewUserNotFoundError returns new UserNotFoundError.

type UserService

type UserService interface {
	UserStore
	Confirmer
}

UserService provides methods to persist users and send confirmations.

type UserServiceError

type UserServiceError error

UserServiceError is a general error specific to UserService. It's just an alias for error interface. Application should use subtypes of UserServiceError to return errors form UserService. It may use New...Error functions from this package, or return it's own custom errors. It's important that errors implement right interface, because authorization logic depends on it.

type UserStore

type UserStore interface {
	TokenStore
	// contains filtered or unexported methods
}

UserStore provides methods to persist users. This interface exists for app's convenience, app may choose to implement MiddlewareUserService and HandlerUserService in separate objects.

Directories

Path Synopsis
Package mocks is generated by the mockery tool, except this file, which is used to satisfy glide.
Package mocks is generated by the mockery tool, except this file, which is used to satisfy glide.
peculiarproviders

Jump to

Keyboard shortcuts

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