oauth

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2023 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// logged in user id key in session
	LoggedInUserIDKey = "logged_in_user_id"
)

Variables

View Source
var (
	ErrInvalidRequest     = errors.New("invalid_request")
	ErrInvalidCredentials = errors.New("invalid_credentials")
	ErrMethodNotAllowed   = errors.New("method_not_allowed")
	ErrInvalidAccessToken = errors.New("invalid_access_token")
	ErrUnauthorized       = errors.New("unauthorized")
)

Predefined errors

Error codes map

View Source
var ErrorMessages = map[error]string{
	ErrInvalidRequest:     "Invalid request",
	ErrInvalidCredentials: "Invalid credentials",
	ErrMethodNotAllowed:   "Method not allowed",
	ErrInvalidAccessToken: "Missed or invalid access token",
	ErrUnauthorized:       "Unauthorized",

	oauthErrors.ErrInvalidRedirectURI:   "Invalid redirect uri",
	oauthErrors.ErrInvalidAuthorizeCode: "Invalid authorize code",
	oauthErrors.ErrInvalidAccessToken:   "Invalid access token",
	oauthErrors.ErrInvalidRefreshToken:  "Invalid refresh token",
	oauthErrors.ErrExpiredAccessToken:   "Expired access token",
	oauthErrors.ErrExpiredRefreshToken:  "Expired refresh token",
	oauthErrors.ErrMissingCodeVerifier:  "Missing code verifier",
	oauthErrors.ErrMissingCodeChallenge: "Missing code challenge",
	oauthErrors.ErrInvalidCodeChallenge: "Invalid code challenge",
}

Error messages

Functions

func CodeAndMessageFrom added in v0.1.5

func CodeAndMessageFrom(err error) (int, interface{})

CodeAndMessageFrom returns http error code by error type. Returns (0, nil) if error is not found. This function can be used to get error code and message from external packages.

func MakeAuthorizeEndpoint

func MakeAuthorizeEndpoint(s oauth2Server) endpoint.Endpoint

MakeAuthorizeEndpoint returns an endpoint via the passed service.

func MakeHTTPHandler

func MakeHTTPHandler(srv oauth2Server, ts tokenStoreManager, log logger, loginURI string) http.Handler

MakeHTTPHandler returns a handler that makes a set of endpoints available on predefined paths.

func MatchScope

func MatchScope(requiredScope string, allowedScopes string) bool

MatchScopes verifies if the scope is allowed. It returns true if the scope is allowed, false otherwise.

func MatchScopes

func MatchScopes(requiredScopes string, allowedScopes string) bool

MatchScopes verifies if the scope is allowed. It returns true if the scope is allowed, false otherwise.

func MatchScopesStrict

func MatchScopesStrict(requiredScopes string, allowedScopes string) bool

MatchScopesStrict verifies if the all scopes is allowed. It returns true if the scope is allowed, false otherwise.

func NewError

func NewError(err error) *httpencoder.ErrorResponse

NewError creates a new error

func NewOauth2Server

func NewOauth2Server(
	jwtGen oauth2.AccessGenerate,
	codeGen oauth2.AuthorizeGenerate,
	tokenStorage oauth2.TokenStore,
	clientStorage oauth2.ClientStore,
	authHandler Handler,
) (*server.Server, *manage.Manager)

NewOauth2Server initializes the OAuth2 server.

func WithClientScope

func WithClientScope(scope string) handlerOption

WithClientScope sets the default scope for client_credentials grant type

func WithCodeScope

func WithCodeScope(scope string) handlerOption

WithCodeScope sets the default scope for authorization_code grant type

func WithPasswordScope

func WithPasswordScope(scope string) handlerOption

WithPasswordScope sets the default scope for password grant type

Types

type AuthorizeRequest

type AuthorizeRequest struct{}

type Client

type Client struct {
	ID     string `json:"id"`
	Secret string `json:"secret,omitempty"`

	Domain    string    `json:"domain"`
	Public    bool      `json:"is_public"`
	UserID    uuid.UUID `json:"user_id"`
	CreatedAt time.Time `json:"created_at"`
	// contains filtered or unexported fields
}

Client represents an OAuth client implements the oauth2.ClientInfo interface.

func NewClient

func NewClient(source repository.Client, secret string) *Client

NewClient creates a new client instance. The secret is hashed before being stored. Client implements the ClientInfo interface.

func (*Client) GetDomain

func (c *Client) GetDomain() string

GetDomain returns the client domain.

func (*Client) GetID

func (c *Client) GetID() string

GetID returns the client ID.

func (*Client) GetSecret

func (c *Client) GetSecret() string

GetSecret returns the client secret.

func (*Client) GetUserID

func (c *Client) GetUserID() string

GetUserID returns the client user ID.

func (*Client) IsPublic

func (c *Client) IsPublic() bool

IsPublic returns true if the client is public.

func (*Client) VerifyPassword

func (c *Client) VerifyPassword(secret string) bool

VerifyPassword verifies the client secret.

type Endpoints

type Endpoints struct {
	Authorize   endpoint.Endpoint
	Token       endpoint.Endpoint
	RevokeToken endpoint.Endpoint
}

Endpoints collects all of the endpoints that compose a auth service. It's meant to be used as a helper struct, to collect all of the endpoints into a single parameter.

func InitEndpoints

func InitEndpoints(s oauth2Server) Endpoints

Init endpoints for auth service

type Handler

type Handler interface {
	ClientAuthorizedHandler(clientID string, grant oauth2.GrantType) (allowed bool, err error)
	ClientScopeHandler(tgr *oauth2.TokenGenerateRequest) (allowed bool, err error)
	AuthorizeScopeHandler(w http.ResponseWriter, r *http.Request) (scope string, err error)
	RefreshingScopeHandler(tgr *oauth2.TokenGenerateRequest, oldScope string) (allowed bool, err error)
	UserAuthorizationHandler(w http.ResponseWriter, r *http.Request) (userID string, err error)
	PasswordAuthorizationHandler(ctx context.Context, clientID, username, password string) (userID string, err error)
	ExtensionFieldsHandler(ti oauth2.TokenInfo) (fieldsValue map[string]interface{})
	ResponseErrorHandler(re *errors.Response)
	InternalErrorHandler(err error) (re *errors.Response)
}

func NewHandler

func NewHandler(repo handlerRepository, opts ...handlerOption) Handler

NewHandler creates a new oauth2 handler instance.

func NewHandlerLogger

func NewHandlerLogger(h Handler, log oauthLogger) Handler

NewHandlerLogger returns a new handlerLogger.

type IntrospectResponse

type IntrospectResponse struct {
	Active    bool   `json:"active"`
	Scope     string `json:"scope,omitempty"`
	ClientID  string `json:"client_id,omitempty"`
	UserID    string `json:"user_id,omitempty"`
	TokenType string `json:"token_type,omitempty"`
	ExpiresAt int64  `json:"exp,omitempty"`
	IssuedAt  int64  `json:"iat,omitempty"`
	NotBefore int64  `json:"nbf,omitempty"`
	Subject   string `json:"sub,omitempty"`
	Audience  string `json:"aud,omitempty"`
	Issuer    string `json:"iss,omitempty"`
	TokenID   string `json:"jti,omitempty"`
}

type Store

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

func NewStore

func NewStore(repo oauthRepository) *Store

NewStore creates a new store instance. The store is used to manage the client and token information. Implements the interface of the oauth2.ClientStore and oauth2.TokenStore.

func (*Store) Create

func (s *Store) Create(ctx context.Context, info oauth2.TokenInfo) error

create and store the new token information

func (*Store) GetByAccess

func (s *Store) GetByAccess(ctx context.Context, access string) (oauth2.TokenInfo, error)

use the access token for token information data

func (*Store) GetByCode

func (s *Store) GetByCode(ctx context.Context, code string) (oauth2.TokenInfo, error)

use the authorization code for token information data

func (*Store) GetByID

func (s *Store) GetByID(ctx context.Context, id string) (oauth2.ClientInfo, error)

according to the ID for the client information

func (*Store) GetByRefresh

func (s *Store) GetByRefresh(ctx context.Context, refresh string) (oauth2.TokenInfo, error)

use the refresh token for token information data

func (*Store) RemoveByAccess

func (s *Store) RemoveByAccess(ctx context.Context, access string) error

use the access token to delete the token information

func (*Store) RemoveByCode

func (s *Store) RemoveByCode(ctx context.Context, code string) error

delete the authorization code

func (*Store) RemoveByRefresh

func (s *Store) RemoveByRefresh(ctx context.Context, refresh string) error

use the refresh token to delete the token information

type Token

type Token struct {
	ID                  uuid.UUID  `json:"id"`
	ClientID            string     `json:"client_id"`
	UserID              *uuid.UUID `json:"user_id,omitempty"`
	RedirectURI         string     `json:"redirect_uri,omitempty"`
	Scope               string     `json:"scope,omitempty"`
	Code                string     `json:"code,omitempty"`
	CodeCreatedAt       *time.Time `json:"code_created_at,omitempty"`
	CodeExpiresIn       int64      `json:"code_expires_in,omitempty"`
	CodeChallenge       string     `json:"code_challenge,omitempty"`
	CodeChallengeMethod string     `json:"code_challenge_method,omitempty"`
	Access              string     `json:"access,omitempty"`
	AccessCreatedAt     *time.Time `json:"access_created_at,omitempty"`
	AccessExpiresIn     int64      `json:"access_expires_in,omitempty"`
	Refresh             string     `json:"refresh,omitempty"`
	RefreshCreatedAt    *time.Time `json:"refresh_created_at,omitempty"`
	RefreshExpiresIn    int64      `json:"refresh_expires_in,omitempty"`
	CreatedAt           time.Time  `json:"created_at"`
}

Token represents an OAuth token implements the oauth2.TokenInfo interface.

func NewToken

func NewToken(source repository.Token) *Token

NewToken creates a new token instance from a repository token.

func (*Token) GetAccess

func (t *Token) GetAccess() string

func (*Token) GetAccessCreateAt

func (t *Token) GetAccessCreateAt() time.Time

func (*Token) GetAccessExpiresIn

func (t *Token) GetAccessExpiresIn() time.Duration

func (*Token) GetClientID

func (t *Token) GetClientID() string

func (*Token) GetCode

func (t *Token) GetCode() string

func (*Token) GetCodeChallenge

func (t *Token) GetCodeChallenge() string

func (*Token) GetCodeChallengeMethod

func (t *Token) GetCodeChallengeMethod() oauth2.CodeChallengeMethod

func (*Token) GetCodeCreateAt

func (t *Token) GetCodeCreateAt() time.Time

func (*Token) GetCodeExpiresIn

func (t *Token) GetCodeExpiresIn() time.Duration

func (*Token) GetRedirectURI

func (t *Token) GetRedirectURI() string

func (*Token) GetRefresh

func (t *Token) GetRefresh() string

func (*Token) GetRefreshCreateAt

func (t *Token) GetRefreshCreateAt() time.Time

func (*Token) GetRefreshExpiresIn

func (t *Token) GetRefreshExpiresIn() time.Duration

func (*Token) GetScope

func (t *Token) GetScope() string

func (*Token) GetUserID

func (t *Token) GetUserID() string

func (*Token) New

func (t *Token) New() oauth2.TokenInfo

func (*Token) SetAccess

func (t *Token) SetAccess(access string)

func (*Token) SetAccessCreateAt

func (t *Token) SetAccessCreateAt(createdAt time.Time)

func (*Token) SetAccessExpiresIn

func (t *Token) SetAccessExpiresIn(expIn time.Duration)

func (*Token) SetClientID

func (t *Token) SetClientID(id string)

func (*Token) SetCode

func (t *Token) SetCode(code string)

func (*Token) SetCodeChallenge

func (t *Token) SetCodeChallenge(challenge string)

func (*Token) SetCodeChallengeMethod

func (t *Token) SetCodeChallengeMethod(method oauth2.CodeChallengeMethod)

func (*Token) SetCodeCreateAt

func (t *Token) SetCodeCreateAt(createdAt time.Time)

func (*Token) SetCodeExpiresIn

func (t *Token) SetCodeExpiresIn(expIn time.Duration)

func (*Token) SetRedirectURI

func (t *Token) SetRedirectURI(uri string)

func (*Token) SetRefresh

func (t *Token) SetRefresh(refresh string)

func (*Token) SetRefreshCreateAt

func (t *Token) SetRefreshCreateAt(createdAt time.Time)

func (*Token) SetRefreshExpiresIn

func (t *Token) SetRefreshExpiresIn(expIn time.Duration)

func (*Token) SetScope

func (t *Token) SetScope(scope string)

func (*Token) SetUserID

func (t *Token) SetUserID(id string)

Jump to

Keyboard shortcuts

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