Enhance cursor rules and add user management functionality
- Updated cursor rules to emphasize the importance of dependency injection and logging practices. - Introduced a new user management domain, including entities, services, handlers, and validation. - Implemented user authentication features such as login, registration, and role-based access control. - Added Redis integration for token management and caching. - Enhanced API documentation with Swagger for user-related endpoints. - Updated configuration to support new JWT settings and Redis connection parameters.
This commit is contained in:
@@ -0,0 +1,721 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
"tm/pkg/authorization"
|
||||
"tm/pkg/logger"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// Service defines business logic for user operations
|
||||
type Service interface {
|
||||
CreateUser(ctx context.Context, form *CreateUserForm, createdBy *uuid.UUID) (*User, error)
|
||||
Login(ctx context.Context, form *LoginForm) (*AuthResponse, error)
|
||||
RefreshToken(ctx context.Context, refreshToken string) (*AuthResponse, error)
|
||||
GetProfile(ctx context.Context, userID uuid.UUID) (*User, error)
|
||||
UpdateProfile(ctx context.Context, userID uuid.UUID, form *UpdateProfileForm) error
|
||||
ChangePassword(ctx context.Context, userID uuid.UUID, form *ChangePasswordForm) error
|
||||
ResetPassword(ctx context.Context, form *ResetPasswordForm) error
|
||||
GetUserByID(ctx context.Context, id uuid.UUID) (*User, error)
|
||||
UpdateUser(ctx context.Context, id uuid.UUID, form *UpdateUserForm, updatedBy *uuid.UUID) (*User, error)
|
||||
DeleteUser(ctx context.Context, id uuid.UUID, deletedBy *uuid.UUID) error
|
||||
ListUsers(ctx context.Context, form *ListUsersForm) (*UserListResponse, error)
|
||||
UpdateUserStatus(ctx context.Context, id uuid.UUID, form *UpdateUserStatusForm, updatedBy *uuid.UUID) error
|
||||
UpdateUserRole(ctx context.Context, id uuid.UUID, form *UpdateUserRoleForm, updatedBy *uuid.UUID) error
|
||||
GetUsersByCompanyID(ctx context.Context, companyID uuid.UUID, limit, offset int) ([]*User, int64, error)
|
||||
GetUsersByRole(ctx context.Context, role UserRole, limit, offset int) ([]*User, error)
|
||||
Logout(ctx context.Context, userID uuid.UUID, accessToken string) error
|
||||
}
|
||||
|
||||
// userService implements the Service interface
|
||||
type userService struct {
|
||||
repository Repository
|
||||
logger logger.Logger
|
||||
authService authorization.AuthorizationService
|
||||
validator ValidationService
|
||||
}
|
||||
|
||||
// NewUserService creates a new user service
|
||||
func NewUserService(repository Repository, logger logger.Logger, authService authorization.AuthorizationService, validator ValidationService) Service {
|
||||
return &userService{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
authService: authService,
|
||||
validator: validator,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateUser creates a new user
|
||||
func (s *userService) CreateUser(ctx context.Context, form *CreateUserForm, createdBy *uuid.UUID) (*User, error) {
|
||||
// Check if email already exists
|
||||
existingUser, _ := s.repository.GetByEmail(ctx, form.Email)
|
||||
if existingUser != nil {
|
||||
return nil, errors.New("email already exists")
|
||||
}
|
||||
|
||||
// Check if username already exists
|
||||
existingUser, _ = s.repository.GetByUsername(ctx, form.Username)
|
||||
if existingUser != nil {
|
||||
return nil, errors.New("username already exists")
|
||||
}
|
||||
|
||||
// Hash password
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(form.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to hash password", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return nil, errors.New("failed to process password")
|
||||
}
|
||||
|
||||
// Parse optional fields
|
||||
var companyID *uuid.UUID
|
||||
if form.CompanyID != nil {
|
||||
parsedID, err := uuid.Parse(*form.CompanyID)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid company ID")
|
||||
}
|
||||
companyID = &parsedID
|
||||
}
|
||||
|
||||
// Validate role
|
||||
role := UserRole(form.Role)
|
||||
if !s.validator.IsValidRole(role) {
|
||||
return nil, errors.New("invalid role")
|
||||
}
|
||||
|
||||
// Create user
|
||||
user := &User{
|
||||
ID: uuid.New(),
|
||||
FullName: form.FullName,
|
||||
Username: form.Username,
|
||||
Email: form.Email,
|
||||
Password: string(hashedPassword),
|
||||
Role: role,
|
||||
Status: UserStatusActive,
|
||||
CompanyID: companyID,
|
||||
Department: form.Department,
|
||||
Position: form.Position,
|
||||
Phone: form.Phone,
|
||||
ProfileImage: form.ProfileImage,
|
||||
IsVerified: false,
|
||||
CreatedBy: createdBy,
|
||||
}
|
||||
|
||||
// Save to database
|
||||
err = s.repository.Create(ctx, user)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to create user", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"email": form.Email,
|
||||
"username": form.Username,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.logger.Info("User created successfully", map[string]interface{}{
|
||||
"user_id": user.ID.String(),
|
||||
"email": user.Email,
|
||||
"username": user.Username,
|
||||
"role": user.Role,
|
||||
"created_by": createdBy.String(),
|
||||
})
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// Login authenticates a user
|
||||
func (s *userService) Login(ctx context.Context, form *LoginForm) (*AuthResponse, error) {
|
||||
// Find user by email or username
|
||||
var user *User
|
||||
var err error
|
||||
|
||||
if strings.Contains(form.Username, "@") {
|
||||
user, err = s.repository.GetByEmail(ctx, form.Username)
|
||||
} else {
|
||||
user, err = s.repository.GetByUsername(ctx, form.Username)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
s.logger.Warn("Login attempt with invalid credentials", map[string]interface{}{
|
||||
"email_or_username": form.Username,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
|
||||
// Check if user is active
|
||||
if user.Status != UserStatusActive {
|
||||
return nil, errors.New("account is inactive")
|
||||
}
|
||||
|
||||
// Verify password
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(form.Password))
|
||||
if err != nil {
|
||||
s.logger.Warn("Login attempt with wrong password", map[string]interface{}{
|
||||
"user_id": user.ID.String(),
|
||||
"email": user.Email,
|
||||
})
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
|
||||
// Update last login
|
||||
err = s.repository.UpdateLastLogin(ctx, user.ID)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to update last login", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": user.ID.String(),
|
||||
})
|
||||
}
|
||||
|
||||
// Generate JWT tokens using authorization service
|
||||
companyID := ""
|
||||
if user.CompanyID != nil {
|
||||
companyID = user.CompanyID.String()
|
||||
}
|
||||
|
||||
tokenPair, err := s.authService.GenerateTokenPair(
|
||||
user.ID.String(),
|
||||
user.Email,
|
||||
string(user.Role),
|
||||
companyID,
|
||||
)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to generate JWT tokens", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": user.ID.String(),
|
||||
})
|
||||
return nil, errors.New("failed to generate authentication tokens")
|
||||
}
|
||||
|
||||
s.logger.Info("User logged in successfully", map[string]interface{}{
|
||||
"user_id": user.ID.String(),
|
||||
"email": user.Email,
|
||||
"role": user.Role,
|
||||
})
|
||||
|
||||
return &AuthResponse{
|
||||
User: user.ToResponse(),
|
||||
AccessToken: tokenPair.AccessToken,
|
||||
RefreshToken: tokenPair.RefreshToken,
|
||||
ExpiresAt: time.Now().Add(15 * time.Minute).Unix(), // 15 minutes from now
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RefreshToken refreshes the access token
|
||||
func (s *userService) RefreshToken(ctx context.Context, refreshToken string) (*AuthResponse, error) {
|
||||
// Validate refresh token and generate new access token
|
||||
newAccessToken, err := s.authService.RefreshAccessToken(refreshToken)
|
||||
if err != nil {
|
||||
s.logger.Warn("Failed to refresh access token", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return nil, errors.New("invalid or expired refresh token")
|
||||
}
|
||||
|
||||
// Parse the new access token to get user information
|
||||
validationResult, err := s.authService.ValidateAccessToken(newAccessToken)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to validate new access token", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return nil, errors.New("failed to generate valid access token")
|
||||
}
|
||||
|
||||
if !validationResult.Valid {
|
||||
s.logger.Error("New access token validation failed", map[string]interface{}{
|
||||
"error": validationResult.Error,
|
||||
})
|
||||
return nil, errors.New("failed to generate valid access token")
|
||||
}
|
||||
|
||||
// Get user information
|
||||
userID, err := uuid.Parse(validationResult.Claims.UserID)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to parse user ID from token", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return nil, errors.New("invalid token format")
|
||||
}
|
||||
|
||||
user, err := s.repository.GetByID(ctx, userID)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to get user for token refresh", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": userID.String(),
|
||||
})
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
|
||||
// Check if user is still active
|
||||
if user.Status != UserStatusActive {
|
||||
return nil, errors.New("user account is inactive")
|
||||
}
|
||||
|
||||
s.logger.Info("Access token refreshed successfully", map[string]interface{}{
|
||||
"user_id": user.ID.String(),
|
||||
"email": user.Email,
|
||||
})
|
||||
|
||||
return &AuthResponse{
|
||||
User: user.ToResponse(),
|
||||
AccessToken: newAccessToken,
|
||||
RefreshToken: refreshToken, // Return the same refresh token
|
||||
ExpiresAt: time.Now().Add(15 * time.Minute).Unix(), // 15 minutes from now
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ChangePassword changes user password
|
||||
func (s *userService) ChangePassword(ctx context.Context, userID uuid.UUID, form *ChangePasswordForm) error {
|
||||
// Get user
|
||||
user, err := s.repository.GetByID(ctx, userID)
|
||||
if err != nil {
|
||||
return errors.New("user not found")
|
||||
}
|
||||
|
||||
// Verify old password
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(form.OldPassword))
|
||||
if err != nil {
|
||||
return errors.New("invalid old password")
|
||||
}
|
||||
|
||||
// Hash new password
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(form.NewPassword), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to hash new password", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": userID.String(),
|
||||
})
|
||||
return errors.New("failed to process new password")
|
||||
}
|
||||
|
||||
// Update password
|
||||
user.Password = string(hashedPassword)
|
||||
err = s.repository.Update(ctx, user)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to update password", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": userID.String(),
|
||||
})
|
||||
return errors.New("failed to update password")
|
||||
}
|
||||
|
||||
s.logger.Info("Password changed successfully", map[string]interface{}{
|
||||
"user_id": userID.String(),
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResetPassword initiates password reset process
|
||||
func (s *userService) ResetPassword(ctx context.Context, form *ResetPasswordForm) error {
|
||||
// Get user by email
|
||||
user, err := s.repository.GetByEmail(ctx, form.Email)
|
||||
if err != nil {
|
||||
// Don't reveal if user exists or not for security
|
||||
s.logger.Info("Password reset requested for non-existent email", map[string]interface{}{
|
||||
"email": form.Email,
|
||||
})
|
||||
return nil // Return success even if user doesn't exist
|
||||
}
|
||||
|
||||
// TODO: Implement password reset logic (send email with reset link)
|
||||
s.logger.Info("Password reset requested", map[string]interface{}{
|
||||
"user_id": user.ID.String(),
|
||||
"email": user.Email,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetUserByID retrieves a user by ID
|
||||
func (s *userService) GetUserByID(ctx context.Context, id uuid.UUID) (*User, error) {
|
||||
user, err := s.repository.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// GetProfile retrieves the current user's profile
|
||||
func (s *userService) GetProfile(ctx context.Context, userID uuid.UUID) (*User, error) {
|
||||
user, err := s.repository.GetByID(ctx, userID)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to get user profile", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": userID.String(),
|
||||
})
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
|
||||
s.logger.Info("User profile retrieved successfully", map[string]interface{}{
|
||||
"user_id": userID.String(),
|
||||
})
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// UpdateProfile updates the current user's profile
|
||||
func (s *userService) UpdateProfile(ctx context.Context, userID uuid.UUID, form *UpdateProfileForm) error {
|
||||
user, err := s.repository.GetByID(ctx, userID)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to get user for profile update", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": userID.String(),
|
||||
})
|
||||
return errors.New("user not found")
|
||||
}
|
||||
|
||||
// Update fields if provided
|
||||
if form.FullName != nil {
|
||||
user.FullName = *form.FullName
|
||||
}
|
||||
if form.Department != nil {
|
||||
user.Department = form.Department
|
||||
}
|
||||
if form.Position != nil {
|
||||
user.Position = form.Position
|
||||
}
|
||||
if form.Phone != nil {
|
||||
user.Phone = form.Phone
|
||||
}
|
||||
if form.ProfileImage != nil {
|
||||
user.ProfileImage = form.ProfileImage
|
||||
}
|
||||
|
||||
// Update timestamp
|
||||
user.UpdatedAt = time.Now().Unix()
|
||||
|
||||
// Save to database
|
||||
err = s.repository.Update(ctx, user)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to update user profile", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": userID.String(),
|
||||
})
|
||||
return errors.New("failed to update profile")
|
||||
}
|
||||
|
||||
s.logger.Info("User profile updated successfully", map[string]interface{}{
|
||||
"user_id": userID.String(),
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateUser updates user information
|
||||
func (s *userService) UpdateUser(ctx context.Context, id uuid.UUID, form *UpdateUserForm, updatedBy *uuid.UUID) (*User, error) {
|
||||
// Get user
|
||||
user, err := s.repository.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
|
||||
// Update fields if provided
|
||||
if form.FullName != nil {
|
||||
user.FullName = *form.FullName
|
||||
}
|
||||
|
||||
if form.Username != nil {
|
||||
// Check if username already exists
|
||||
existingUser, _ := s.repository.GetByUsername(ctx, *form.Username)
|
||||
if existingUser != nil && existingUser.ID != id {
|
||||
return nil, errors.New("username already exists")
|
||||
}
|
||||
user.Username = *form.Username
|
||||
}
|
||||
|
||||
if form.Email != nil {
|
||||
// Check if email already exists
|
||||
existingUser, _ := s.repository.GetByEmail(ctx, *form.Email)
|
||||
if existingUser != nil && existingUser.ID != id {
|
||||
return nil, errors.New("email already exists")
|
||||
}
|
||||
user.Email = *form.Email
|
||||
}
|
||||
|
||||
if form.Role != nil {
|
||||
role := UserRole(*form.Role)
|
||||
if !s.validator.IsValidRole(role) {
|
||||
return nil, errors.New("invalid role")
|
||||
}
|
||||
user.Role = role
|
||||
}
|
||||
|
||||
if form.CompanyID != nil {
|
||||
parsedID, err := uuid.Parse(*form.CompanyID)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid company ID")
|
||||
}
|
||||
user.CompanyID = &parsedID
|
||||
}
|
||||
|
||||
if form.Department != nil {
|
||||
user.Department = form.Department
|
||||
}
|
||||
|
||||
if form.Position != nil {
|
||||
user.Position = form.Position
|
||||
}
|
||||
|
||||
if form.Phone != nil {
|
||||
user.Phone = form.Phone
|
||||
}
|
||||
|
||||
if form.ProfileImage != nil {
|
||||
user.ProfileImage = form.ProfileImage
|
||||
}
|
||||
|
||||
if form.Status != nil {
|
||||
user.Status = UserStatus(*form.Status)
|
||||
}
|
||||
|
||||
// Set updated by
|
||||
user.UpdatedBy = updatedBy
|
||||
|
||||
// Update in database
|
||||
err = s.repository.Update(ctx, user)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to update user", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": id.String(),
|
||||
})
|
||||
return nil, errors.New("failed to update user")
|
||||
}
|
||||
|
||||
s.logger.Info("User updated successfully", map[string]interface{}{
|
||||
"user_id": id.String(),
|
||||
"updated_by": updatedBy.String(),
|
||||
})
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// DeleteUser deletes a user (soft delete)
|
||||
func (s *userService) DeleteUser(ctx context.Context, id uuid.UUID, deletedBy *uuid.UUID) error {
|
||||
// Get user to check if exists
|
||||
user, err := s.repository.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return errors.New("user not found")
|
||||
}
|
||||
|
||||
// Set updated by before deletion
|
||||
user.UpdatedBy = deletedBy
|
||||
|
||||
// Update user status to inactive (soft delete)
|
||||
user.Status = UserStatusInactive
|
||||
err = s.repository.Update(ctx, user)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to delete user", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": id.String(),
|
||||
})
|
||||
return errors.New("failed to delete user")
|
||||
}
|
||||
|
||||
s.logger.Info("User deleted successfully", map[string]interface{}{
|
||||
"user_id": id.String(),
|
||||
"deleted_by": deletedBy.String(),
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListUsers lists users with search and filters
|
||||
func (s *userService) ListUsers(ctx context.Context, form *ListUsersForm) (*UserListResponse, error) {
|
||||
// Set defaults
|
||||
limit := 20
|
||||
if form.Limit != nil {
|
||||
limit = *form.Limit
|
||||
}
|
||||
|
||||
offset := 0
|
||||
if form.Offset != nil {
|
||||
offset = *form.Offset
|
||||
}
|
||||
|
||||
search := ""
|
||||
if form.Search != nil {
|
||||
search = *form.Search
|
||||
}
|
||||
|
||||
sortBy := "created_at"
|
||||
if form.SortBy != nil {
|
||||
sortBy = *form.SortBy
|
||||
}
|
||||
|
||||
sortOrder := "desc"
|
||||
if form.SortOrder != nil {
|
||||
sortOrder = *form.SortOrder
|
||||
}
|
||||
|
||||
// Parse company ID if provided
|
||||
var companyID *uuid.UUID
|
||||
if form.CompanyID != nil {
|
||||
parsedID, err := uuid.Parse(*form.CompanyID)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid company ID")
|
||||
}
|
||||
companyID = &parsedID
|
||||
}
|
||||
|
||||
// Get users
|
||||
users, err := s.repository.Search(ctx, search, form.Status, form.Role, companyID, limit, offset, sortBy, sortOrder)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to list users", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return nil, errors.New("failed to list users")
|
||||
}
|
||||
|
||||
// Convert to responses
|
||||
var userResponses []*UserResponse
|
||||
for _, user := range users {
|
||||
userResponses = append(userResponses, user.ToResponse())
|
||||
}
|
||||
|
||||
// TODO: Implement proper count for pagination metadata
|
||||
total := int64(len(users)) // This should be a separate count query
|
||||
totalPages := (total + int64(limit) - 1) / int64(limit)
|
||||
|
||||
return &UserListResponse{
|
||||
Users: userResponses,
|
||||
Total: total,
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
TotalPages: int(totalPages),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateUserStatus updates user status
|
||||
func (s *userService) UpdateUserStatus(ctx context.Context, id uuid.UUID, form *UpdateUserStatusForm, updatedBy *uuid.UUID) error {
|
||||
// Get user
|
||||
user, err := s.repository.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return errors.New("user not found")
|
||||
}
|
||||
|
||||
// Update status
|
||||
user.Status = UserStatus(form.Status)
|
||||
user.UpdatedBy = updatedBy
|
||||
|
||||
// Update in database
|
||||
err = s.repository.Update(ctx, user)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to update user status", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": id.String(),
|
||||
"status": form.Status,
|
||||
})
|
||||
return errors.New("failed to update user status")
|
||||
}
|
||||
|
||||
s.logger.Info("User status updated successfully", map[string]interface{}{
|
||||
"user_id": id.String(),
|
||||
"status": form.Status,
|
||||
"updated_by": updatedBy.String(),
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateUserRole updates user role
|
||||
func (s *userService) UpdateUserRole(ctx context.Context, id uuid.UUID, form *UpdateUserRoleForm, updatedBy *uuid.UUID) error {
|
||||
// Get user
|
||||
user, err := s.repository.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return errors.New("user not found")
|
||||
}
|
||||
|
||||
// Validate role
|
||||
role := UserRole(form.Role)
|
||||
if !s.validator.IsValidRole(role) {
|
||||
return errors.New("invalid role")
|
||||
}
|
||||
|
||||
// Update role
|
||||
user.Role = role
|
||||
user.UpdatedBy = updatedBy
|
||||
|
||||
// Update in database
|
||||
err = s.repository.Update(ctx, user)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to update user role", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": id.String(),
|
||||
"role": form.Role,
|
||||
})
|
||||
return errors.New("failed to update user role")
|
||||
}
|
||||
|
||||
s.logger.Info("User role updated successfully", map[string]interface{}{
|
||||
"user_id": id.String(),
|
||||
"role": form.Role,
|
||||
"updated_by": updatedBy.String(),
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetUsersByCompanyID retrieves users by company ID with pagination
|
||||
func (s *userService) GetUsersByCompanyID(ctx context.Context, companyID uuid.UUID, limit, offset int) ([]*User, int64, error) {
|
||||
users, err := s.repository.GetByCompanyID(ctx, companyID, limit, offset)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to get users by company ID", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"company_id": companyID.String(),
|
||||
})
|
||||
return nil, 0, errors.New("failed to get users by company")
|
||||
}
|
||||
|
||||
// Get total count
|
||||
total, err := s.repository.CountByCompanyID(ctx, companyID)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to count users by company ID", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"company_id": companyID.String(),
|
||||
})
|
||||
return users, 0, nil // Return users even if count fails
|
||||
}
|
||||
|
||||
return users, total, nil
|
||||
}
|
||||
|
||||
// GetUsersByRole retrieves users by role with pagination
|
||||
func (s *userService) GetUsersByRole(ctx context.Context, role UserRole, limit, offset int) ([]*User, error) {
|
||||
users, err := s.repository.GetByRole(ctx, role, limit, offset)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to get users by role", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"role": role,
|
||||
})
|
||||
return nil, errors.New("failed to get users by role")
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// Logout logs out a user and invalidates tokens
|
||||
func (s *userService) Logout(ctx context.Context, userID uuid.UUID, accessToken string) error {
|
||||
// Invalidate the access token
|
||||
err := s.authService.InvalidateToken(accessToken)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to invalidate access token", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": userID.String(),
|
||||
})
|
||||
// Don't return error here as the user should still be logged out
|
||||
}
|
||||
|
||||
s.logger.Info("User logged out successfully", map[string]interface{}{
|
||||
"user_id": userID.String(),
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user