auth

package module
v0.0.0-...-726ff5c Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: MIT Imports: 26 Imported by: 0

README

auth

Auth module for the Modulus framework

Documentation

Index

Constants

View Source
const TagUnauthenticated = "unauthenticated"
View Source
const TagUnauthorized = "unauthorized"

Variables

View Source
var ErrCannotCreateAccessToken = errors.New("cannot create access token")
View Source
var ErrCannotCreateRefreshToken = errors.New("cannot create refresh token")
View Source
var ErrCannotHashPassword = errors.New("cannot hash password")
View Source
var ErrIdentityIsBlocked = errors.New("identity is blocked")
View Source
var ErrInvalidIdentity = errors.New("invalid identity")
View Source
var ErrInvalidPassword = errors.New("invalid password")
View Source
var ErrInvalidToken = translation.WithDomain(
	erruser.New("invalid access token", "Please provide a valid access token"),
	locales.Domain,
)
View Source
var ErrTokenIsExpired = errors.New("token is expired")
View Source
var ErrTokenIsRevoked = errors.New("token is revoked")
View Source
var ErrUnauthenticated = translation.WithDomain(
	errors.WithAddedTags(
		erruser.New("unauthenticated", localize.Singular("Please authenticate to get access to this resource")),
		TagUnauthenticated,
	), locales.Domain,
)
View Source
var ErrUnauthorized = translation.WithDomain(
	errors.WithAddedTags(
		erruser.New("unauthorized", "You are not authorized to access this resource"),
		TagUnauthorized,
	),
	locales.Domain,
)

Functions

func AddHttpCode

func AddHttpCode() errhttp.ErrorProcessor

func GetPerformerID

func GetPerformerID(ctx context.Context) uuid.UUID

func GetRefreshToken

func GetRefreshToken(ctx context.Context) string

func NewManifesto

func NewManifesto() module.Manifesto

func NewModule

func NewModule(options ...module.Option) *module.Module

NewModule creates a new module for the auth package. It works with the default storage implementation. It uses pgxpool for database connection.

If you want to use a custom identity storage implementation, you should implement the IdentityRepository interface and call authModule := auth.OverrideIdentityRepository(auth.NewModule(), NewYourIdentityRepositoryImplementation). The same is for other storage implementations if you need it.

func OverrideAccountRepository

func OverrideAccountRepository[T repository.AccountRepository](authModule *module.Module) *module.Module

OverrideAccountRepository overrides the default account storage implementation with the custom one. repository should be a constructor returning the implementation of the AccountRepository interface.

func OverrideCredentialRepository

func OverrideCredentialRepository[T repository.CredentialRepository](authModule *module.Module) *module.Module

OverrideCredentialRepository overrides the default credential storage implementation with the custom one. repository should be a constructor returning the implementation of the CredentialRepository interface.

func OverrideIdentityRepository

func OverrideIdentityRepository[T repository.IdentityRepository](authModule *module.Module) *module.Module

OverrideIdentityRepository overrides the default identity storage implementation with the custom one. repository should be a constructor returning the implementation of the IdentityRepository interface.

func OverrideMiddlewareAuthenticator

func OverrideMiddlewareAuthenticator[T Authenticator](authModule *module.Module) *module.Module

OverrideMiddlewareAuthenticator overrides the default middleware authenticator with the custom one. authenticator should be a constructor returning the implementation of the Authenticator interface.

func OverrideResetPasswordRequestRepository

func OverrideResetPasswordRequestRepository[T repository.ResetPasswordRequestRepository](authModule *module.Module) *module.Module

OverrideResetPasswordRequestRepository overrides the default reset password request storage implementation with the custom one.

func OverrideTokenHashStrategy

func OverrideTokenHashStrategy[T hash.TokenHashStrategy](authModule *module.Module) *module.Module

OverrideTokenHashStrategy overrides the default token hash strategy with the custom one. strategy should be a constructor returning the implementation of the hash.TokenHashStrategy interface. by default, the sha1 hash strategy is used. if you don't want to hash tokens, you can set the strategy to none, like this auth.OverrideTokenHashStrategy[*hash.None](authModule)

func OverrideTokenRepository

func OverrideTokenRepository[T repository.TokenRepository](authModule *module.Module) *module.Module

OverrideTokenRepository overrides the default token storage implementation with the custom one. repository should be a constructor returning the implementation of the TokenRepository interface.

func RemoveRefreshToken

func RemoveRefreshToken(ctx context.Context)

func SendRefreshToken

func SendRefreshToken(ctx context.Context, token string)

func WithPerformer

func WithPerformer(ctx context.Context, performer Performer) context.Context

func WithRefreshToken

func WithRefreshToken(ctx context.Context, refreshToken string) context.Context

Types

type Authenticator

type Authenticator interface {
	// Authenticate authenticates the user with the given token.
	// It returns the performer of the authenticated user.
	//
	// Errors:
	// * github.com/go-modulus/auth.ErrTokenIsRevoked - if the token is revoked.
	// * github.com/go-modulus/auth.ErrTokenIsExpired - if the token is expired.
	Authenticate(ctx context.Context, token string) (Performer, error)
}

type Middleware

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

func NewMiddleware

func NewMiddleware(
	authenticator Authenticator,
	config *MiddlewareConfig,
	errorPipeline *errhttp.ErrorPipeline,
) *Middleware

func (*Middleware) HttpMiddleware

func (a *Middleware) HttpMiddleware() func(http.Handler) http.Handler

func (*Middleware) Middleware

func (a *Middleware) Middleware(next http.Handler) errhttp.Handler

type MiddlewareConfig

type MiddlewareConfig struct {
	RefreshTokenConfig
}

func NewMiddlewareConfig

func NewMiddlewareConfig() (*MiddlewareConfig, error)

type ModuleConfig

type ModuleConfig struct {
	AccessTokenTTL  time.Duration `env:"AUTH_ACCESS_TOKEN_TTL, default=1h"`
	RefreshTokenTTL time.Duration `env:"AUTH_REFRESH_TOKEN_TTL, default=720h"`
}

type PasswordAuthenticator

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

func NewPasswordAuthenticator

func NewPasswordAuthenticator(
	accountRepository repository.AccountRepository,
	identityRepository repository.IdentityRepository,
	credentialRepository repository.CredentialRepository,
) *PasswordAuthenticator

func (*PasswordAuthenticator) Authenticate

func (a *PasswordAuthenticator) Authenticate(ctx context.Context, identity, password string) (Performer, error)

Authenticate authenticates the user with the given identity and password. It returns the performer of the authenticated user.

Errors: * github.com/go-modulus/auth.ErrIdentityIsBlocked - if the identity is blocked. * github.com/go-modulus/auth.ErrInvalidPassword - if the password is invalid. * github.com/go-modulus/auth.ErrInvalidIdentity - if identity is not found in the repository.

func (*PasswordAuthenticator) Register

func (a *PasswordAuthenticator) Register(
	ctx context.Context,
	identity,
	password string,
	identityType repository.IdentityType,
	roles []string,
	userInfo map[string]interface{},
) (repository.Account, error)

Register registers a new user account with the given identity and password. In the userInfo, you can pass any additional data you want to store (e.g. IP, unregistered user token from frontend, name, date of birth, etc.). It returns the performer of the registered user.

Errors: * github.com/go-modulus/auth.ErrIdentityExists - if you try to register a user for the same identity. * github.com/go-modulus/auth.ErrIdentityIsBlocked - if the identity exists in the storage, and it has status blocked. * Any error from the IdentityRepository.Create method. * Any error from the CredentialRepository.Create method.

func (*PasswordAuthenticator) RemoveIdentity

func (a *PasswordAuthenticator) RemoveIdentity(ctx context.Context, identity string) error

type Performer

type Performer struct {
	ID         uuid.UUID
	SessionID  uuid.UUID
	Roles      []string
	IdentityID uuid.UUID
}

func GetPerformer

func GetPerformer(ctx context.Context) Performer

type PlainTokenAuthenticator

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

func NewPlainTokenAuthenticator

func NewPlainTokenAuthenticator(
	accountRepository repository.AccountRepository,
	tokenRepository repository.TokenRepository,
	identityRepository repository.IdentityRepository,
	config ModuleConfig,
) *PlainTokenAuthenticator

func (*PlainTokenAuthenticator) Authenticate

func (a *PlainTokenAuthenticator) Authenticate(ctx context.Context, token string) (Performer, error)

Authenticate authenticates the user with the given token. It returns the performer of the authenticated user.

Errors: * github.com/go-modulus/auth.ErrTokenIsRevoked - if the token is revoked. * github.com/go-modulus/auth.ErrTokenIsExpired - if the token is expired.

func (*PlainTokenAuthenticator) IssueNewAccessToken

func (a *PlainTokenAuthenticator) IssueNewAccessToken(
	ctx context.Context,
	refreshToken string,
	additionalData map[string]interface{},
) (repository.AccessToken, error)

IssueNewAccessToken issues the new access token linking it to the session from the given refresh token. It returns a new access token. Refresh token is not revoked. Old access token is not revoked. The session is not changed.

Errors: * ErrTokenIsRevoked - if the refresh token is revoked. * ErrTokenIsExpired - if the refresh token expired. * ErrCannotCreateAccessToken - if the access token cannot be created. * ErrCannotCreateRefreshToken - if the refresh token cannot be created.

func (*PlainTokenAuthenticator) IssueTokens

func (a *PlainTokenAuthenticator) IssueTokens(
	ctx context.Context,
	identityID uuid.UUID,
	additionalData map[string]interface{},
) (TokenPair, error)

IssueTokens starts a new session for the given performer. It means creation the new pair of access and refresh tokens without revoking any existing tokens. It returns an access token and a refresh token.

The additionalData parameter is used to store additional data in the access token. For example, you can store the IP address of the user.

Errors: * ErrCannotCreateAccessToken - if the access token cannot be created. * ErrCannotCreateRefreshToken - if the refresh token cannot be created. * repository.ErrIdentityNotFound - if the identity does not exist. * repository.ErrCannotCreateAccessToken - if there are some issues with DB to create a token * repository.ErrCannotCreateRefreshToken - if there are some issues with DB to create a token

func (*PlainTokenAuthenticator) RefreshAccessToken

func (a *PlainTokenAuthenticator) RefreshAccessToken(
	ctx context.Context,
	refreshToken string,
	additionalData map[string]interface{},
	expirationLag time.Duration,
) (repository.AccessToken, error)

RefreshAccessToken refreshes the access token with the given refresh token. It returns a new access token. Refresh token is not revoked. Old access token expires. The session is not changed.

Errors: * ErrTokenIsRevoked - if the refresh token is revoked. * ErrTokenIsExpired - if the refresh token expired. * ErrCannotCreateAccessToken - if the access token cannot be created. * ErrCannotCreateRefreshToken - if the refresh token cannot be created.

type RefreshTokenConfig

type RefreshTokenConfig struct {
	CookieName   string        `env:"REFRESH_TOKEN_COOKIE_NAME, default=art"`
	CookieDomain string        `env:"REFRESH_TOKEN_COOKIE_DOMAIN, default=localhost"`
	CookieSecure bool          `env:"REFRESH_TOKEN_COOKIE_SECURE, default=false"`
	TTL          time.Duration `env:"AUTH_REFRESH_TOKEN_TTL, default=8760h"`
}

type TokenPair

type TokenPair struct {
	AccessToken  repository.AccessToken
	RefreshToken repository.RefreshToken
}

Jump to

Keyboard shortcuts

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