services

package
v0.0.0-...-a58f9c2 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2025 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidLogin         = errors.New("invalid email or password")
	ErrUserBlocked          = errors.New("user account is blocked due to too many failed login attempts")
	ErrUserInactive         = errors.New("user account is inactive")
	ErrInvalidToken         = errors.New("invalid or expired token")
	ErrTooManyRequests      = errors.New("too many requests, please try again later")
	ErrEmailNotFound        = errors.New("no user found with this email")
	ErrPhoneNotFound        = errors.New("no user found with this phone number")
	ErrPasswordTooWeak      = errors.New("password is too weak")
	ErrPasswordConfirmation = errors.New("password and confirmation do not match")
)

Erros do serviço de autenticação

View Source
var (
	ErrSendingEmail     = errors.New("error sending email")
	ErrSendingSMS       = errors.New("error sending SMS")
	ErrSendingWhatsApp  = errors.New("error sending WhatsApp message")
	ErrInvalidTemplate  = errors.New("invalid template")
	ErrProviderNotFound = errors.New("notification provider not found")
)

Common errors for notification services

Functions

This section is empty.

Types

type AuthConfig

type AuthConfig struct {
	// Limite de tentativas de login
	MaxLoginAttempts int
	// Tempo para bloqueio após exceder tentativas de login
	LoginLockDuration time.Duration
	// Limite de tokens de recuperação de senha por período
	ResetTokenRateLimit int
	// Período para verificação de rate limit
	ResetTokenRateWindow time.Duration
	// Tempo de expiração de token de recuperação via email
	ResetTokenEmailExpiration time.Duration
	// Tempo de expiração de token de recuperação via SMS/WhatsApp
	ResetTokenSMSExpiration time.Duration
}

AuthConfig contém as configurações para o serviço de autenticação

func DefaultAuthConfig

func DefaultAuthConfig() AuthConfig

DefaultAuthConfig retorna uma configuração padrão para o serviço de autenticação

type AuthService

type AuthService struct {
	UserRepo        repositories.UserRepository
	TokenRepo       repositories.TokenRepositoryInterface
	PasswordUtil    *utils.PasswordUtil
	JWTUtil         *utils.JWTUtil
	EmailService    EmailServiceInterface
	SMSService      SMSServiceInterface
	WhatsAppService WhatsAppServiceInterface
	Config          AuthConfig
}

AuthService implementa os serviços de autenticação

func NewAuthService

func NewAuthService(
	userRepo repositories.UserRepository,
	tokenRepo repositories.TokenRepositoryInterface,
	passwordUtil *utils.PasswordUtil,
	jwtUtil *utils.JWTUtil,
	emailService EmailServiceInterface,
	smsService SMSServiceInterface,
	whatsAppService WhatsAppServiceInterface,
	config AuthConfig,
) *AuthService

NewAuthService cria uma nova instância do serviço de autenticação

func (*AuthService) ExtractTokenFromRequest

func (s *AuthService) ExtractTokenFromRequest(r *http.Request) string

ExtractTokenFromRequest extrai o token JWT do cabecalho de Authorization

func (*AuthService) ForgotPasswordEmail

func (s *AuthService) ForgotPasswordEmail(req ForgotPasswordRequest) error

ForgotPasswordEmail inicia o processo de recuperação de senha via email

func (*AuthService) ForgotPasswordSMS

func (s *AuthService) ForgotPasswordSMS(req ForgotPasswordRequest) error

ForgotPasswordSMS inicia o processo de recuperação de senha via SMS

func (*AuthService) ForgotPasswordWhatsApp

func (s *AuthService) ForgotPasswordWhatsApp(req ForgotPasswordRequest) error

ForgotPasswordWhatsApp inicia o processo de recuperação de senha via WhatsApp

func (*AuthService) GetUserFromToken

func (s *AuthService) GetUserFromToken(tokenString string) (*models.User, error)

GetUserFromToken obtem os dados do usuario a partir de um token JWT

func (*AuthService) Login

func (s *AuthService) Login(req LoginRequest) (*models.User, *TokenResponse, error)

Login realiza o login de um usuário

func (*AuthService) RefreshToken

func (s *AuthService) RefreshToken(req RefreshTokenRequest) (*TokenResponse, error)

RefreshToken renova o token de acesso usando um refresh token

func (*AuthService) Register

func (s *AuthService) Register(req RegisterRequest) (*models.User, error)

Register registra um novo usuário

func (*AuthService) ResetPassword

func (s *AuthService) ResetPassword(req ResetPasswordRequest) error

ResetPassword redefine a senha de um usuário usando o token de recuperação

func (*AuthService) ValidateResetToken

func (s *AuthService) ValidateResetToken(token string) error

ValidateResetToken valida um token de recuperação de senha

type EmailConfig

type EmailConfig struct {
	Host         string
	Port         int
	Username     string
	Password     string
	FromEmail    string
	FromName     string
	TemplatesDir string
	IsSMTP       bool
	ServiceType  string // "smtp", "sendgrid", "aws_ses"
	APIKey       string // For SendGrid or other API-based services
}

EmailConfig contains the settings for the email service

type EmailService

type EmailService struct {
	Config EmailConfig
}

EmailService implements the EmailServiceInterface

func (*EmailService) SendGenericEmail

func (s *EmailService) SendGenericEmail(email, subject, body string) error

SendGenericEmail sends a generic email

func (*EmailService) SendPasswordResetEmail

func (s *EmailService) SendPasswordResetEmail(email, name, token string) error

SendPasswordResetEmail sends a password reset email

type EmailServiceInterface

type EmailServiceInterface interface {
	SendPasswordResetEmail(email, name, token string) error
	SendGenericEmail(email, subject, body string) error
}

EmailServiceInterface defines the interface for the email service

func NewEmailService

func NewEmailService(config EmailConfig) EmailServiceInterface

NewEmailService creates a new instance of the email service

type ForgotPasswordRequest

type ForgotPasswordRequest struct {
	Email     string `json:"email" validate:"omitempty,email"`
	Phone     string `json:"phone,omitempty" validate:"omitempty,phone"`
	ClientIP  string `json:"client_ip" validate:"required"`
	UserAgent string
}

ForgotPasswordRequest representa os dados de requisição para solicitação de recuperação de senha

type LoginRequest

type LoginRequest struct {
	Email    string `json:"email" validate:"required,email"`
	Password string `json:"password" validate:"required"`
}

LoginRequest representa os dados de requisição para login

type RefreshTokenRequest

type RefreshTokenRequest struct {
	RefreshToken string `json:"refresh_token" validate:"required"`
}

RefreshTokenRequest representa os dados de requisição para refresh token

type RegisterRequest

type RegisterRequest struct {
	Name            string          `json:"name" validate:"required"`
	Email           string          `json:"email" validate:"required,email"`
	Phone           string          `json:"phone" validate:"required"`
	Password        string          `json:"password" validate:"required"`
	ConfirmPassword string          `json:"confirm_password" validate:"required,eqfield=Password"`
	Role            models.UserRole `json:"role" validate:"required,oneof=CLIENT PROFESSIONAL"`
	Timezone        string          `json:"timezone"`
}

RegisterRequest representa os dados de requisição para registro

type ResetPasswordRequest

type ResetPasswordRequest struct {
	Token           string `json:"token" validate:"required"`
	Password        string `json:"password" validate:"required"`
	ConfirmPassword string `json:"confirm_password" validate:"required,eqfield=Password"`
}

ResetPasswordRequest representa os dados de requisição para recuperação de senha

type ResetPasswordToken

type ResetPasswordToken struct {
	Token           string `json:"token" validate:"required"`
	Password        string `json:"password" validate:"required"`
	ConfirmPassword string `json:"confirm_password" validate:"required,eqfield=Password"`
}

ResetPasswordToken representa os dados de requisição para recuperação de senha

type SMSConfig

type SMSConfig struct {
	Provider   string // "twilio", "zenvia"
	AccountSID string // For Twilio
	AuthToken  string // For Twilio
	FromNumber string // Source number
	APIKey     string // For Zenvia
	APISecret  string // For Zenvia
}

SMSConfig contains the settings for the SMS service

type SMSService

type SMSService struct {
	Config SMSConfig
}

SMSService implements the SMSServiceInterface

func (*SMSService) SendGenericSMS

func (s *SMSService) SendGenericSMS(phone, message string) error

SendGenericSMS sends a generic SMS

func (*SMSService) SendPasswordResetSMS

func (s *SMSService) SendPasswordResetSMS(phone, code string) error

SendPasswordResetSMS sends a password recovery SMS

type SMSServiceInterface

type SMSServiceInterface interface {
	SendPasswordResetSMS(phone, code string) error
	SendGenericSMS(phone, message string) error
}

SMSServiceInterface defines the interface for the SMS service

func NewSMSService

func NewSMSService(config SMSConfig) SMSServiceInterface

NewSMSService creates a new instance of the SMS service

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"`
}

TokenResponse representa a resposta com tokens JWT

type WhatsAppConfig

type WhatsAppConfig struct {
	Provider      string // "meta", "twilio"
	PhoneNumberID string // For Meta API
	AccessToken   string // For Meta API
	AccountSID    string // For Twilio
	AuthToken     string // For Twilio
	FromNumber    string // Source number (with WhatsApp)
}

WhatsAppConfig contains the settings for the WhatsApp service

type WhatsAppService

type WhatsAppService struct {
	Config WhatsAppConfig
}

WhatsAppService implements the WhatsAppServiceInterface

func (*WhatsAppService) SendGenericWhatsApp

func (s *WhatsAppService) SendGenericWhatsApp(phone, message string) error

SendGenericWhatsApp sends a generic WhatsApp message

func (*WhatsAppService) SendPasswordResetWhatsApp

func (s *WhatsAppService) SendPasswordResetWhatsApp(phone, name, code string) error

SendPasswordResetWhatsApp sends a WhatsApp message for password recovery

type WhatsAppServiceInterface

type WhatsAppServiceInterface interface {
	SendPasswordResetWhatsApp(phone, name, code string) error
	SendGenericWhatsApp(phone, message string) error
}

WhatsAppServiceInterface defines the interface for the WhatsApp service

func NewWhatsAppService

func NewWhatsAppService(config WhatsAppConfig) WhatsAppServiceInterface

NewWhatsAppService creates a new instance of the WhatsApp service

Jump to

Keyboard shortcuts

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