Refactor user domain to utilize string IDs and integrate MongoDB ORM

- Updated User entity to embed MongoDB model and replace uuid.UUID with string for ID fields.
- Modified repository methods to accept string IDs instead of uuid.UUID, enhancing compatibility with MongoDB.
- Refactored service and handler methods to align with the new ID type, ensuring consistent usage across the user management functionality.
- Improved response handling in UserListResponse to directly use string IDs.
- Streamlined index creation in the user repository using the MongoDB ORM for better maintainability.
This commit is contained in:
n.nakhostin
2025-08-11 13:45:46 +03:30
parent 8c1e593686
commit 08cf927294
6 changed files with 252 additions and 355 deletions
+62 -75
View File
@@ -14,22 +14,22 @@ import (
// Service defines business logic for user operations
type Service interface {
CreateUser(ctx context.Context, form *CreateUserForm, createdBy *uuid.UUID) (*User, error)
CreateUser(ctx context.Context, form *CreateUserForm, createdBy *string) (*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
GetProfile(ctx context.Context, userID string) (*User, error)
UpdateProfile(ctx context.Context, userID string, form *UpdateProfileForm) error
ChangePassword(ctx context.Context, userID string, 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
GetUserByID(ctx context.Context, id string) (*User, error)
UpdateUser(ctx context.Context, id string, form *UpdateUserForm, updatedBy *string) (*User, error)
DeleteUser(ctx context.Context, id string, deletedBy *string) 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)
UpdateUserStatus(ctx context.Context, id string, form *UpdateUserStatusForm, updatedBy *string) error
UpdateUserRole(ctx context.Context, id string, form *UpdateUserRoleForm, updatedBy *string) error
GetUsersByCompanyID(ctx context.Context, companyID string, 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
Logout(ctx context.Context, userID string, accessToken string) error
}
// userService implements the Service interface
@@ -51,7 +51,7 @@ func NewUserService(repository Repository, logger logger.Logger, authService aut
}
// CreateUser creates a new user
func (s *userService) CreateUser(ctx context.Context, form *CreateUserForm, createdBy *uuid.UUID) (*User, error) {
func (s *userService) CreateUser(ctx context.Context, form *CreateUserForm, createdBy *string) (*User, error) {
// Check if email already exists
existingUser, _ := s.repository.GetByEmail(ctx, form.Email)
if existingUser != nil {
@@ -74,13 +74,9 @@ func (s *userService) CreateUser(ctx context.Context, form *CreateUserForm, crea
}
// Parse optional fields
var companyID *uuid.UUID
var companyID *string
if form.CompanyID != nil {
parsedID, err := uuid.Parse(*form.CompanyID)
if err != nil {
return nil, errors.New("invalid company ID")
}
companyID = &parsedID
companyID = form.CompanyID
}
// Validate role
@@ -91,7 +87,6 @@ func (s *userService) CreateUser(ctx context.Context, form *CreateUserForm, crea
// Create user
user := &User{
ID: uuid.New(),
FullName: form.FullName,
Username: form.Username,
Email: form.Email,
@@ -119,11 +114,11 @@ func (s *userService) CreateUser(ctx context.Context, form *CreateUserForm, crea
}
s.logger.Info("User created successfully", map[string]interface{}{
"user_id": user.ID.String(),
"user_id": user.ID,
"email": user.Email,
"username": user.Username,
"role": user.Role,
"created_by": createdBy.String(),
"created_by": *createdBy,
})
return user, nil
@@ -158,7 +153,7 @@ func (s *userService) Login(ctx context.Context, form *LoginForm) (*AuthResponse
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(),
"user_id": user.ID,
"email": user.Email,
})
return nil, errors.New("invalid credentials")
@@ -169,18 +164,18 @@ func (s *userService) Login(ctx context.Context, form *LoginForm) (*AuthResponse
if err != nil {
s.logger.Error("Failed to update last login", map[string]interface{}{
"error": err.Error(),
"user_id": user.ID.String(),
"user_id": user.ID,
})
}
// Generate JWT tokens using authorization service
companyID := ""
if user.CompanyID != nil {
companyID = user.CompanyID.String()
companyID = *user.CompanyID
}
tokenPair, err := s.authService.GenerateTokenPair(
user.ID.String(),
user.ID,
user.Email,
string(user.Role),
companyID,
@@ -188,13 +183,13 @@ func (s *userService) Login(ctx context.Context, form *LoginForm) (*AuthResponse
if err != nil {
s.logger.Error("Failed to generate JWT tokens", map[string]interface{}{
"error": err.Error(),
"user_id": user.ID.String(),
"user_id": user.ID,
})
return nil, errors.New("failed to generate authentication tokens")
}
s.logger.Info("User logged in successfully", map[string]interface{}{
"user_id": user.ID.String(),
"user_id": user.ID,
"email": user.Email,
"role": user.Role,
})
@@ -243,7 +238,7 @@ func (s *userService) RefreshToken(ctx context.Context, refreshToken string) (*A
return nil, errors.New("invalid token format")
}
user, err := s.repository.GetByID(ctx, userID)
user, err := s.repository.GetByID(ctx, userID.String())
if err != nil {
s.logger.Error("Failed to get user for token refresh", map[string]interface{}{
"error": err.Error(),
@@ -258,7 +253,7 @@ func (s *userService) RefreshToken(ctx context.Context, refreshToken string) (*A
}
s.logger.Info("Access token refreshed successfully", map[string]interface{}{
"user_id": user.ID.String(),
"user_id": user.ID,
"email": user.Email,
})
@@ -271,7 +266,7 @@ func (s *userService) RefreshToken(ctx context.Context, refreshToken string) (*A
}
// ChangePassword changes user password
func (s *userService) ChangePassword(ctx context.Context, userID uuid.UUID, form *ChangePasswordForm) error {
func (s *userService) ChangePassword(ctx context.Context, userID string, form *ChangePasswordForm) error {
// Get user
user, err := s.repository.GetByID(ctx, userID)
if err != nil {
@@ -289,7 +284,7 @@ func (s *userService) ChangePassword(ctx context.Context, userID uuid.UUID, form
if err != nil {
s.logger.Error("Failed to hash new password", map[string]interface{}{
"error": err.Error(),
"user_id": userID.String(),
"user_id": userID,
})
return errors.New("failed to process new password")
}
@@ -300,13 +295,13 @@ func (s *userService) ChangePassword(ctx context.Context, userID uuid.UUID, form
if err != nil {
s.logger.Error("Failed to update password", map[string]interface{}{
"error": err.Error(),
"user_id": userID.String(),
"user_id": userID,
})
return errors.New("failed to update password")
}
s.logger.Info("Password changed successfully", map[string]interface{}{
"user_id": userID.String(),
"user_id": userID,
})
return nil
@@ -326,7 +321,7 @@ func (s *userService) ResetPassword(ctx context.Context, form *ResetPasswordForm
// TODO: Implement password reset logic (send email with reset link)
s.logger.Info("Password reset requested", map[string]interface{}{
"user_id": user.ID.String(),
"user_id": user.ID,
"email": user.Email,
})
@@ -334,7 +329,7 @@ func (s *userService) ResetPassword(ctx context.Context, form *ResetPasswordForm
}
// GetUserByID retrieves a user by ID
func (s *userService) GetUserByID(ctx context.Context, id uuid.UUID) (*User, error) {
func (s *userService) GetUserByID(ctx context.Context, id string) (*User, error) {
user, err := s.repository.GetByID(ctx, id)
if err != nil {
return nil, err
@@ -344,30 +339,30 @@ func (s *userService) GetUserByID(ctx context.Context, id uuid.UUID) (*User, err
}
// GetProfile retrieves the current user's profile
func (s *userService) GetProfile(ctx context.Context, userID uuid.UUID) (*User, error) {
func (s *userService) GetProfile(ctx context.Context, userID string) (*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(),
"user_id": userID,
})
return nil, errors.New("user not found")
}
s.logger.Info("User profile retrieved successfully", map[string]interface{}{
"user_id": userID.String(),
"user_id": userID,
})
return user, nil
}
// UpdateProfile updates the current user's profile
func (s *userService) UpdateProfile(ctx context.Context, userID uuid.UUID, form *UpdateProfileForm) error {
func (s *userService) UpdateProfile(ctx context.Context, userID string, 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(),
"user_id": userID,
})
return errors.New("user not found")
}
@@ -397,20 +392,20 @@ func (s *userService) UpdateProfile(ctx context.Context, userID uuid.UUID, form
if err != nil {
s.logger.Error("Failed to update user profile", map[string]interface{}{
"error": err.Error(),
"user_id": userID.String(),
"user_id": userID,
})
return errors.New("failed to update profile")
}
s.logger.Info("User profile updated successfully", map[string]interface{}{
"user_id": userID.String(),
"user_id": userID,
})
return nil
}
// UpdateUser updates user information
func (s *userService) UpdateUser(ctx context.Context, id uuid.UUID, form *UpdateUserForm, updatedBy *uuid.UUID) (*User, error) {
func (s *userService) UpdateUser(ctx context.Context, id string, form *UpdateUserForm, updatedBy *string) (*User, error) {
// Get user
user, err := s.repository.GetByID(ctx, id)
if err != nil {
@@ -449,11 +444,7 @@ func (s *userService) UpdateUser(ctx context.Context, id uuid.UUID, form *Update
}
if form.CompanyID != nil {
parsedID, err := uuid.Parse(*form.CompanyID)
if err != nil {
return nil, errors.New("invalid company ID")
}
user.CompanyID = &parsedID
user.CompanyID = form.CompanyID
}
if form.Department != nil {
@@ -484,21 +475,21 @@ func (s *userService) UpdateUser(ctx context.Context, id uuid.UUID, form *Update
if err != nil {
s.logger.Error("Failed to update user", map[string]interface{}{
"error": err.Error(),
"user_id": id.String(),
"user_id": id,
})
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(),
"user_id": id,
"updated_by": *updatedBy,
})
return user, nil
}
// DeleteUser deletes a user (soft delete)
func (s *userService) DeleteUser(ctx context.Context, id uuid.UUID, deletedBy *uuid.UUID) error {
func (s *userService) DeleteUser(ctx context.Context, id string, deletedBy *string) error {
// Get user to check if exists
user, err := s.repository.GetByID(ctx, id)
if err != nil {
@@ -514,14 +505,14 @@ func (s *userService) DeleteUser(ctx context.Context, id uuid.UUID, deletedBy *u
if err != nil {
s.logger.Error("Failed to delete user", map[string]interface{}{
"error": err.Error(),
"user_id": id.String(),
"user_id": id,
})
return errors.New("failed to delete user")
}
s.logger.Info("User deleted successfully", map[string]interface{}{
"user_id": id.String(),
"deleted_by": deletedBy.String(),
"user_id": id,
"deleted_by": *deletedBy,
})
return nil
@@ -556,13 +547,9 @@ func (s *userService) ListUsers(ctx context.Context, form *ListUsersForm) (*User
}
// Parse company ID if provided
var companyID *uuid.UUID
var companyID *string
if form.CompanyID != nil {
parsedID, err := uuid.Parse(*form.CompanyID)
if err != nil {
return nil, errors.New("invalid company ID")
}
companyID = &parsedID
companyID = form.CompanyID
}
// Get users
@@ -594,7 +581,7 @@ func (s *userService) ListUsers(ctx context.Context, form *ListUsersForm) (*User
}
// UpdateUserStatus updates user status
func (s *userService) UpdateUserStatus(ctx context.Context, id uuid.UUID, form *UpdateUserStatusForm, updatedBy *uuid.UUID) error {
func (s *userService) UpdateUserStatus(ctx context.Context, id string, form *UpdateUserStatusForm, updatedBy *string) error {
// Get user
user, err := s.repository.GetByID(ctx, id)
if err != nil {
@@ -610,23 +597,23 @@ func (s *userService) UpdateUserStatus(ctx context.Context, id uuid.UUID, form *
if err != nil {
s.logger.Error("Failed to update user status", map[string]interface{}{
"error": err.Error(),
"user_id": id.String(),
"user_id": id,
"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(),
"user_id": id,
"status": form.Status,
"updated_by": updatedBy.String(),
"updated_by": *updatedBy,
})
return nil
}
// UpdateUserRole updates user role
func (s *userService) UpdateUserRole(ctx context.Context, id uuid.UUID, form *UpdateUserRoleForm, updatedBy *uuid.UUID) error {
func (s *userService) UpdateUserRole(ctx context.Context, id string, form *UpdateUserRoleForm, updatedBy *string) error {
// Get user
user, err := s.repository.GetByID(ctx, id)
if err != nil {
@@ -648,28 +635,28 @@ func (s *userService) UpdateUserRole(ctx context.Context, id uuid.UUID, form *Up
if err != nil {
s.logger.Error("Failed to update user role", map[string]interface{}{
"error": err.Error(),
"user_id": id.String(),
"user_id": id,
"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(),
"user_id": id,
"role": form.Role,
"updated_by": updatedBy.String(),
"updated_by": *updatedBy,
})
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) {
func (s *userService) GetUsersByCompanyID(ctx context.Context, companyID string, 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(),
"company_id": companyID,
})
return nil, 0, errors.New("failed to get users by company")
}
@@ -679,7 +666,7 @@ func (s *userService) GetUsersByCompanyID(ctx context.Context, companyID uuid.UU
if err != nil {
s.logger.Error("Failed to count users by company ID", map[string]interface{}{
"error": err.Error(),
"company_id": companyID.String(),
"company_id": companyID,
})
return users, 0, nil // Return users even if count fails
}
@@ -702,19 +689,19 @@ func (s *userService) GetUsersByRole(ctx context.Context, role UserRole, limit,
}
// Logout logs out a user and invalidates tokens
func (s *userService) Logout(ctx context.Context, userID uuid.UUID, accessToken string) error {
func (s *userService) Logout(ctx context.Context, userID string, 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(),
"user_id": userID,
})
// 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(),
"user_id": userID,
})
return nil