auth

package
v0.0.0-...-ae1d368 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2020 License: Apache-2.0 Imports: 13 Imported by: 0

README

Auth

Auth is a simple library for adding known OAuth2 providers along with nonce, session creation and session handling.

Authenticator

The authenticator is the parent of one or more providers which it shares its sessions with. It distributes http handlers for unauthorized and server errors to the provider, as well as handles the storage of the sessions. The store is an implementation of the session-store which by default supports sqlite3 and postgres.

Provider

A provider is simply something that provides a way of authenticating a user and aggregating a Profile based on the available data for the provider. An OAuth2Provider has a corresponding Config object which needs to be filled by various optional fields depending on the provider. The provider also has the job of serving the auth endpoints, ie the OAuth2 callback endpoint. While fully configurable, the defaults allow for most users to just use the sane the providers with minimal configuration.

Configuration

All config objects are primed with the Params library, making it easy to configure your provider by just putting the config in your Params-init.

Documentation

Index

Constants

View Source
const (
	// AuthCookieName is the name of the cookie used to store the session ID
	AuthCookieName = "ee_session"
	// ProfileContextKey is the context key for the active Profile
	ProfileContextKey = "ee_context_profile"
)

Variables

This section is empty.

Functions

func RemoveAuthCookie

func RemoveAuthCookie(w http.ResponseWriter)

Types

type AuthError

type AuthError error

AuthError is an error specific to an error in the OAuth2 or session process

var (
	RedirectURIMismatchError        AuthError = errors.New("The redirect URL provided is a mismatch to the configured OAuth application")
	IncorrectClientCredentialsError AuthError = errors.New("The provided client id or client secret are incorrect")
	BadVerificationCode             AuthError = errors.New("The code passed is either incorrect or expired")
	InvalidScopeError               AuthError = errors.New("The provided scope is not valid for the provider")
	UserAccessDeniedError           AuthError = errors.New("The user denied the authorization request")
	ServerError                     AuthError = errors.New("The provider returned server error")
	TemporarilyUnavailableError     AuthError = errors.New("The provider is temporarily unavailable")

	MissingCodeError  AuthError = errors.New("No access token code in query")
	UnknownStateError AuthError = errors.New("Unknown state variable in query")
	RemoteServerError AuthError = errors.New("Something went wrong during requesting a remote server")

	UnknownMethodError AuthError = errors.New("Method or path not supported")
	PersistStateError  AuthError = errors.New("Failed to persist state in Session")
	StoreError         AuthError = errors.New("Failed to persist profile in DB")

	UnauthorizedError AuthError = errors.New("User is not authorized")
)

type AuthProvider

type AuthProvider string
const (
	AuthGithub  AuthProvider = "github"
	AuthConnect AuthProvider = "connect"
	AuthToken   AuthProvider = "token"
)

type Authenticator

type Authenticator struct {
	Providers []Provider
	// contains filtered or unexported fields
}

Authenticator is the OAuth interface. Create this to enable authentication

func NewAuthenticator

func NewAuthenticator(config AuthenticatorConfig) (*Authenticator, error)

func (*Authenticator) AddProvider

func (a *Authenticator) AddProvider(provider Provider)

AddProvider adds a provider and provisions the provider with the shared sessions store for the authenticator

func (*Authenticator) Profile

func (a *Authenticator) Profile(w http.ResponseWriter, r *http.Request) (Profile, error)

Profile reads the user profile from the http.Request cookie

func (*Authenticator) ServerErrorHandlerFunc

func (a *Authenticator) ServerErrorHandlerFunc(serverErrorFunc func(w http.ResponseWriter, r *http.Request, err AuthError))

ServerErrorHandlerFunc is a handler func for handling server errors which might happen during authentication.

type AuthenticatorConfig

type AuthenticatorConfig struct {
	// DBDriver is the DB driver to be used for persistent sessions. Defaults to sqlite
	DBDriver string `param:"desc=Database driver;options=postgres,sqlite3;default=sqlite3"`
	// DBConnectionString is the connection string for the DB. Defaults to in-memory.
	DBConnectionString string `param:"desc=Database connection string;default=:memory:"`
}

type Profile

type Profile struct {
	// Name of the user
	Name string `json:"name"`
	// PhoneNumber is the phone number of the user
	PhoneNumber string `json:"phone_number"`
	// PhoneNumberVerified tells if the phone number has been verified
	PhoneNumberVerified bool `json:"phone_number_verified"`
	// Email is the email of the user
	Email string `json:"email"`
	// VerfiedEmail tells if the email has been verified
	EmailVerified bool `json:"email_verified"`
	// LoginID is the ID used to uniquely identify the user
	LoginID string `json:"sub"`
	// AvatarURL is the URL to the user avatar
	AvatarURL string `json:"avatar_url"`
	// Provider determines what kind of ID the user is registered with
	Provider AuthProvider `json:"provider"`
	// UserObject is the raw user object retrieved from the Oauth Server
	UserObject interface{} `json:"user"`
}

Profile is the aggregated user which can be created from several different IDs. This in turn means that the Profile have several optional values and needs to be checked if the value is important to your user. The LoginID and Provider is the only fields that are mandatory, but the LoginID is only unique within the Provider.

func (*Profile) Scan

func (p *Profile) Scan(src interface{}) error

Scan implements the sql.Scanner interface

func (*Profile) Value

func (p *Profile) Value() (driver.Value, error)

Value implements the driver.Valuer interface

type Provider

type Provider interface {
	// Enabled tells whether a provider is enabled
	Enabled() bool

	// ServeHTTP adds the different provider endpoints needed for authentication
	ServeHTTP(w http.ResponseWriter, r *http.Request)
	// BasePath is the http base path of the provider
	BasePath() string

	// SetSessions sets the sessions to be used by the provider
	SetSessions(sessions SessionStore)

	// StartSessionChecker will start a go routine to periodically check the sessions for the provider
	// for their validity. Should only be called once.
	StartSessionChecker()

	// SetServerErrorHandleFunc is called with corresponding AuthError when something went wrong
	// during authentication. At this point you must expect the authorization to have
	// failed partially or completely and the user must either try to reauthenticate or the
	// server auth config must be changed
	SetServerErrorHandlerFunc(func(w http.ResponseWriter, r *http.Request, err AuthError))
}

Provider is the provider OAuth interface. Implement this to enable authentication with different providers.

type Session

type Session struct {
	ID          string
	Expires     int64
	AccessToken string
	Profile     Profile
}

Session is the stored session data

type SessionStore

type SessionStore interface {
	// PutState inserts a new state nonce in the storage. The nonce will never expire
	PutState(state string) error

	// RemoveState removes a state nonce from the storage. An error is returned if the
	// nonce does not exist.
	RemoveState(state string) error

	// CreateSession creates a new session in the store. The expires parameter is the expire
	// time in nanonseconds for the session.
	CreateSession(accessToken string, expires int64, profile Profile) (string, error)

	// GetSession returns the session from the session store based on given ID and where expire is higher than provided nanoseconds.
	GetSession(sessionID string, ingnoreOlderNs int64) (Session, error)

	// RemoveSession removes the session from the store.
	RemoveSession(sessionID string) error

	// GetSessions returns sessions with expire time is less than given time in nanoseconds.
	GetSessions(time int64) ([]Session, error)

	// RefreshSession refreshes a session expire time by adding the given nanoseconds.
	RefreshSession(sessionID string, expireAddNs int64) error
}

SessionStore is the interface for the session back-end store.

func NewSQLSessionStore

func NewSQLSessionStore(driver, connectionString string) (SessionStore, error)

NewSQLSessionStore creates a sql-backed session streo

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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