users

package
v0.46.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 23 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Users Service

The Users service manages user accounts, authentication, and platform-level access control. It provides multiple registration flows, JWT-based token issuance, OAuth integration, and a platform invite system for onboarding new users into organizations and groups.

Configuration

The service is configured using the environment variables presented in the following table. Note that any unset variables will be replaced with their default values.

Variable Description Default
MF_USERS_LOG_LEVEL Log level for Users (debug, info, warn, error) error
MF_USERS_DB_HOST Database host address localhost
MF_USERS_DB_PORT Database host port 5432
MF_USERS_DB_USER Database user mainflux
MF_USERS_DB_PASS Database password mainflux
MF_USERS_DB Name of the database used by the service users
MF_USERS_DB_SSL_MODE Database connection SSL mode (disable, require, verify-ca, verify-full) disable
MF_USERS_DB_SSL_CERT Path to the PEM encoded certificate file
MF_USERS_DB_SSL_KEY Path to the PEM encoded key file
MF_USERS_DB_SSL_ROOT_CERT Path to the PEM encoded root certificate file
MF_USERS_HTTP_PORT Users service HTTP port 8180
MF_USERS_GRPC_PORT Users service gRPC port (used by Auth service) 8184
MF_USERS_SERVER_CERT Path to server certificate in PEM format
MF_USERS_SERVER_KEY Path to server key in PEM format
MF_USERS_PLATFORM_OWNER_EMAIL Default platform owner user email, created on startup
MF_USERS_PLATFORM_OWNER_PASSWORD Default platform owner user password, created on startup
MF_USERS_PASS_MIN_LENGTH Minimum password length in characters, between 8 and 128 15
MF_USERS_SELF_REGISTER_ENABLED Allow users to self-register. If false, only admins can create accounts true
MF_AUTH_GRPC_URL Auth service gRPC URL localhost:8181
MF_AUTH_GRPC_TIMEOUT Auth service gRPC request timeout 1s
MF_AUTH_CLIENT_TLS Enable TLS for Auth gRPC connection false
MF_AUTH_CA_CERTS Path to trusted CAs in PEM format for Auth gRPC TLS
MF_JAEGER_URL Jaeger server URL for distributed tracing. Leave empty to disable tracing.
MF_EMAIL_HOST Mail server host localhost
MF_EMAIL_PORT Mail server port 25
MF_EMAIL_USERNAME Mail server username
MF_EMAIL_PASSWORD Mail server password
MF_EMAIL_FROM_ADDRESS Email "from" address
MF_EMAIL_FROM_NAME Email "from" name
MF_EMAIL_TEMPLATES_DIR Path to the directory containing email templates .
MF_HOST Frontend URL base included in user-facing emails http://localhost
MF_REQUIRE_EMAIL_VERIFICATION Whether email verification is required during self-registration false
MF_INVITE_DURATION Validity duration of created Platform Invites 168h
MF_REDIRECT_LOGIN_URL Path appended to MF_HOST for post-OAuth login redirects
MF_USERS_ES_URL Event store (Redis) URL redis://localhost:6379/0
MF_USERS_ES_STREAM_MAXLEN Approximate maximum number of entries kept in the event stream 100000
MF_USERS_ES_BUFFER_SIZE Capacity of the in-memory buffer for events awaiting publishing 10000
MF_GOOGLE_CLIENT_ID Google OAuth application client ID
MF_GOOGLE_CLIENT_SECRET Google OAuth application client secret
MF_GOOGLE_REDIRECT_URL Google OAuth callback path (appended to MF_HOST)
MF_GOOGLE_USER_INFO Google API endpoint for fetching user profile
MF_GITHUB_CLIENT_ID GitHub OAuth application client ID
MF_GITHUB_CLIENT_SECRET GitHub OAuth application client secret
MF_GITHUB_REDIRECT_URL GitHub OAuth callback path (appended to MF_HOST)
MF_GITHUB_USER_INFO GitHub API endpoint for fetching user profile
MF_GITHUB_USER_EMAILS GitHub API endpoint for fetching user email addresses
MF_OIDC_ISSUER_URL OIDC issuer URL used for discovery; empty disables the oidc provider
MF_OIDC_CLIENT_ID OIDC client ID
MF_OIDC_CLIENT_SECRET OIDC client secret
MF_OIDC_REDIRECT_URL OIDC callback path (appended to MF_HOST)

Note: If MF_EMAIL_TEMPLATES_DIR does not point to a valid directory containing the required templates, the service will start normally but email-based features (email verification, platform invites) will not work.

Password policy

Passwords are checked on registration, self-registration, platform invite registration, password change and password reset. Login does not apply the policy, so existing passwords keep working.

  • The password is normalized to Unicode NFKC before validation and hashing.
  • Length is at least MF_USERS_PASS_MIN_LENGTH and at most 128 characters, counted in Unicode code points.
  • All characters are allowed, including spaces, symbols and Unicode. There are no uppercase, digit or special character requirements.
  • The password must not be on the NCSC list of the 100,000 most used passwords, compared case-insensitively.
  • The password must not contain the local part of the user's e-mail address, compared case-insensitively, when the local part has at least 3 characters.

MF_USERS_PLATFORM_OWNER_PASSWORD must meet the policy, otherwise the service fails to start.

Passwords are hashed with Argon2id (19 MiB of memory, 2 iterations, parallelism 1) and stored in PHC string format. Passwords hashed with bcrypt by earlier versions keep working: on the next successful login, the bcrypt hash is replaced with an Argon2id hash.

Deployment

The service itself is distributed as Docker container. Check the users service section in docker-compose to see how service is deployed.

To start the service, execute the following shell script:

# Download the latest version of the service
git clone https://github.com/MainfluxLabs/mainflux

cd mainflux

# compile the users service
make users

# Copy binary to bin
make install

# Set the environment variables and run the service
MF_USERS_LOG_LEVEL=[Users log level] \
MF_USERS_DB_HOST=[Database host address] \
MF_USERS_DB_PORT=[Database host port] \
MF_USERS_DB_USER=[Database user] \
MF_USERS_DB_PASS=[Database password] \
MF_USERS_DB=[Name of the database used by the service] \
MF_USERS_HTTP_PORT=[Service HTTP port] \
MF_JAEGER_URL=[Jaeger server URL] \
MF_EMAIL_HOST=[Mail server host] \
MF_EMAIL_PORT=[Mail server port] \
MF_EMAIL_USERNAME=[Mail server username] \
MF_EMAIL_PASSWORD=[Mail server password] \
MF_EMAIL_FROM_ADDRESS=[Email from address] \
MF_EMAIL_FROM_NAME=[Email from name] \
$GOBIN/mainfluxlabs-users

Usage

For the full HTTP API reference, see the OpenAPI specification.

Documentation

Index

Constants

View Source
const (
	UserTypeInvitee = "invitee"
	UserTypeInviter = "inviter"

	InviteStatePending  = "pending"
	InviteStateExpired  = "expired"
	InviteStateRevoked  = "revoked"
	InviteStateAccepted = "accepted"
	InviteStateDeclined = "declined"
)
View Source
const (
	// MinPasswordLength is the lowest allowed value of the configured minimum password length.
	MinPasswordLength = 8
	// MaxPasswordLength is the maximum password length in Unicode code points.
	MaxPasswordLength = 128
)
View Source
const (
	EnabledStatusKey  = domain.EnabledStatusKey
	DisabledStatusKey = domain.DisabledStatusKey
	AllStatusKey      = domain.AllStatusKey
	GoogleProvider    = "google"
	GitHubProvider    = "github"
	OIDCProvider      = "oidc"
)

Variables

View Source
var (
	// ErrPasswordTooShort indicates that the password is shorter than the minimum length.
	ErrPasswordTooShort = errors.New("password is too short")

	// ErrPasswordTooLong indicates that the password is longer than the maximum length.
	ErrPasswordTooLong = errors.New("password is too long")

	// ErrCommonPassword indicates that the password is on the list of common passwords.
	ErrCommonPassword = errors.New("password is too common")

	// ErrPasswordContainsEmail indicates that the password contains the user's e-mail local part.
	ErrPasswordContainsEmail = errors.New("password must not contain the e-mail address")
)
View Source
var (
	// ErrRecoveryToken indicates error in generating password recovery token.
	ErrRecoveryToken = errors.New("failed to generate password recovery token")

	// ErrAlreadyEnabledUser indicates the user is already enabled.
	ErrAlreadyEnabledUser = errors.New("the user is already enabled")

	// ErrAlreadyDisabledUser indicates the user is already disabled.
	ErrAlreadyDisabledUser = errors.New("the user is already disabled")

	// ErrEmailVerificationExpired indicates that the e-mail verification token has expired.
	ErrEmailVerificationExpired = errors.New("e-mail verification token expired")

	// ErrSelfRegisterDisabled indicates that self-registration is disabled in the service config.
	ErrSelfRegisterDisabled = errors.New("self register disabled")

	// ErrInvalidPlatformOwnerCredentials indicates that the configured platform owner e-mail
	// or password is invalid.
	ErrInvalidPlatformOwnerCredentials = errors.New("invalid platform owner e-mail or password")

	// ErrEmailNotVerified indicates that the identity provider did not verify the user e-mail.
	ErrEmailNotVerified = errors.New("e-mail not verified by identity provider")

	// ErrPlatformRoleAssigned indicates that the user already has a platform role.
	ErrPlatformRoleAssigned = errors.New("the user already has a platform role")

	// ErrNotPlatformAdmin indicates that the user does not have the platform admin role.
	ErrNotPlatformAdmin = errors.New("the user does not have the platform admin role")

	// ErrDisabledUser indicates that the operation is not allowed for a disabled user.
	ErrDisabledUser = errors.New("the user is disabled")
)
View Source
var ErrUnsupportedHash = errors.New("unsupported hash format")

ErrUnsupportedHash indicates that the hash was not created by the hasher.

View Source
var PlatformInviteOrderFields = map[string]string{
	"id":            "id",
	"invitee_email": "LOWER(invitee_email)",
	"state":         "state",
	"created_at":    "created_at",
}

PlatformInviteOrderFields maps API-facing order keys to SQL column expressions for the platform_invites table.

Functions

func NormalizePassword added in v0.46.0

func NormalizePassword(password string) string

NormalizePassword returns the password in Unicode NFKC form, used for validation and hashing.

func ValidatePassword added in v0.46.0

func ValidatePassword(password, email string, minLength int) error

ValidatePassword returns an error if the password does not meet the password policy.

Types

type Config added in v0.38.0

type Config struct {
	InviteDuration      time.Duration
	EmailVerifyEnabled  bool
	SelfRegisterEnabled bool
	GoogleOAuth         oauth2.Config
	GitHubOAuth         oauth2.Config
	OIDC                OIDCConfig
	URLs                ConfigURLs
	PassMinLength       int
}

Config holds configuration values for the users service.

type ConfigURLs added in v0.38.0

type ConfigURLs struct {
	GoogleUserInfoURL   string
	GitHubUserInfoURL   string
	GitHubUserEmailsURL string
	RedirectLoginURL    string
}

type EmailVerification added in v0.29.0

type EmailVerification struct {
	User      User
	Token     string
	CreatedAt time.Time
	ExpiresAt time.Time
}

type EmailVerificationRepository added in v0.29.0

type EmailVerificationRepository interface {
	// Save persists the EmailVerification.
	Save(ctx context.Context, verification EmailVerification) (string, error)

	// RetrieveByToken retrieves an EmailVerification based on its token.
	RetrieveByToken(ctx context.Context, token string) (EmailVerification, error)

	// Remove removes an EmailVerification from the database.
	Remove(ctx context.Context, token string) error
}

type Emailer

type Emailer interface {
	SendPasswordReset(To []string, redirectPath, token string) error
	SendEmailVerification(To []string, redirectPath, token string) error
	SendPlatformInvite(to []string, inv PlatformInvite, redirectPath string) error
}

Emailer wrapper around the email

type Hasher

type Hasher interface {
	// Hash generates the hashed string from plain-text.
	Hash(string) (string, error)

	// Compare compares plain-text version to the hashed one. An error should
	// indicate failed comparison. ErrUnsupportedHash is returned if the
	// hash was not created by this hasher.
	Compare(string, string) error
}

Hasher specifies an API for generating hashes of an arbitrary textual content.

type Identity added in v0.38.0

type Identity struct {
	UserID         string
	Provider       string
	ProviderUserID string
}

type IdentityRepository added in v0.38.0

type IdentityRepository interface {
	// Save persists an OAuth identity.
	Save(ctx context.Context, identity Identity) error

	// Retrieve fetches an OAuth identity by provider and provider user ID.
	Retrieve(ctx context.Context, provider, providerUserID string) (Identity, error)

	// BackupAll retrieves all OAuth identities.
	BackupAll(ctx context.Context) ([]Identity, error)
}

type Metadata

type Metadata = domain.Metadata

Domain type aliases

type OAuthCallbackData added in v0.38.0

type OAuthCallbackData struct {
	Provider     string
	Code         string
	Verifier     string
	InviteID     string
	RedirectPath string
}

type OAuthCallbackResult added in v0.46.0

type OAuthCallbackResult struct {
	RedirectURL string
	User        User
	// Registered reports whether the callback created the user.
	Registered bool
}

OAuthCallbackResult is the outcome of an OAuth callback.

type OAuthLoginData added in v0.38.0

type OAuthLoginData struct {
	State       string
	Verifier    string
	RedirectURL string
}

type OIDCConfig added in v0.46.0

type OIDCConfig struct {
	IssuerURL string
	OAuth     oauth2.Config
}

OIDCConfig holds configuration of a generic OpenID Connect provider. The OAuth endpoints are resolved from the issuer's discovery document, so OAuth.Endpoint is ignored.

type PageMetadata

type PageMetadata = domain.UsersPageMetadata

type PlatformInvite added in v0.30.0

type PlatformInvite = domain.PlatformInvite

Domain type aliases

type PlatformInvites added in v0.30.0

type PlatformInvites interface {
	// CreatePlatformInvite creates a pending platform Invite for the appropriate email address.
	// The user can optionally also be invited to an Organization with a certain role by supplying the `orgInvite` argument - the invite
	// becomes visible once the user completes registration via the platform invite.
	// temp:orgid, role, gis
	CreatePlatformInvite(ctx context.Context, token, redirectPath, email string, orgInvite domain.OrgInvite) (PlatformInvite, error)

	// RevokePlatformInvite revokes a specific pending PlatformInvite.
	// Only usable by the Platform Owner or a Platform Admin.
	RevokePlatformInvite(ctx context.Context, token, inviteID string) error

	// ViewPlatformInvite retrieves a single PlatformInvite denoted by its ID.
	// This endpoint is public - the invite UUID acts as the access secret.
	ViewPlatformInvite(ctx context.Context, inviteID string) (PlatformInvite, error)

	// ListPlatformInvites retrieves a list of platform invites.
	// Only usable by the Platform Owner or a Platform Admin.
	ListPlatformInvites(ctx context.Context, token string, pm PageMetadata) (PlatformInvitesPage, error)

	// ValidatePlatformInvite checks if there exists a valid, pending, non-expired platform invite in the database that matches
	// the passed ID and user e-mail. If so, it marks that invite's state as 'accepted', and returns nil.
	// If no such valid platform invite is found in the database, it instead returns errors.ErrAuthorization.
	ValidatePlatformInvite(ctx context.Context, inviteID, email string) error

	// SendPlatformInviteEmail sends an e-mail notifying the invitee about the corresponding platform invite.
	SendPlatformInviteEmail(ctx context.Context, invite PlatformInvite, redirectPath string) error
}

type PlatformInvitesPage added in v0.30.0

type PlatformInvitesPage = domain.PlatformInvitesPage

Domain type aliases

type PlatformInvitesRepository added in v0.30.0

type PlatformInvitesRepository interface {
	// SavePlatformInvite saves one or more pending platform invites to the repository.
	SavePlatformInvite(ctx context.Context, invites ...PlatformInvite) error

	// RetrievePlatformInviteByID retrieves a single platform invite by its ID.
	RetrievePlatformInviteByID(ctx context.Context, inviteID string) (PlatformInvite, error)

	// RetrievePlatformInvites retrieves a list of platform invites.
	RetrievePlatformInvites(ctx context.Context, pm PageMetadata) (PlatformInvitesPage, error)

	// UpdatePlatformInviteState updates the state of a specific platform invite denoted by its ID.
	UpdatePlatformInviteState(ctx context.Context, inviteID, state string) error
}

type Service

type Service interface {
	// SelfRegister carries out the first stage of own account registration: it
	// creates a pending e-mail verification entity and sends the user an e-mail
	// with a URL containing a token used to verify the e-mail address and complete
	// registration.
	SelfRegister(ctx context.Context, user User, redirectPath string) (string, error)

	// VerifyEmail completes the self-registration process by matching the provided
	// email verification token against the database. If the token is valid and not expired, the e-mail
	// is considered verified a new User is fully registered.
	// Returns the ID of the newly-registered User upon success.
	VerifyEmail(ctx context.Context, confirmationToken string) (string, error)

	// RegisterByInvite performs user registration based on a platform invite.
	// inviteID must correspond to a valid, pending and non-expired platform invite, and the user's supplied
	// e-mail address must match the e-mail address of that platform invite. Upon success, marks the associated
	// invite's state as 'accepted'. Returns the ID of the newly registered user.
	RegisterByInvite(ctx context.Context, user User, inviteID, orgInviteRedirectPath string) (string, error)

	// Register creates new user account. In case of the failed registration, a
	// non-nil error value is returned. The user registration is only allowed
	// for admin.
	Register(ctx context.Context, token string, user User) (string, error)

	// RegisterPlatformOwner creates the platform owner account, validating e-mail and password on creation.
	// Existing user with given e-mail is assigned the platform owner role and password is ignored.
	RegisterPlatformOwner(ctx context.Context, user User) error

	// Login authenticates the user given its credentials. Successful
	// authentication generates new access token. Failed invocations are
	// identified by the non-nil error values in the response.
	Login(ctx context.Context, user User) (string, error)

	// RefreshToken issues a new access token to the bearer of a still-valid one,
	// extending the session without re-sending credentials.
	RefreshToken(ctx context.Context, token string) (string, error)

	// OAuthLogin returns the URL to initiate OAuth login.
	OAuthLogin(provider string) (data OAuthLoginData, err error)

	// OAuthCallback exchanges the OAuth code for user info and logs in/creates the user.
	OAuthCallback(ctx context.Context, data OAuthCallbackData) (OAuthCallbackResult, error)

	// ViewUser retrieves user info for a given user ID and an authorized token.
	ViewUser(ctx context.Context, token, id string) (User, error)

	// ViewProfile retrieves user info for a given token.
	ViewProfile(ctx context.Context, token string) (User, error)

	// ListUsers retrieves users list for a valid admin token.
	ListUsers(ctx context.Context, token string, pm PageMetadata) (UsersPage, error)

	// ListUsersByIDs retrieves users list for the given IDs.
	ListUsersByIDs(ctx context.Context, ids []string, pm PageMetadata) (UsersPage, error)

	// ListUsersByEmails retrieves users list for the given emails.
	ListUsersByEmails(ctx context.Context, emails []string) ([]User, error)

	// UpdateUser updates the user metadata.
	UpdateUser(ctx context.Context, token string, user User) error

	// GenerateResetToken email where mail will be sent.
	GenerateResetToken(ctx context.Context, email, redirectPath string) error

	// ChangePassword change users password for authenticated user.
	ChangePassword(ctx context.Context, token, email, password, oldPassword string) error

	// ResetPassword change users password in reset flow.
	// token can be authentication token or password reset token.
	ResetPassword(ctx context.Context, resetToken, password string) error

	// SendPasswordReset sends reset password link to email.
	SendPasswordReset(ctx context.Context, redirectPath, email, token string) error

	// EnableUser logically enables the user identified with the provided ID
	EnableUser(ctx context.Context, token, id string) error

	// DisableUser logically disables the user identified with the provided ID
	DisableUser(ctx context.Context, token, id string) error

	// Impersonate issues a login token for the user identified with the provided ID,
	// on behalf of the platform admin identified by the provided token.
	// Only the platform owner is allowed to impersonate a platform admin.
	Impersonate(ctx context.Context, token, id string) (string, error)

	// AssignAdminRole assigns the platform admin role to the user with the provided ID.
	// Only the platform owner is allowed to assign it.
	AssignAdminRole(ctx context.Context, token, id string) error

	// UnassignAdminRole unassigns the platform admin role from the user with the provided ID.
	// Only the platform owner is allowed to unassign it.
	UnassignAdminRole(ctx context.Context, token, id string) error

	// Backup returns the platform owner, all users, and all OAuth identities.
	// Only accessible by the platform owner.
	Backup(ctx context.Context, token string) (User, []User, []Identity, error)

	// Restore restores users and OAuth identities from backup.
	// Only accessible by the platform owner.
	Restore(ctx context.Context, token string, platformOwner User, users []User, identities []Identity) error

	PlatformInvites
}

Service specifies an API that must be fulfilled by the domain service implementation, and all of its decorators (e.g. logging & metrics).

func New

func New(users UserRepository, verifications EmailVerificationRepository, invites PlatformInvitesRepository, identity IdentityRepository, hasher, legacyHasher Hasher, auth domain.AuthClient, e Emailer, idp uuid.IDProvider, logger logger.Logger, c Config) Service

New instantiates the users service implementation

type User

type User = domain.User

Domain type aliases

type UserRepository

type UserRepository interface {
	// Save persists the user account. A non-nil error is returned to indicate
	// operation failure.
	Save(ctx context.Context, u User) (string, error)

	// Update updates the user.
	Update(ctx context.Context, u User) error

	// UpdateUserMetadata updates the user metadata.
	UpdateUserMetadata(ctx context.Context, u User) error

	// RetrieveByEmail retrieves user by its unique identifier (i.e. email).
	RetrieveByEmail(ctx context.Context, email string) (User, error)

	// RetrieveByID retrieves user by its unique identifier ID.
	RetrieveByID(ctx context.Context, id string) (User, error)

	// RetrieveByIDs retrieves all users for given array of userIDs.
	RetrieveByIDs(ctx context.Context, userIDs []string, pm PageMetadata) (UsersPage, error)

	// UpdatePassword updates password for user with given email
	UpdatePassword(ctx context.Context, email, password string) error

	// ChangeStatus changes users status to enabled or disabled
	ChangeStatus(ctx context.Context, id, status string) error

	// BackupAll retrieves all users.
	BackupAll(ctx context.Context) ([]User, error)
}

UserRepository specifies an account persistence API.

type UsersPage added in v0.39.0

type UsersPage = domain.UsersPage

Domain type aliases

Directories

Path Synopsis
api
Package api contains API-related concerns: endpoint definitions, middlewares and all resource representations.
Package api contains API-related concerns: endpoint definitions, middlewares and all resource representations.
grpc
Package grpc contains implementation of users service gRPC API.
Package grpc contains implementation of users service gRPC API.
http
Package http contains implementation of users service HTTP API.
Package http contains implementation of users service HTTP API.
Package argon2 provides a hasher implementation utilizing Argon2id.
Package argon2 provides a hasher implementation utilizing Argon2id.
Package bcrypt provides a hasher implementation utilizing bcrypt.
Package bcrypt provides a hasher implementation utilizing bcrypt.
Package postgres contains repository implementations using PostgreSQL as the underlying database.
Package postgres contains repository implementations using PostgreSQL as the underlying database.
Package redis contains the event store middleware that publishes users service events to Redis Streams.
Package redis contains the event store middleware that publishes users service events to Redis Streams.
Package tracing contains middlewares that will add spans to existing traces.
Package tracing contains middlewares that will add spans to existing traces.

Jump to

Keyboard shortcuts

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