users

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2024 License: Apache-2.0 Imports: 22 Imported by: 0

README

Clients

Users service provides an HTTP API for managing users. Through this API clients are able to do the following actions:

  • register new accounts
  • login
  • manage account(s) (list, update, delete)

For in-depth explanation of the aforementioned scenarios, as well as thorough understanding of Magistrala, please check out the official documentation.

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
MG_USERS_LOG_LEVEL Log level for users service (debug, info, warn, error) info
MG_USERS_ADMIN_EMAIL Default user, created on startup admin@sponxt.com
MG_USERS_ADMIN_PASSWORD Default user password, created on startup 12345678
MG_USERS_PASS_REGEX Password regex ^.{8,}$
MG_TOKEN_RESET_ENDPOINT Password request reset endpoint, for constructing link /reset-request
MG_USERS_HTTP_HOST Users service HTTP host localhost
MG_USERS_HTTP_PORT Users service HTTP port 9002
MG_USERS_HTTP_SERVER_CERT Path to the PEM encoded server certificate file ""
MG_USERS_HTTP_SERVER_KEY Path to the PEM encoded server key file ""
MG_USERS_HTTP_SERVER_CA_CERTS Path to the PEM encoded server CA certificate file ""
MG_USERS_HTTP_CLIENT_CA_CERTS Path to the PEM encoded client CA certificate file ""
MG_AUTH_GRPC_URL Auth service GRPC URL localhost:8181
MG_AUTH_GRPC_TIMEOUT Auth service GRPC timeout 1s
MG_AUTH_GRPC_CLIENT_CERT Path to the PEM encoded client certificate file ""
MG_AUTH_GRPC_CLIENT_KEY Path to the PEM encoded client key file ""
MG_AUTH_GRPC_SERVER_CA_CERTS Path to the PEM encoded server CA certificate file ""
MG_USERS_DB_HOST Database host address localhost
MG_USERS_DB_PORT Database host port 5432
MG_USERS_DB_USER Database user magistrala
MG_USERS_DB_PASS Database password magistrala
MG_USERS_DB_NAME Name of the database used by the service users
MG_USERS_DB_SSL_MODE Database connection SSL mode (disable, require, verify-ca, verify-full) disable
MG_USERS_DB_SSL_CERT Path to the PEM encoded certificate file ""
MG_USERS_DB_SSL_KEY Path to the PEM encoded key file ""
MG_USERS_DB_SSL_ROOT_CERT Path to the PEM encoded root certificate file ""
MG_EMAIL_HOST Mail server host localhost
MG_EMAIL_PORT Mail server port 25
MG_EMAIL_USERNAME Mail server username ""
MG_EMAIL_PASSWORD Mail server password ""
MG_EMAIL_FROM_ADDRESS Email "from" address ""
MG_EMAIL_FROM_NAME Email "from" name ""
MG_EMAIL_TEMPLATE Email template for sending emails with password reset link email.tmpl
MG_USERS_ES_URL Event store URL nats://localhost:4222
MG_JAEGER_URL Jaeger server URL http://localhost:14268/api/traces
MG_OAUTH_UI_REDIRECT_URL OAuth UI redirect URL http://localhost:9095/domains
MG_OAUTH_UI_ERROR_URL OAuth UI error URL http://localhost:9095/error
MG_USERS_DELETE_INTERVAL Interval for deleting users 24h
MG_USERS_DELETE_AFTER Time after which users are deleted 720h
MG_JAEGER_TRACE_RATIO Jaeger sampling ratio 1.0
MG_SEND_TELEMETRY Send telemetry to magistrala call home server. true
MG_USERS_INSTANCE_ID Magistrala instance ID ""

Deployment

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

To start the service outside of the container, execute the following shell script:

# download the latest version of the service
git clone https://github.com/andychao217/magistrala

cd magistrala

# compile the service
make users

# copy binary to bin
make install

# set the environment variables and run the service
MG_USERS_LOG_LEVEL=info \
MG_USERS_ADMIN_EMAIL=admin@sponxt.com \
MG_USERS_ADMIN_PASSWORD=12345678 \
MG_USERS_PASS_REGEX="^.{8,}$" \
MG_TOKEN_RESET_ENDPOINT="/reset-request" \
MG_USERS_HTTP_HOST=localhost \
MG_USERS_HTTP_PORT=9002 \
MG_USERS_HTTP_SERVER_CERT="" \
MG_USERS_HTTP_SERVER_KEY="" \
MG_USERS_HTTP_SERVER_CA_CERTS="" \
MG_USERS_HTTP_CLIENT_CA_CERTS="" \
MG_AUTH_GRPC_URL=localhost:8181 \
MG_AUTH_GRPC_TIMEOUT=1s \
MG_AUTH_GRPC_CLIENT_CERT="" \
MG_AUTH_GRPC_CLIENT_KEY="" \
MG_AUTH_GRPC_SERVER_CA_CERTS="" \
MG_USERS_DB_HOST=localhost \
MG_USERS_DB_PORT=5432 \
MG_USERS_DB_USER=magistrala \
MG_USERS_DB_PASS=magistrala \
MG_USERS_DB_NAME=users \
MG_USERS_DB_SSL_MODE=disable \
MG_USERS_DB_SSL_CERT="" \
MG_USERS_DB_SSL_KEY="" \
MG_USERS_DB_SSL_ROOT_CERT="" \
MG_EMAIL_HOST=smtp.mailtrap.io \
MG_EMAIL_PORT=2525 \
MG_EMAIL_USERNAME="18bf7f7070513" \
MG_EMAIL_PASSWORD="2b0d302e775b1e" \
MG_EMAIL_FROM_ADDRESS=from@example.com \
MG_EMAIL_FROM_NAME=Example \
MG_EMAIL_TEMPLATE="docker/templates/users.tmpl" \
MG_USERS_ES_URL=nats://localhost:4222 \
MG_JAEGER_URL=http://localhost:14268/api/traces \
MG_JAEGER_TRACE_RATIO=1.0 \
MG_SEND_TELEMETRY=true \
MG_USERS_INSTANCE_ID="" \
$GOBIN/magistrala-users

If MG_EMAIL_TEMPLATE doesn't point to any file service will function but password reset functionality will not work. The email environment variables are used to send emails with password reset link. The service expects a file in Go template format. The template should be something like this.

Setting MG_USERS_HTTP_SERVER_CERT and MG_USERS_HTTP_SERVER_KEY will enable TLS against the service. The service expects a file in PEM format for both the certificate and the key. Setting MG_USERS_HTTP_SERVER_CA_CERTS will enable TLS against the service trusting only those CAs that are provided. The service expects a file in PEM format of trusted CAs. Setting MG_USERS_HTTP_CLIENT_CA_CERTS will enable TLS against the service trusting only those CAs that are provided. The service expects a file in PEM format of trusted CAs.

Setting MG_AUTH_GRPC_CLIENT_CERT and MG_AUTH_GRPC_CLIENT_KEY will enable TLS against the auth service. The service expects a file in PEM format for both the certificate and the key. Setting MG_AUTH_GRPC_SERVER_CA_CERTS will enable TLS against the auth service trusting only those CAs that are provided. The service expects a file in PEM format of trusted CAs.

Usage

For more information about service capabilities and its usage, please check out the API documentation.

Documentation

Overview

Package users contains the domain concept definitions needed to support Magistrala users service functionality.

This package defines the core domain concepts and types necessary to handle users in the context of a Magistrala users service. It abstracts the underlying complexities of user management and provides a structured approach to working with users.

Index

Constants

This section is empty.

Variables

View Source
var CurrentUser = UserInfo{}

Functions

func NewDeleteHandler added in v1.0.1

func NewDeleteHandler(ctx context.Context, clients postgres.Repository, auth magistrala.AuthServiceClient, defCheckInterval, deleteAfter time.Duration, logger *slog.Logger)

Types

type Credentials

type Credentials struct {
	Identity string `json:"identity"`
}

Credentials 结构体表示credentials对象

type Emailer

type Emailer interface {
	// SendPasswordReset sends an email to the user with a link to reset the password.
	SendPasswordReset(To []string, host, user, token 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.
	Compare(string, string) error
}

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

type Service

type Service interface {
	// RegisterClient creates new client. In case of the failed registration, a
	// non-nil error value is returned.
	RegisterClient(ctx context.Context, token string, client clients.Client) (clients.Client, error)

	// ViewClient retrieves client info for a given client ID and an authorized token.
	ViewClient(ctx context.Context, token, id string) (clients.Client, error)

	// ViewProfile retrieves client info for a given token.
	ViewProfile(ctx context.Context, token string) (clients.Client, error)

	// ListClients retrieves clients list for a valid auth token.
	ListClients(ctx context.Context, token string, pm clients.Page) (clients.ClientsPage, error)

	// ListMembers retrieves everything that is assigned to a group/thing identified by objectID.
	ListMembers(ctx context.Context, token, objectKind, objectID string, pm clients.Page) (clients.MembersPage, error)

	// UpdateClient updates the client's name and metadata.
	UpdateClient(ctx context.Context, token string, client clients.Client) (clients.Client, error)

	// UpdateClientTags updates the client's tags.
	UpdateClientTags(ctx context.Context, token string, client clients.Client) (clients.Client, error)

	// UpdateClientIdentity updates the client's identity.
	UpdateClientIdentity(ctx context.Context, token, id, identity string) (clients.Client, error)

	// GenerateResetToken email where mail will be sent.
	// host is used for generating reset link.
	GenerateResetToken(ctx context.Context, email, host string) error

	// UpdateClientSecret updates the client's secret.
	UpdateClientSecret(ctx context.Context, token, oldSecret, newSecret string) (clients.Client, error)

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

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

	// UpdateClientRole updates the client's Role.
	UpdateClientRole(ctx context.Context, token string, client clients.Client) (clients.Client, error)

	// EnableClient logically enableds the client identified with the provided ID.
	EnableClient(ctx context.Context, token, id string) (clients.Client, error)

	// DisableClient logically disables the client identified with the provided ID.
	DisableClient(ctx context.Context, token, id string) (clients.Client, error)

	// DeleteClient deletes client with given ID.
	DeleteClient(ctx context.Context, token, id string) error

	// Identify returns the client id from the given token.
	Identify(ctx context.Context, tkn string) (string, error)

	// IssueToken issues a new access and refresh token.
	IssueToken(ctx context.Context, identity, secret, domainID string) (*magistrala.Token, error)

	// RefreshToken refreshes expired access tokens.
	// After an access token expires, the refresh token is used to get
	// a new pair of access and refresh tokens.
	RefreshToken(ctx context.Context, accessToken, domainID string) (*magistrala.Token, error)

	// OAuthCallback handles the callback from any supported OAuth provider.
	// It processes the OAuth tokens and either signs in or signs up the user based on the provided state.
	OAuthCallback(ctx context.Context, state mgoauth2.State, client clients.Client) (*magistrala.Token, error)
}

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

func NewService

func NewService(crepo postgres.Repository, authClient magistrala.AuthServiceClient, emailer Emailer, hasher Hasher, idp magistrala.IDProvider, selfRegister bool) Service

NewService returns a new Users service implementation.

type TokenResponseBody

type TokenResponseBody struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	AccessType   string `json:"access_type"`
}

type UserInfo

type UserInfo struct {
	Identity string
	Secret   string
}

type UserInfoResponseBody

type UserInfoResponseBody struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	Credentials Credentials            `json:"credentials"`
	Metadata    map[string]interface{} `json:"metadata"`
	CreatedAt   time.Time              `json:"created_at"`
	UpdatedAt   time.Time              `json:"updated_at"`
	UpdatedBy   string                 `json:"updated_by"`
	Status      string                 `json:"status"`
}

UserInfo 结构体表示整个JSON对象

Directories

Path Synopsis
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.
Package emailer contains the domain concept definitions needed to support Magistrala users email service functionality.
Package emailer contains the domain concept definitions needed to support Magistrala users email service functionality.
Package events provides the domain concept definitions needed to support Magistrala users service functionality.
Package events provides the domain concept definitions needed to support Magistrala users service functionality.
Package hasher contains the domain concept definitions needed to support Magistrala users password hasher sub-service functionality.
Package hasher contains the domain concept definitions needed to support Magistrala users password hasher sub-service functionality.
Package mocks contains mocks for testing purposes.
Package mocks contains mocks for testing purposes.
Package postgres contains the database implementation of clients repository layer.
Package postgres contains the database implementation of clients repository layer.
Package tracing provides tracing instrumentation for Magistrala Users service.
Package tracing provides tracing instrumentation for Magistrala Users service.

Jump to

Keyboard shortcuts

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