auth

package
v0.21.6 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2020 License: Apache-2.0 Imports: 18 Imported by: 10

README

Neuron - Auth

This package contains interfaces that defines basic authentication and authorization structures. It also provides basic authentication functions, and PEM file reading helpers.

Documentation

Overview

Package auth contains interfaces that defines basic authentication and authorization structures. It also provides basic authentication functions, and PEM file reading helpers.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrAuth is the account general error.
	ErrAuth = errors.New("Auth")
	// ErrAccountNotFound is the error classification when account is not found.
	ErrAccountNotFound = errors.Wrap(ErrAuth, "account not found")
	// ErrAccountNotValid is the error for invalid accounts.
	ErrAccountNotValid = errors.Wrap(ErrAuth, "account not valid")
	// ErrAccountModelNotDefined is an error that occurs when the account model is not defined.
	ErrAccountModelNotDefined = errors.Wrap(ErrAuth, "account model not defined")
	// ErrAccountAlreadyExists is an error when the account already exists.
	ErrAccountAlreadyExists = errors.Wrap(ErrAuth, "an account with provided username already exists")
	// ErrInternalError is an auth package internal error.
	ErrInternalError = errors.Wrap(errors.ErrInternal, "auth")
	// ErrAuthentication is an error related with authentication.
	ErrAuthentication = errors.Wrap(ErrAuth, "authentication")
	// ErrInvalidUsername is an error for invalid usernames.
	ErrInvalidUsername = errors.Wrap(ErrAuthentication, "invalid username")
	// ErrInvalidPassword is the error classification when provided secret is not valid.
	ErrInvalidPassword = errors.Wrap(ErrAuthentication, "provided invalid secret")
	// ErrNoRequiredOption is the error classification while there is no required option.
	ErrNoRequiredOption = errors.Wrap(ErrAuthentication, "provided no required option")
	// ErrInitialization is the error classification while initializing the structures.
	ErrInitialization = errors.New("auth initialization failed")
	// ErrInvalidSecret is an error for initialization invalid secret.
	ErrInvalidSecret = errors.Wrap(ErrInitialization, "invalid secret")
	// ErrInvalidRSAKey is an error for initialization with an invalid RSA key.
	ErrInvalidRSAKey = errors.Wrap(ErrInitialization, "invalid RSA key")
	// ErrInvalidECDSAKey is an error for initialization with an invalid ECDSA key.
	ErrInvalidECDSAKey = errors.Wrap(ErrInitialization, "invalid ECDSA key")
	// ErrToken is the error for invalid token.
	ErrToken = errors.Wrap(ErrAuthentication, "invalid token")
	// ErrTokenRevoked is the error for invalid token.
	ErrTokenRevoked = errors.Wrap(ErrToken, "revoked")
	// ErrTokenExpired is an error related to expired token.
	ErrTokenExpired = errors.Wrap(ErrToken, "expired")
	// ErrTokenNotValidYet is an error related to the token that is not valid yet.
	ErrTokenNotValidYet = errors.Wrap(ErrToken, "not valid yet")
)
View Source
var (
	// ErrAuthorization is the major authorization errors.
	ErrAuthorization = errors.Wrap(ErrAuth, "authorization")
	// ErrAuthorizationScope is an error related to the authorization scope.
	ErrAuthorizationScope = errors.Wrap(ErrAuthorization, "scope")
	// ErrAuthorizationHeader is an error related to authorization header.
	ErrAuthorizationHeader = errors.Wrap(ErrAuthorization, "header")
	// ErrForbidden is the error classification when authorization fails.
	ErrForbidden = errors.Wrap(ErrAuthorization, "forbidden")
	// ErrInvalidRole is the error classification when the role is not valid.
	ErrInvalidRole = errors.Wrap(ErrAuthorization, "invalid role")
	// ErrRoleAlreadyGranted is the error when the role is already granted.
	ErrRoleAlreadyGranted = errors.Wrap(ErrAuthorization, "role already granter")
)

Functions

func CompareHashPassword added in v0.17.0

func CompareHashPassword(h hash.Hash, password string, hashedPassword, salt []byte) (bool, error)

CompareHashPassword compares if provided password matches the sha512 hashed password with given salt.

func CompareMD5Password added in v0.17.0

func CompareMD5Password(password string, hashedPassword, salt []byte) (bool, error)

CompareMD5Password compares if provided password matches the md5 hashed password with given salt.

func CompareSHA256Password added in v0.17.0

func CompareSHA256Password(password string, hashedPassword, salt []byte) (bool, error)

CompareSHA256Password compares if provided password matches the sha256 hashed password with given salt.

func CompareSHA512Password added in v0.17.0

func CompareSHA512Password(password string, hashedPassword, salt []byte) (bool, error)

CompareSHA512Password compares if provided password matches the sha512 hashed password with given salt.

func CtxWithAccount added in v0.17.0

func CtxWithAccount(ctx context.Context, account Account) context.Context

CtxWithAccount stores account in the context.

func DefaultPasswordScorer added in v0.17.0

func DefaultPasswordScorer(pw *Password)

DefaultPasswordScorer is the default scoring function for the password.

func DefaultPasswordValidator added in v0.17.0

func DefaultPasswordValidator(p *Password) error

DefaultPasswordValidator is the default password validator function.

func DefaultUsernameValidator added in v0.17.0

func DefaultUsernameValidator(username string) error

DefaultUsernameValidator is the default username validator function.

func GenerateSalt added in v0.17.0

func GenerateSalt(saltLength int) ([]byte, error)

GenerateSalt creates a crypto random byte slice salt.

func ParsePemECDSAPrivateKey added in v0.17.0

func ParsePemECDSAPrivateKey(key []byte) (*ecdsa.PrivateKey, error)

ParsePemECDSAPrivateKey parses 'pem' encoded 'ecdsa.PrivateKey'

func ParsePemRsaPrivateKey added in v0.17.0

func ParsePemRsaPrivateKey(pemPrivateKey []byte) (*rsa.PrivateKey, error)

ParsePemRsaPrivateKey parses 'pem' encoded 'rsa.PrivateKey'.

Types

type AccessClaims added in v0.17.0

type AccessClaims interface {
	// GetAccount gets the account stored in given token.
	GetAccount() Account
	Claims
}

AccessClaims is an interface used for the access token claims. It should store the whole user account.

type Account added in v0.17.0

type Account interface {
	mapping.Model
	// GetUsername gets the current account username.
	GetUsername() string
	// SetUsername sets the account username.
	SetUsername(username string)
	// GetPasswordHash sets the password hash for the account.
	GetPasswordHash() []byte
	// SetPasswordHash sets the password hash for given account.
	SetPasswordHash(hash []byte)
	// UsernameField gets the account username field name.
	UsernameField() string
	// PasswordHashField gets the hashed password field name.
	PasswordHashField() string
}

Account is an interface for the authenticate account models. It needs to get/set username and password.

func CtxGetAccount added in v0.17.0

func CtxGetAccount(ctx context.Context) (Account, bool)

CtxGetAccount gets the account from the context 'ctx'

type Audiencer added in v0.18.0

type Audiencer interface {
	Audience() string
}

Audiencer is an interface that allows to get token's optional audience value.

type AuthenticateMethod added in v0.17.0

type AuthenticateMethod int

AuthenticateMethod is a method of authentication used by the authenticator

const (
	// BCrypt is a bcrypt password hashing method
	BCrypt AuthenticateMethod = iota
	// MD5 is a md5 password hashing method.
	MD5
	// SHA256 is a sha256 password hashing method.
	SHA256
	// SHA512 is a sha512 password hashing method.
	SHA512
)

type Authenticator

type Authenticator interface {
	// HashAndSetPassword creates a password hash and stores it within given account.
	// If a model implements SaltSetter this function should set the salt also.
	HashAndSetPassword(account Account, password *Password) error
	// ComparePassword hash the 'password' (with optional salt) and compare with stored password hash.
	ComparePassword(account Account, password string) error
}

Authenticator is the interface used to authenticate the username and password.

type AuthenticatorOption added in v0.17.0

type AuthenticatorOption func(o *AuthenticatorOptions)

AuthenticatorOption is a function used to set authentication options.

func AuthenticatorBCryptCost added in v0.17.0

func AuthenticatorBCryptCost(op int) AuthenticatorOption

AuthenticatorBCryptCost is an option that sets BCryptCost in the auth options.

func AuthenticatorMethod added in v0.17.0

func AuthenticatorMethod(op AuthenticateMethod) AuthenticatorOption

AuthenticatorMethod is an option that sets AuthenticateMethod in the auth options.

func AuthenticatorSaltLength added in v0.17.0

func AuthenticatorSaltLength(op int) AuthenticatorOption

AuthenticatorSaltLength is an option that sets SaltLength in the auth options.

func AuthenticatorStore added in v0.17.0

func AuthenticatorStore(op store.Store) AuthenticatorOption

AuthenticatorStore is an option that sets Store in the option.

type AuthenticatorOptions added in v0.17.0

type AuthenticatorOptions struct {
	// Store is a store used for some authenticator implementations.
	Store store.Store
	// BCryptCost is an option that defines the cost of given password.
	BCryptCost int
	// AuthenticateMethod is a method used for authentication.
	AuthenticateMethod AuthenticateMethod
	// SaltLength is the length of the salt.
	SaltLength int
}

AuthenticatorOptions are the authentication service options.

type Claims added in v0.17.0

type Claims interface {
	// Subject should contain account id string value.
	Subject() string
	// ExpiresIn should define when (in seconds) the claims will expire.
	ExpiresIn() int64
	// Valid validates the claims.
	Valid() error
}

Claims is an interface used for the tokens.

type HierarchicalRole added in v0.17.0

type HierarchicalRole interface {
	Role
	HierarchyValue() int
}

HierarchicalRole is an interface for the

type Issuer added in v0.18.0

type Issuer interface {
	Issuer() string
}

Issuer is an interface that allows to get the token issuer.

type ListRoleOption added in v0.17.0

type ListRoleOption func(o *ListRoleOptions)

ListRoleOption is the option

type ListRoleOptions added in v0.17.0

type ListRoleOptions struct {
	SortByHierarchy bool
	SortOrder       query.SortOrder
	Limit, Offset   int
	Account         Account
}

ListRoleOptions are the options for listing the roles.

type ListScopeOption added in v0.17.0

type ListScopeOption func(o *ListScopeOptions)

ListScopeOption is an option function that changes list scope options.

type ListScopeOptions added in v0.17.0

type ListScopeOptions struct {
	Limit, Offset int
	Role          Role
}

ListScopeOptions are the options used for listing the

type NotBeforer added in v0.18.0

type NotBeforer interface {
	NotBefore() int64
}

NotBeforer is an interface that allows to get Token's NotBefore (nbf) value.

type Password added in v0.17.0

type Password struct {
	// Password is the string value of the provided password.
	Password string
	// Uppers is a count of the uppercase letters.
	Uppers int
	// Lowers is a count of the lowercase letters.
	Lowers int
	// Specials is a count of special symbols.
	Specials int
	// Numbers is a count of numbers in the password.
	Numbers int
	// UniqueRunes is the number of unique runes int
	UniqueRunes int
	// Score is a password strength score.
	Score int
}

Password is a structure that defines the password and its properties.

func NewPassword added in v0.17.0

func NewPassword(password string, scorer ...PasswordScorer) *Password

NewPassword creates and analyze the 'password' using provided (optional) scorer function. If no 'scorer' is provided than the 'DefaultPasswordScorer' would be used.

func (*Password) Hash added in v0.17.0

func (p *Password) Hash(h hash.Hash, salt []byte) ([]byte, error)

Hash gets the password hash with salted with 'salt'.

func (*Password) MD5 added in v0.17.0

func (p *Password) MD5(salt []byte) (password []byte, err error)

MD5 creates salted hash password using MD5 function.

func (*Password) SHA256 added in v0.17.0

func (p *Password) SHA256(salt []byte) ([]byte, error)

SHA256 creates salted hash password using SHA256 function.

func (*Password) SHA512 added in v0.17.0

func (p *Password) SHA512(salt []byte) ([]byte, error)

SHA512 creates salted hash password using SHA512 function.

func (*Password) UniqueRunesRatio added in v0.17.0

func (p *Password) UniqueRunesRatio() float64

UniqueRunesRatio gets the ratio of unique runes to the total password length.

type PasswordScorer added in v0.17.0

type PasswordScorer func(pw *Password)

PasswordScorer is a function that sets the score for given password.

type PasswordValidator added in v0.17.0

type PasswordValidator func(*Password) error

PasswordValidator is a function that validates the password.

type Role

type Role interface {
	RoleName() string
}

Role is the interface used for the roles.

type RoleScoper added in v0.17.0

type RoleScoper interface {
	// ListRoleScopes lists the scopes for provided options.
	ListRoleScopes(ctx context.Context, options ...ListScopeOption) ([]Scope, error)
	// ClearRoleScopes clears the scopes for provided roles/accounts.
	ClearRoleScopes(ctx context.Context, roles ...Role) error
	// GrantRoleScope grants roles/accounts access for given scope.
	GrantRoleScope(ctx context.Context, role Role, scope Scope) error
	// RevokeRoleScope revokes the roles/accounts access for given scope.
	RevokeRoleScope(ctx context.Context, role Role, scope Scope) error
}

RoleScoper is an interface for authorizators that allows to set and get scopes.

type Roler added in v0.17.0

type Roler interface {
	// FindRoles list all roles for
	FindRoles(ctx context.Context, options ...ListRoleOption) ([]Role, error)
	// ClearRoles clears all roles for given account.
	ClearRoles(ctx context.Context, account Account) error
	// GrantRole grants given 'role' access to given 'scope'.
	GrantRole(ctx context.Context, account Account, role Role) error
	// RevokeRole revokes access to given 'scope' for the 'role'.
	RevokeRole(ctx context.Context, account Account, role Role) error
}

Roler is the role-based access control authorization.

type SaltFielder added in v0.17.0

type SaltFielder interface {
	SaltField() string
}

SaltFielder is an interface that gets the salt field name for given account.

type SaltGetter added in v0.17.0

type SaltGetter interface {
	GetSalt() []byte
}

SaltGetter is an interface for Account that could get it's stored salt value.

type SaltSetter added in v0.17.0

type SaltSetter interface {
	SetSalt(salt []byte)
}

SaltSetter is an interface for Account that sets it's salt field value.

type Salter added in v0.18.0

type Salter interface {
	SaltFielder
	SaltSetter
	SaltGetter
}

Salter is an interface for accounts that has the 'salt' field.

type Scope

type Scope interface {
	ScopeName() string
}

Scope is an interface that defines authorization scope.

type Scoper added in v0.18.0

type Scoper interface {
	Scope() string
}

Scoper is an interface that allows to get Token's authorization scope value. This should return all of the scopes for which the token is authorized, space separated.

type SigningMethod added in v0.17.0

type SigningMethod interface {
	Verify(signingString, signature string, key interface{}) error
	Sign(signingString string, key interface{}) (string, error)
	Alg() string
}

SigningMethod is an interface used for signing and verify the string. This interface is equal to the Signing method of github.com/dgrijalva/jwt-go.

type Token

type Token struct {
	// AccessToken is the string access token.
	AccessToken string
	// RefreshToken defines the token.
	RefreshToken string
	// ExpiresIn defines the expiration time for given access token.
	ExpiresIn int
	// TokenType defines the token type.
	TokenType string
}

Token is the authorization token structure.

type TokenOption

type TokenOption func(o *TokenOptions)

TokenOption is the token options changer function.

func TokenExpirationTime

func TokenExpirationTime(d time.Duration) TokenOption

TokenExpirationTime sets the expiration time for the token.

func TokenRefreshExpirationTime added in v0.17.0

func TokenRefreshExpirationTime(d time.Duration) TokenOption

TokenRefreshExpirationTime sets the expiration time for the token.

func TokenRefreshToken

func TokenRefreshToken(refreshToken string) TokenOption

TokenRefreshToken sets the refresh token for the token creation.

func TokenScope added in v0.18.0

func TokenScope(scope string) TokenOption

TokenScope sets the space separated scopes where the token should have an access.

func TokenWithAudience added in v0.18.0

func TokenWithAudience(audience string) TokenOption

TokenWithAudience sets the token audience.

func TokenWithIssuer added in v0.18.0

func TokenWithIssuer(issuer string) TokenOption

TokenWithIssuer is the token option that sets up the issuer.

func TokenWithNotBefore added in v0.18.0

func TokenWithNotBefore(notBefore time.Time) TokenOption

TokenWithNotBefore is the token option that sets up the not before option.

type TokenOptions

type TokenOptions struct {
	// ExpirationTime is the expiration time of the token.
	ExpirationTime time.Duration
	// RefreshExpirationTime is the expiration time for refresh token
	RefreshExpirationTime time.Duration
	// RefreshToken is the optional refresh token used on token creation, when the refresh token is still valid (optional).
	RefreshToken string

	// Optional settings.
	//
	// Scope contains space separated authorization scopes that the token is available for (optional).
	Scope string
	// Audience is the audience of the token.
	Audience string
	// Issuer is the token issuer name.
	Issuer string
	// NotBefore is an option that sets the token to be valid not before provided time.
	NotBefore time.Time
}

TokenOptions is the options used to create the token.

type Tokener

type Tokener interface {
	// InspectToken extracts claims from the token.
	InspectToken(ctx context.Context, token string) (claims Claims, err error)
	// Token creates the token for provided options.
	Token(ctx context.Context, account Account, options ...TokenOption) (Token, error)
	// RevokeToken revokes provided 'token'
	RevokeToken(ctx context.Context, token string) error
}

Tokener is the interface used for the authorization with the token.

type TokenerOption added in v0.17.0

type TokenerOption func(o *TokenerOptions)

TokenerOption is a function that sets the TokenerOptions.

func TokenerAccount added in v0.21.3

func TokenerAccount(model Account) TokenerOption

TokenerAccount sets the account for the tokener.

func TokenerEcdsaPrivateKey added in v0.17.0

func TokenerEcdsaPrivateKey(key *ecdsa.PrivateKey) TokenerOption

TokenerEcdsaPrivateKey is an option that sets EcdsaPrivateKey in the auth options.

func TokenerRefreshTokenExpiration added in v0.17.0

func TokenerRefreshTokenExpiration(op time.Duration) TokenerOption

TokenerRefreshTokenExpiration is an option that sets RefreshTokenExpiration in the auth options.

func TokenerRsaPrivateKey added in v0.17.0

func TokenerRsaPrivateKey(key *rsa.PrivateKey) TokenerOption

TokenerRsaPrivateKey is an option that sets RsaPrivateKey in the auth options.

func TokenerSecret added in v0.17.0

func TokenerSecret(secret []byte) TokenerOption

TokenerSecret is an option that sets Secret in the auth options.

func TokenerSigningMethod added in v0.17.0

func TokenerSigningMethod(op SigningMethod) TokenerOption

TokenerSigningMethod is an option that sets SigningMethod in the auth options.

func TokenerStore added in v0.18.0

func TokenerStore(s store.Store) TokenerOption

TokenerStore sets the store for the tokener.

func TokenerTimeFunc added in v0.21.3

func TokenerTimeFunc(tf func() time.Time) TokenerOption

TokenerTimeFunc sets the default time function for the tokener.

func TokenerTokenExpiration added in v0.17.0

func TokenerTokenExpiration(op time.Duration) TokenerOption

TokenerTokenExpiration is an option that sets TokenExpiration in the auth options.

type TokenerOptions added in v0.17.0

type TokenerOptions struct {
	// Model is the account model used by the tokener.
	Model Account
	// Store is a store used for some authenticator implementations.
	Store store.Store
	// Secret is the authorization secret.
	Secret []byte
	// RsaPrivateKey is used for encoding the token using RSA methods.
	RsaPrivateKey *rsa.PrivateKey
	// EcdsaPrivateKey is used for encoding the token using ECDSA methods.
	EcdsaPrivateKey *ecdsa.PrivateKey
	// TokenExpiration is the default token expiration time.
	TokenExpiration time.Duration
	// RefreshTokenExpiration is the default refresh token expiration time,.
	RefreshTokenExpiration time.Duration
	// SigningMethod is the token signing method.
	SigningMethod SigningMethod
	// TimeFunc sets the time function for given tokener.
	TimeFunc func() time.Time
}

TokenerOptions are the options that defines the settings for the Tokener.

type UsernameValidator added in v0.17.0

type UsernameValidator func(username string) error

UsernameValidator is a function used to validate the username for the account.

type Verifier added in v0.17.0

type Verifier interface {
	// Authorize if the is allowed to access the resource. The resourceID is a unique resource identifier.
	Verify(ctx context.Context, account Account, options ...VerifyOption) error
}

Verifier is the interface used to authorize resources.

type VerifyOption added in v0.17.0

type VerifyOption func(o *VerifyOptions)

VerifyOption is an option used for the verification.

func VerifyAllowedRoles added in v0.17.0

func VerifyAllowedRoles(allowedRoles ...Role) VerifyOption

VerifyAllowedRoles sets allowed roles for the verify options.

func VerifyDisallowedRoles added in v0.17.0

func VerifyDisallowedRoles(disallowedRoles ...Role) VerifyOption

VerifyDisallowedRoles sets disallowed roles for the verify options.

func VerifyScopes added in v0.17.0

func VerifyScopes(scopes ...Scope) VerifyOption

VerifyScopes sets the verify options scopes.

type VerifyOptions added in v0.17.0

type VerifyOptions struct {
	AllowedRoles    []Role
	DisallowedRoles []Role
	Scopes          []Scope
}

VerifyOptions is the structure contains authorize query options.

Jump to

Keyboard shortcuts

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