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,214 @@
|
||||
# User Management Service
|
||||
|
||||
This service provides comprehensive user management functionality for the Tender Management system, following Clean Architecture principles and Domain-Driven Design patterns.
|
||||
|
||||
## Features
|
||||
|
||||
### User Authentication
|
||||
- **Login**: Authenticate users with email/username and password
|
||||
- **Refresh Token**: Refresh access tokens
|
||||
- **Logout**: Securely log out users
|
||||
- **Password Management**: Change password and reset password functionality
|
||||
|
||||
### User Management
|
||||
- **Create User**: Create new users with roles and permissions
|
||||
- **Update User**: Update user information and profile
|
||||
- **Delete User**: Soft delete users (set status to inactive)
|
||||
- **Get User**: Retrieve user information by ID
|
||||
- **List Users**: Search and filter users with pagination
|
||||
|
||||
### Role-Based Access Control
|
||||
- **User Roles**: admin, manager, operator, viewer
|
||||
- **Role Management**: Update user roles
|
||||
- **Status Management**: Activate, deactivate, or suspend users
|
||||
|
||||
### Company Management
|
||||
- **Company Users**: Get users by company ID
|
||||
- **User Count**: Count users per company
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Public Endpoints
|
||||
|
||||
#### Authentication
|
||||
```
|
||||
POST /api/v1/users/login
|
||||
POST /api/v1/users/refresh-token
|
||||
POST /api/v1/users/reset-password
|
||||
```
|
||||
|
||||
### Protected Endpoints (Require Authentication)
|
||||
|
||||
#### User Profile
|
||||
```
|
||||
GET /api/v1/users/profile
|
||||
PUT /api/v1/users/profile
|
||||
PUT /api/v1/users/change-password
|
||||
POST /api/v1/users/logout
|
||||
```
|
||||
|
||||
### Admin Endpoints (Require Admin Role)
|
||||
|
||||
#### User Management
|
||||
```
|
||||
POST /api/v1/users/admin/
|
||||
GET /api/v1/users/admin/
|
||||
GET /api/v1/users/admin/:id
|
||||
PUT /api/v1/users/admin/:id
|
||||
DELETE /api/v1/users/admin/:id
|
||||
```
|
||||
|
||||
#### User Status & Role Management
|
||||
```
|
||||
PUT /api/v1/users/admin/:id/status
|
||||
PUT /api/v1/users/admin/:id/role
|
||||
```
|
||||
|
||||
#### Company & Role Queries
|
||||
```
|
||||
GET /api/v1/users/admin/company/:company_id
|
||||
GET /api/v1/users/admin/role/:role
|
||||
```
|
||||
|
||||
## Request/Response Examples
|
||||
|
||||
### Create User
|
||||
```json
|
||||
POST /api/v1/users/admin/
|
||||
{
|
||||
"full_name": "John Doe",
|
||||
"username": "johndoe",
|
||||
"email": "john.doe@example.com",
|
||||
"password": "securepassword123",
|
||||
"role": "manager",
|
||||
"company_id": "550e8400-e29b-41d4-a716-446655440000",
|
||||
"department": "Engineering",
|
||||
"position": "Senior Manager",
|
||||
"phone": "+1234567890",
|
||||
"profile_image": "https://example.com/avatar.jpg"
|
||||
}
|
||||
```
|
||||
|
||||
### Login
|
||||
```json
|
||||
POST /api/v1/users/login
|
||||
{
|
||||
"email_or_username": "john.doe@example.com",
|
||||
"password": "securepassword123"
|
||||
}
|
||||
```
|
||||
|
||||
### Update User
|
||||
```json
|
||||
PUT /api/v1/users/admin/:id
|
||||
{
|
||||
"full_name": "John Smith",
|
||||
"department": "Product Management",
|
||||
"status": "active"
|
||||
}
|
||||
```
|
||||
|
||||
### List Users with Filters
|
||||
```
|
||||
GET /api/v1/users/admin/?search=john&role=manager&status=active&limit=20&offset=0&sort_by=created_at&sort_order=desc
|
||||
```
|
||||
|
||||
## Data Models
|
||||
|
||||
### User Entity
|
||||
```go
|
||||
type User struct {
|
||||
ID uuid.UUID `bson:"_id"`
|
||||
FullName string `bson:"full_name"`
|
||||
Username string `bson:"username"`
|
||||
Email string `bson:"email"`
|
||||
Password string `bson:"password"`
|
||||
Role UserRole `bson:"role"`
|
||||
Status UserStatus `bson:"status"`
|
||||
CompanyID *uuid.UUID `bson:"company_id,omitempty"`
|
||||
Department *string `bson:"department,omitempty"`
|
||||
Position *string `bson:"position,omitempty"`
|
||||
Phone *string `bson:"phone,omitempty"`
|
||||
ProfileImage *string `bson:"profile_image,omitempty"`
|
||||
IsVerified bool `bson:"is_verified"`
|
||||
LastLoginAt *int64 `bson:"last_login_at,omitempty"`
|
||||
CreatedAt int64 `bson:"created_at"`
|
||||
UpdatedAt int64 `bson:"updated_at"`
|
||||
CreatedBy *uuid.UUID `bson:"created_by,omitempty"`
|
||||
UpdatedBy *uuid.UUID `bson:"updated_by,omitempty"`
|
||||
}
|
||||
```
|
||||
|
||||
### User Roles
|
||||
- `admin`: Full system access
|
||||
- `manager`: Company and team management
|
||||
- `operator`: Operational tasks
|
||||
- `viewer`: Read-only access
|
||||
|
||||
### User Status
|
||||
- `active`: User can access the system
|
||||
- `inactive`: User account is disabled
|
||||
- `suspended`: User account is temporarily suspended
|
||||
|
||||
## Security Features
|
||||
|
||||
### Password Security
|
||||
- Passwords are hashed using bcrypt
|
||||
- Minimum password length: 8 characters
|
||||
- Maximum password length: 128 characters
|
||||
|
||||
### Authentication
|
||||
- JWT-based authentication (to be implemented)
|
||||
- Token refresh mechanism
|
||||
- Secure logout with token invalidation
|
||||
|
||||
### Authorization
|
||||
- Role-based access control
|
||||
- Admin-only endpoints for user management
|
||||
- Company-scoped access for multi-tenant support
|
||||
|
||||
## Database Indexes
|
||||
|
||||
The service creates the following MongoDB indexes for optimal performance:
|
||||
|
||||
- **Email Index**: Unique index on email field
|
||||
- **Username Index**: Unique index on username field
|
||||
- **Company ID Index**: For company-based queries
|
||||
- **Role Index**: For role-based filtering
|
||||
- **Status Index**: For status-based filtering
|
||||
- **Created At Index**: For sorting by creation date
|
||||
- **Text Search Index**: For full-text search across name, email, username, department, and position
|
||||
|
||||
## Error Handling
|
||||
|
||||
The service provides comprehensive error handling with:
|
||||
|
||||
- **Validation Errors**: Detailed validation messages using govalidator
|
||||
- **Business Logic Errors**: Clear error messages for business rule violations
|
||||
- **Database Errors**: Proper handling of database constraints and connection issues
|
||||
- **Security Errors**: Secure error messages that don't leak sensitive information
|
||||
|
||||
## Logging
|
||||
|
||||
All operations are logged with structured logging including:
|
||||
|
||||
- **Operation Context**: User ID, company ID, operation type
|
||||
- **Error Details**: Full error context for debugging
|
||||
- **Security Events**: Login attempts, password changes, role updates
|
||||
- **Performance Metrics**: Operation timing and resource usage
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
### Planned Features
|
||||
- **JWT Token Management**: Complete JWT implementation with refresh tokens
|
||||
- **Email Verification**: Email verification for new user accounts
|
||||
- **Password Reset**: Complete password reset flow with email
|
||||
- **Audit Trail**: Comprehensive audit logging for all user operations
|
||||
- **Bulk Operations**: Bulk user import/export functionality
|
||||
- **Advanced Search**: Elasticsearch integration for advanced search capabilities
|
||||
|
||||
### Integration Points
|
||||
- **Email Service**: For password reset and verification emails
|
||||
- **Notification Service**: For user activity notifications
|
||||
- **Audit Service**: For comprehensive audit logging
|
||||
- **Permission Service**: For fine-grained permission management
|
||||
@@ -0,0 +1,46 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// UserRole represents user roles in the system
|
||||
type UserRole string
|
||||
|
||||
const (
|
||||
UserRoleAdmin UserRole = "admin"
|
||||
UserRoleManager UserRole = "manager"
|
||||
UserRoleOperator UserRole = "operator"
|
||||
UserRoleViewer UserRole = "viewer"
|
||||
)
|
||||
|
||||
// UserStatus represents user account status
|
||||
type UserStatus string
|
||||
|
||||
const (
|
||||
UserStatusActive UserStatus = "active"
|
||||
UserStatusInactive UserStatus = "inactive"
|
||||
UserStatusSuspended UserStatus = "suspended"
|
||||
)
|
||||
|
||||
// User represents a system user (admin/manager/operator)
|
||||
type User struct {
|
||||
ID uuid.UUID `bson:"_id"`
|
||||
FullName string `bson:"full_name"`
|
||||
Username string `bson:"username"`
|
||||
Email string `bson:"email"`
|
||||
Password string `bson:"password"` // Never serialize password
|
||||
Role UserRole `bson:"role"`
|
||||
Status UserStatus `bson:"status"`
|
||||
CompanyID *uuid.UUID `bson:"company_id,omitempty"`
|
||||
Department *string `bson:"department,omitempty"`
|
||||
Position *string `bson:"position,omitempty"`
|
||||
Phone *string `bson:"phone,omitempty"`
|
||||
ProfileImage *string `bson:"profile_image,omitempty"`
|
||||
IsVerified bool `bson:"is_verified"`
|
||||
LastLoginAt *int64 `bson:"last_login_at,omitempty"` // Unix timestamp
|
||||
CreatedAt int64 `bson:"created_at"` // Unix timestamp
|
||||
UpdatedAt int64 `bson:"updated_at"` // Unix timestamp
|
||||
CreatedBy *uuid.UUID `bson:"created_by,omitempty"`
|
||||
UpdatedBy *uuid.UUID `bson:"updated_by,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package user
|
||||
|
||||
// User Registration DTOs
|
||||
type CreateUserForm struct {
|
||||
FullName string `json:"full_name" valid:"required,length(2|100)"`
|
||||
Username string `json:"username" valid:"required,alphanum,length(3|30)"`
|
||||
Email string `json:"email" valid:"required,email"`
|
||||
Password string `json:"password" valid:"required,length(8|128)"`
|
||||
Role string `json:"role" valid:"required,in(admin|manager|operator|viewer)"`
|
||||
CompanyID *string `json:"company_id,omitempty" valid:"optional,uuid"`
|
||||
Department *string `json:"department,omitempty" valid:"optional,length(2|100)"`
|
||||
Position *string `json:"position,omitempty" valid:"optional,length(2|100)"`
|
||||
Phone *string `json:"phone,omitempty" valid:"optional,length(10|20)"`
|
||||
ProfileImage *string `json:"profile_image,omitempty" valid:"optional,url"`
|
||||
}
|
||||
|
||||
type UpdateUserForm struct {
|
||||
FullName *string `json:"full_name,omitempty" valid:"optional,length(2|100)"`
|
||||
Username *string `json:"username,omitempty" valid:"optional,alphanum,length(3|30)"`
|
||||
Email *string `json:"email,omitempty" valid:"optional,email"`
|
||||
Role *string `json:"role,omitempty" valid:"optional,in(admin|manager|operator|viewer)"`
|
||||
CompanyID *string `json:"company_id,omitempty" valid:"optional,uuid"`
|
||||
Department *string `json:"department,omitempty" valid:"optional,length(2|100)"`
|
||||
Position *string `json:"position,omitempty" valid:"optional,length(2|100)"`
|
||||
Phone *string `json:"phone,omitempty" valid:"optional,length(10|20)"`
|
||||
ProfileImage *string `json:"profile_image,omitempty" valid:"optional,url"`
|
||||
Status *string `json:"status,omitempty" valid:"optional,in(active|inactive|suspended)"`
|
||||
}
|
||||
|
||||
// User Authentication DTOs
|
||||
type LoginForm struct {
|
||||
Username string `json:"username" valid:"required"`
|
||||
Password string `json:"password" valid:"required"`
|
||||
}
|
||||
|
||||
type RefreshTokenForm struct {
|
||||
RefreshToken string `json:"refresh_token" valid:"required"`
|
||||
}
|
||||
|
||||
type ChangePasswordForm struct {
|
||||
OldPassword string `json:"old_password" valid:"required"`
|
||||
NewPassword string `json:"new_password" valid:"required,length(8|128)"`
|
||||
}
|
||||
|
||||
type UpdateProfileForm struct {
|
||||
FullName *string `json:"full_name,omitempty" valid:"optional,length(2|100)"`
|
||||
Department *string `json:"department,omitempty" valid:"optional,length(2|100)"`
|
||||
Position *string `json:"position,omitempty" valid:"optional,length(2|100)"`
|
||||
Phone *string `json:"phone,omitempty" valid:"optional,length(10|20)"`
|
||||
ProfileImage *string `json:"profile_image,omitempty" valid:"optional,url"`
|
||||
}
|
||||
|
||||
type ResetPasswordForm struct {
|
||||
Email string `json:"email" valid:"required,email"`
|
||||
}
|
||||
|
||||
// Admin DTOs
|
||||
type ListUsersForm struct {
|
||||
Search *string `query:"search" valid:"optional"`
|
||||
Status *string `query:"status" valid:"optional,in(active|inactive|suspended)"`
|
||||
Role *string `query:"role" valid:"optional,in(admin|manager|operator|viewer)"`
|
||||
CompanyID *string `query:"company_id" valid:"optional,uuid"`
|
||||
Limit *int `query:"limit" valid:"optional,range(1|100)"`
|
||||
Offset *int `query:"offset" valid:"optional,min(0)"`
|
||||
SortBy *string `query:"sort_by" valid:"optional,in(full_name|email|username|role|created_at|last_login_at)"`
|
||||
SortOrder *string `query:"sort_order" valid:"optional,in(asc|desc)"`
|
||||
}
|
||||
|
||||
type UpdateUserStatusForm struct {
|
||||
Status string `json:"status" valid:"required,in(active|inactive|suspended)"`
|
||||
}
|
||||
|
||||
type UpdateUserRoleForm struct {
|
||||
Role string `json:"role" valid:"required,in(admin|manager|operator|viewer)"`
|
||||
}
|
||||
|
||||
// Response DTOs
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
FullName string `json:"full_name"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Role string `json:"role"`
|
||||
Status string `json:"status"`
|
||||
CompanyID *string `json:"company_id,omitempty"`
|
||||
Department *string `json:"department,omitempty"`
|
||||
Position *string `json:"position,omitempty"`
|
||||
Phone *string `json:"phone,omitempty"`
|
||||
ProfileImage *string `json:"profile_image,omitempty"`
|
||||
IsVerified bool `json:"is_verified"`
|
||||
LastLoginAt *int64 `json:"last_login_at,omitempty"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
CreatedBy *string `json:"created_by,omitempty"`
|
||||
UpdatedBy *string `json:"updated_by,omitempty"`
|
||||
}
|
||||
|
||||
type AuthResponse struct {
|
||||
User *UserResponse `json:"user"`
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
|
||||
type UserListResponse struct {
|
||||
Users []*UserResponse `json:"users"`
|
||||
Total int64 `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
TotalPages int `json:"total_pages"`
|
||||
}
|
||||
|
||||
// Helper function to convert User to UserResponse
|
||||
func (u *User) ToResponse() *UserResponse {
|
||||
companyID := ""
|
||||
if u.CompanyID != nil {
|
||||
companyID = u.CompanyID.String()
|
||||
}
|
||||
|
||||
createdBy := ""
|
||||
if u.CreatedBy != nil {
|
||||
createdBy = u.CreatedBy.String()
|
||||
}
|
||||
|
||||
updatedBy := ""
|
||||
if u.UpdatedBy != nil {
|
||||
updatedBy = u.UpdatedBy.String()
|
||||
}
|
||||
|
||||
return &UserResponse{
|
||||
ID: u.ID.String(),
|
||||
FullName: u.FullName,
|
||||
Username: u.Username,
|
||||
Email: u.Email,
|
||||
Role: string(u.Role),
|
||||
Status: string(u.Status),
|
||||
CompanyID: &companyID,
|
||||
Department: u.Department,
|
||||
Position: u.Position,
|
||||
Phone: u.Phone,
|
||||
ProfileImage: u.ProfileImage,
|
||||
IsVerified: u.IsVerified,
|
||||
LastLoginAt: u.LastLoginAt,
|
||||
CreatedAt: u.CreatedAt,
|
||||
UpdatedAt: u.UpdatedAt,
|
||||
CreatedBy: &createdBy,
|
||||
UpdatedBy: &updatedBy,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,687 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"tm/pkg/authorization"
|
||||
"tm/pkg/logger"
|
||||
"tm/pkg/response"
|
||||
|
||||
"github.com/asaskevich/govalidator"
|
||||
"github.com/google/uuid"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// Handler handles HTTP requests for user operations
|
||||
type Handler struct {
|
||||
service Service
|
||||
logger logger.Logger
|
||||
validator ValidationService
|
||||
authService authorization.AuthorizationService
|
||||
}
|
||||
|
||||
// NewUserHandler creates a new user handler
|
||||
func NewUserHandler(service Service, logger logger.Logger, validator ValidationService, authService authorization.AuthorizationService) *Handler {
|
||||
return &Handler{
|
||||
service: service,
|
||||
logger: logger,
|
||||
validator: validator,
|
||||
authService: authService,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterRoutes registers user routes
|
||||
func (h *Handler) RegisterRoutes(e *echo.Echo) {
|
||||
v1 := e.Group("/api/v1")
|
||||
|
||||
userGroup := v1.Group("/users")
|
||||
{
|
||||
// Public routes
|
||||
userGroup.POST("/login", h.Login)
|
||||
userGroup.POST("/refresh-token", h.RefreshToken)
|
||||
userGroup.POST("/reset-password", h.ResetPassword)
|
||||
|
||||
// Protected routes (require authentication)
|
||||
authGroup := userGroup.Group("")
|
||||
// authGroup.Use(h.AuthMiddleware())
|
||||
{
|
||||
authGroup.GET("/profile", h.GetProfile)
|
||||
authGroup.PUT("/profile", h.UpdateProfile)
|
||||
authGroup.PUT("/change-password", h.ChangePassword)
|
||||
authGroup.POST("/logout", h.Logout)
|
||||
|
||||
// Admin routes
|
||||
adminGroup := authGroup.Group("/admin")
|
||||
// adminGroup.Use(h.AdminMiddleware())
|
||||
{
|
||||
adminGroup.POST("", h.CreateUser)
|
||||
adminGroup.GET("", h.ListUsers)
|
||||
adminGroup.GET("/:id", h.GetUserByID)
|
||||
adminGroup.PUT("/:id", h.UpdateUser)
|
||||
adminGroup.DELETE("/:id", h.DeleteUser)
|
||||
adminGroup.PUT("/:id/status", h.UpdateUserStatus)
|
||||
adminGroup.PUT("/:id/role", h.UpdateUserRole)
|
||||
adminGroup.GET("/company/:company_id", h.GetUsersByCompanyID)
|
||||
adminGroup.GET("/role/:role", h.GetUsersByRole)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Login handles user login
|
||||
// @Summary Login user
|
||||
// @Description Authenticate user with email/username and password
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param login body LoginForm true "Login credentials"
|
||||
// @Success 200 {object} response.APIResponse{data=AuthResponse}
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/login [post]
|
||||
func (h *Handler) Login(c echo.Context) error {
|
||||
form, err := response.Parse[LoginForm](c)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid request format", "")
|
||||
}
|
||||
|
||||
// Call service
|
||||
authResponse, err := h.service.Login(c.Request().Context(), form)
|
||||
if err != nil {
|
||||
return response.Unauthorized(c, err.Error())
|
||||
}
|
||||
|
||||
return response.Success(c, authResponse, "Login successful")
|
||||
}
|
||||
|
||||
// RefreshToken handles token refresh
|
||||
// @Summary Refresh access token
|
||||
// @Description Refresh access token using refresh token
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param refresh body RefreshTokenForm true "Refresh token"
|
||||
// @Success 200 {object} response.APIResponse{data=AuthResponse}
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/refresh-token [post]
|
||||
func (h *Handler) RefreshToken(c echo.Context) error {
|
||||
form, err := response.Parse[RefreshTokenForm](c)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid request format", "")
|
||||
}
|
||||
|
||||
authResponse, err := h.service.RefreshToken(c.Request().Context(), form.RefreshToken)
|
||||
if err != nil {
|
||||
return response.Unauthorized(c, err.Error())
|
||||
}
|
||||
|
||||
return response.Success(c, authResponse, "Token refreshed successfully")
|
||||
}
|
||||
|
||||
// ResetPassword handles password reset request
|
||||
// @Summary Reset password
|
||||
// @Description Send password reset email to user
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param reset body ResetPasswordForm true "Password reset request"
|
||||
// @Success 200 {object} response.APIResponse
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/reset-password [post]
|
||||
func (h *Handler) ResetPassword(c echo.Context) error {
|
||||
form, err := response.Parse[ResetPasswordForm](c)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid request format", "")
|
||||
}
|
||||
|
||||
err = h.service.ResetPassword(c.Request().Context(), form)
|
||||
if err != nil {
|
||||
return response.InternalServerError(c, "Failed to process password reset")
|
||||
}
|
||||
|
||||
return response.Success(c, map[string]interface{}{
|
||||
"message": "Password reset email sent successfully",
|
||||
}, "Password reset initiated")
|
||||
}
|
||||
|
||||
// GetProfile gets current user profile
|
||||
// @Summary Get user profile
|
||||
// @Description Get current user profile information
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} response.APIResponse{data=UserResponse}
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 404 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/profile [get]
|
||||
func (h *Handler) GetProfile(c echo.Context) error {
|
||||
// Extract user ID from JWT token context
|
||||
userID, err := GetUserIDFromContext(c)
|
||||
if err != nil {
|
||||
return response.Unauthorized(c, "User not authenticated")
|
||||
}
|
||||
|
||||
user, err := h.service.GetProfile(c.Request().Context(), userID)
|
||||
if err != nil {
|
||||
return response.NotFound(c, "User not found")
|
||||
}
|
||||
|
||||
return response.Success(c, user.ToResponse(), "Profile retrieved successfully")
|
||||
}
|
||||
|
||||
// UpdateProfile updates current user profile
|
||||
// @Summary Update user profile
|
||||
// @Description Update current user profile information
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param profile body UpdateUserForm true "Profile update data"
|
||||
// @Success 200 {object} response.APIResponse{data=UserResponse}
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/profile [put]
|
||||
func (h *Handler) UpdateProfile(c echo.Context) error {
|
||||
// TODO: Extract user ID from JWT token
|
||||
userID := uuid.New() // Placeholder - should be extracted from JWT
|
||||
|
||||
form, err := response.Parse[UpdateUserForm](c)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid request format", "")
|
||||
}
|
||||
|
||||
user, err := h.service.UpdateUser(c.Request().Context(), userID, form, &userID)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, err.Error(), "")
|
||||
}
|
||||
|
||||
return response.Success(c, user.ToResponse(), "Profile updated successfully")
|
||||
}
|
||||
|
||||
// ChangePassword changes current user password
|
||||
// @Summary Change password
|
||||
// @Description Change current user password
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param password body ChangePasswordForm true "Password change data"
|
||||
// @Success 200 {object} response.APIResponse
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/change-password [put]
|
||||
func (h *Handler) ChangePassword(c echo.Context) error {
|
||||
// TODO: Extract user ID from JWT token
|
||||
userID := uuid.New() // Placeholder - should be extracted from JWT
|
||||
|
||||
form, err := response.Parse[ChangePasswordForm](c)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid request format", "")
|
||||
}
|
||||
|
||||
err = h.service.ChangePassword(c.Request().Context(), userID, form)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, err.Error(), "")
|
||||
}
|
||||
|
||||
return response.Success(c, map[string]interface{}{
|
||||
"message": "Password changed successfully",
|
||||
}, "Password changed successfully")
|
||||
}
|
||||
|
||||
// Logout handles user logout
|
||||
// @Summary Logout user
|
||||
// @Description Logout current user and invalidate tokens
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/logout [post]
|
||||
func (h *Handler) Logout(c echo.Context) error {
|
||||
// Extract user ID and access token from context
|
||||
userID, err := GetUserIDFromContext(c)
|
||||
if err != nil {
|
||||
return response.Unauthorized(c, "User not authenticated")
|
||||
}
|
||||
|
||||
accessToken, err := GetAccessTokenFromContext(c)
|
||||
if err != nil {
|
||||
return response.Unauthorized(c, "Access token not found")
|
||||
}
|
||||
|
||||
err = h.service.Logout(c.Request().Context(), userID, accessToken)
|
||||
if err != nil {
|
||||
return response.InternalServerError(c, "Failed to logout")
|
||||
}
|
||||
|
||||
return response.Success(c, map[string]interface{}{
|
||||
"message": "Logged out successfully",
|
||||
}, "Logged out successfully")
|
||||
}
|
||||
|
||||
// CreateUser creates a new user (admin only)
|
||||
// @Summary Create user
|
||||
// @Description Create a new user (admin only)
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param user body CreateUserForm true "User creation data"
|
||||
// @Success 201 {object} response.APIResponse{data=UserResponse}
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 403 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/admin [post]
|
||||
func (h *Handler) CreateUser(c echo.Context) error {
|
||||
// Get current user ID from JWT token
|
||||
currentUserID, err := GetUserIDFromContext(c)
|
||||
if err != nil {
|
||||
return response.Unauthorized(c, "User not authenticated")
|
||||
}
|
||||
|
||||
var form CreateUserForm
|
||||
if err := c.Bind(&form); err != nil {
|
||||
return response.BadRequest(c, "Invalid request format", "")
|
||||
}
|
||||
|
||||
// Validate form
|
||||
if _, err := govalidator.ValidateStruct(form); err != nil {
|
||||
return response.ValidationError(c, err.Error(), "")
|
||||
}
|
||||
|
||||
// Call service
|
||||
user, err := h.service.CreateUser(c.Request().Context(), &form, ¤tUserID)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, err.Error(), "")
|
||||
}
|
||||
|
||||
return response.Created(c, user.ToResponse(), "User created successfully")
|
||||
}
|
||||
|
||||
// ListUsers lists users with search and filters (admin only)
|
||||
// @Summary List users
|
||||
// @Description List users with search and filters (admin only)
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param search query string false "Search term"
|
||||
// @Param status query string false "User status filter"
|
||||
// @Param role query string false "User role filter"
|
||||
// @Param company_id query string false "Company ID filter"
|
||||
// @Param limit query int false "Limit results"
|
||||
// @Param offset query int false "Offset results"
|
||||
// @Param sort_by query string false "Sort field"
|
||||
// @Param sort_order query string false "Sort order"
|
||||
// @Success 200 {object} response.APIResponse{data=UserListResponse}
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 403 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/admin [get]
|
||||
func (h *Handler) ListUsers(c echo.Context) error {
|
||||
var form ListUsersForm
|
||||
if err := c.Bind(&form); err != nil {
|
||||
return response.BadRequest(c, "Invalid request format", "")
|
||||
}
|
||||
|
||||
// Validate form
|
||||
if _, err := govalidator.ValidateStruct(form); err != nil {
|
||||
return response.ValidationError(c, err.Error(), "")
|
||||
}
|
||||
|
||||
// Call service
|
||||
users, err := h.service.ListUsers(c.Request().Context(), &form)
|
||||
if err != nil {
|
||||
return response.InternalServerError(c, "Failed to list users")
|
||||
}
|
||||
|
||||
return response.Success(c, users, "Users retrieved successfully")
|
||||
}
|
||||
|
||||
// GetUserByID gets a user by ID (admin only)
|
||||
// @Summary Get user by ID
|
||||
// @Description Get user details by ID (admin only)
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path string true "User ID"
|
||||
// @Success 200 {object} response.APIResponse{data=UserResponse}
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 403 {object} response.APIResponse
|
||||
// @Failure 404 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/admin/{id} [get]
|
||||
func (h *Handler) GetUserByID(c echo.Context) error {
|
||||
idStr := c.Param("id")
|
||||
userID, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid user ID", "")
|
||||
}
|
||||
|
||||
user, err := h.service.GetUserByID(c.Request().Context(), userID)
|
||||
if err != nil {
|
||||
return response.NotFound(c, "User not found")
|
||||
}
|
||||
|
||||
return response.Success(c, user.ToResponse(), "User retrieved successfully")
|
||||
}
|
||||
|
||||
// UpdateUser updates a user (admin only)
|
||||
// @Summary Update user
|
||||
// @Description Update user information (admin only)
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path string true "User ID"
|
||||
// @Param user body UpdateUserForm true "User update data"
|
||||
// @Success 200 {object} response.APIResponse{data=UserResponse}
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 403 {object} response.APIResponse
|
||||
// @Failure 404 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/admin/{id} [put]
|
||||
func (h *Handler) UpdateUser(c echo.Context) error {
|
||||
// TODO: Get current user ID from JWT token
|
||||
currentUserID := uuid.New() // Placeholder
|
||||
|
||||
idStr := c.Param("id")
|
||||
userID, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid user ID", "")
|
||||
}
|
||||
|
||||
var form UpdateUserForm
|
||||
if err := c.Bind(&form); err != nil {
|
||||
return response.BadRequest(c, "Invalid request format", "")
|
||||
}
|
||||
|
||||
// Validate form
|
||||
if _, err := govalidator.ValidateStruct(form); err != nil {
|
||||
return response.ValidationError(c, err.Error(), "")
|
||||
}
|
||||
|
||||
// Call service
|
||||
user, err := h.service.UpdateUser(c.Request().Context(), userID, &form, ¤tUserID)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, err.Error(), "")
|
||||
}
|
||||
|
||||
return response.Success(c, user.ToResponse(), "User updated successfully")
|
||||
}
|
||||
|
||||
// DeleteUser deletes a user (admin only)
|
||||
// @Summary Delete user
|
||||
// @Description Delete a user (admin only)
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path string true "User ID"
|
||||
// @Success 200 {object} response.APIResponse
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 403 {object} response.APIResponse
|
||||
// @Failure 404 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/admin/{id} [delete]
|
||||
func (h *Handler) DeleteUser(c echo.Context) error {
|
||||
// TODO: Get current user ID from JWT token
|
||||
currentUserID := uuid.New() // Placeholder
|
||||
|
||||
idStr := c.Param("id")
|
||||
userID, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid user ID", "")
|
||||
}
|
||||
|
||||
err = h.service.DeleteUser(c.Request().Context(), userID, ¤tUserID)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, err.Error(), "")
|
||||
}
|
||||
|
||||
return response.Success(c, map[string]interface{}{
|
||||
"message": "User deleted successfully",
|
||||
}, "User deleted successfully")
|
||||
}
|
||||
|
||||
// UpdateUserStatus updates user status (admin only)
|
||||
// @Summary Update user status
|
||||
// @Description Update user account status (admin only)
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path string true "User ID"
|
||||
// @Param status body UpdateUserStatusForm true "Status update data"
|
||||
// @Success 200 {object} response.APIResponse
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 403 {object} response.APIResponse
|
||||
// @Failure 404 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/admin/{id}/status [put]
|
||||
func (h *Handler) UpdateUserStatus(c echo.Context) error {
|
||||
// TODO: Get current user ID from JWT token
|
||||
currentUserID := uuid.New() // Placeholder
|
||||
|
||||
idStr := c.Param("id")
|
||||
userID, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid user ID", "")
|
||||
}
|
||||
|
||||
var form UpdateUserStatusForm
|
||||
if err := c.Bind(&form); err != nil {
|
||||
return response.BadRequest(c, "Invalid request format", "")
|
||||
}
|
||||
|
||||
// Validate form
|
||||
if _, err := govalidator.ValidateStruct(form); err != nil {
|
||||
return response.ValidationError(c, err.Error(), "")
|
||||
}
|
||||
|
||||
// Call service
|
||||
err = h.service.UpdateUserStatus(c.Request().Context(), userID, &form, ¤tUserID)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, err.Error(), "")
|
||||
}
|
||||
|
||||
return response.Success(c, map[string]interface{}{
|
||||
"message": "User status updated successfully",
|
||||
}, "User status updated successfully")
|
||||
}
|
||||
|
||||
// UpdateUserRole updates user role (admin only)
|
||||
// @Summary Update user role
|
||||
// @Description Update user role (admin only)
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path string true "User ID"
|
||||
// @Param role body UpdateUserRoleForm true "Role update data"
|
||||
// @Success 200 {object} response.APIResponse
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 403 {object} response.APIResponse
|
||||
// @Failure 404 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/admin/{id}/role [put]
|
||||
func (h *Handler) UpdateUserRole(c echo.Context) error {
|
||||
// TODO: Get current user ID from JWT token
|
||||
currentUserID := uuid.New() // Placeholder
|
||||
|
||||
idStr := c.Param("id")
|
||||
userID, err := uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid user ID", "")
|
||||
}
|
||||
|
||||
var form UpdateUserRoleForm
|
||||
if err := c.Bind(&form); err != nil {
|
||||
return response.BadRequest(c, "Invalid request format", "")
|
||||
}
|
||||
|
||||
// Validate form
|
||||
if _, err := govalidator.ValidateStruct(form); err != nil {
|
||||
return response.ValidationError(c, err.Error(), "")
|
||||
}
|
||||
|
||||
// Call service
|
||||
err = h.service.UpdateUserRole(c.Request().Context(), userID, &form, ¤tUserID)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, err.Error(), "")
|
||||
}
|
||||
|
||||
return response.Success(c, map[string]interface{}{
|
||||
"message": "User role updated successfully",
|
||||
}, "User role updated successfully")
|
||||
}
|
||||
|
||||
// GetUsersByCompanyID gets users by company ID (admin only)
|
||||
// @Summary Get users by company ID
|
||||
// @Description Get users belonging to a specific company (admin only)
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param company_id path string true "Company ID"
|
||||
// @Param limit query int false "Limit results"
|
||||
// @Param offset query int false "Offset results"
|
||||
// @Success 200 {object} response.APIResponse
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 403 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/admin/company/{company_id} [get]
|
||||
func (h *Handler) GetUsersByCompanyID(c echo.Context) error {
|
||||
companyIDStr := c.Param("company_id")
|
||||
companyID, err := uuid.Parse(companyIDStr)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid company ID", "")
|
||||
}
|
||||
|
||||
// Get query parameters
|
||||
limitStr := c.QueryParam("limit")
|
||||
if limitStr == "" {
|
||||
limitStr = "20"
|
||||
}
|
||||
offsetStr := c.QueryParam("offset")
|
||||
if offsetStr == "" {
|
||||
offsetStr = "0"
|
||||
}
|
||||
|
||||
limit, err := strconv.Atoi(limitStr)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid limit parameter", "")
|
||||
}
|
||||
|
||||
offset, err := strconv.Atoi(offsetStr)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid offset parameter", "")
|
||||
}
|
||||
|
||||
// Call service
|
||||
users, total, err := h.service.GetUsersByCompanyID(c.Request().Context(), companyID, limit, offset)
|
||||
if err != nil {
|
||||
return response.InternalServerError(c, "Failed to get users by company")
|
||||
}
|
||||
|
||||
// Convert to responses
|
||||
var userResponses []*UserResponse
|
||||
for _, user := range users {
|
||||
userResponses = append(userResponses, user.ToResponse())
|
||||
}
|
||||
|
||||
return response.SuccessWithMeta(c, map[string]interface{}{
|
||||
"users": userResponses,
|
||||
}, &response.Meta{
|
||||
Total: int(total),
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
}, "Users retrieved successfully")
|
||||
}
|
||||
|
||||
// GetUsersByRole gets users by role (admin only)
|
||||
// @Summary Get users by role
|
||||
// @Description Get users with a specific role (admin only)
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param role path string true "User role"
|
||||
// @Param limit query int false "Limit results"
|
||||
// @Param offset query int false "Offset results"
|
||||
// @Success 200 {object} response.APIResponse
|
||||
// @Failure 400 {object} response.APIResponse
|
||||
// @Failure 401 {object} response.APIResponse
|
||||
// @Failure 403 {object} response.APIResponse
|
||||
// @Failure 500 {object} response.APIResponse
|
||||
// @Router /users/admin/role/{role} [get]
|
||||
func (h *Handler) GetUsersByRole(c echo.Context) error {
|
||||
roleStr := c.Param("role")
|
||||
role := UserRole(roleStr)
|
||||
|
||||
// Validate role
|
||||
if !h.validator.IsValidRole(role) {
|
||||
return response.BadRequest(c, "Invalid role", "")
|
||||
}
|
||||
|
||||
// Get query parameters
|
||||
limitStr := c.QueryParam("limit")
|
||||
if limitStr == "" {
|
||||
limitStr = "20"
|
||||
}
|
||||
offsetStr := c.QueryParam("offset")
|
||||
if offsetStr == "" {
|
||||
offsetStr = "0"
|
||||
}
|
||||
|
||||
limit, err := strconv.Atoi(limitStr)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid limit parameter", "")
|
||||
}
|
||||
|
||||
offset, err := strconv.Atoi(offsetStr)
|
||||
if err != nil {
|
||||
return response.BadRequest(c, "Invalid offset parameter", "")
|
||||
}
|
||||
|
||||
// Call service
|
||||
users, err := h.service.GetUsersByRole(c.Request().Context(), role, limit, offset)
|
||||
if err != nil {
|
||||
return response.InternalServerError(c, "Failed to get users by role")
|
||||
}
|
||||
|
||||
// Convert to responses
|
||||
var userResponses []*UserResponse
|
||||
for _, user := range users {
|
||||
userResponses = append(userResponses, user.ToResponse())
|
||||
}
|
||||
|
||||
return response.SuccessWithMeta(c, map[string]interface{}{
|
||||
"users": userResponses,
|
||||
"role": role,
|
||||
}, &response.Meta{
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
}, "Users retrieved successfully")
|
||||
}
|
||||
|
||||
// AuthMiddleware and AdminMiddleware are now implemented in middleware.go
|
||||
@@ -0,0 +1,192 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"tm/pkg/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// AuthMiddleware validates JWT access tokens and extracts user information
|
||||
func (h *Handler) AuthMiddleware() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
// Extract token from Authorization header
|
||||
authHeader := c.Request().Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
return response.Unauthorized(c, "Authorization header required")
|
||||
}
|
||||
|
||||
// Check if it's a Bearer token
|
||||
if !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
return response.Unauthorized(c, "Invalid authorization format. Use 'Bearer <token>'")
|
||||
}
|
||||
|
||||
// Extract the token
|
||||
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
|
||||
// Validate the access token
|
||||
validationResult, err := h.authService.ValidateAccessToken(tokenString)
|
||||
if err != nil {
|
||||
h.logger.Error("Token validation error", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return response.Unauthorized(c, "Invalid token")
|
||||
}
|
||||
|
||||
if !validationResult.Valid {
|
||||
if validationResult.Expired {
|
||||
return response.Unauthorized(c, "Token expired")
|
||||
}
|
||||
return response.Unauthorized(c, validationResult.Error)
|
||||
}
|
||||
|
||||
// Extract user information from token
|
||||
userID, err := uuid.Parse(validationResult.Claims.UserID)
|
||||
if err != nil {
|
||||
h.logger.Error("Failed to parse user ID from token", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return response.Unauthorized(c, "Invalid token format")
|
||||
}
|
||||
|
||||
// Store user information in context for handlers to use
|
||||
c.Set("user_id", userID)
|
||||
c.Set("user_email", validationResult.Claims.Email)
|
||||
c.Set("user_role", validationResult.Claims.Role)
|
||||
c.Set("company_id", validationResult.Claims.CompanyID)
|
||||
c.Set("access_token", tokenString)
|
||||
|
||||
// Continue to next handler
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AdminMiddleware checks if the authenticated user has admin role
|
||||
func (h *Handler) AdminMiddleware() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
// Get user role from context (set by AuthMiddleware)
|
||||
userRole, ok := c.Get("user_role").(string)
|
||||
if !ok {
|
||||
return response.Unauthorized(c, "User role not found in context")
|
||||
}
|
||||
|
||||
// Check if user has admin role
|
||||
if userRole != string(UserRoleAdmin) {
|
||||
return response.Forbidden(c, "Admin access required")
|
||||
}
|
||||
|
||||
// Continue to next handler
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RoleMiddleware checks if the authenticated user has the required role
|
||||
func (h *Handler) RoleMiddleware(requiredRole UserRole) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
// Get user role from context (set by AuthMiddleware)
|
||||
userRole, ok := c.Get("user_role").(string)
|
||||
if !ok {
|
||||
return response.Unauthorized(c, "User role not found in context")
|
||||
}
|
||||
|
||||
// Check if user has the required role
|
||||
if userRole != string(requiredRole) {
|
||||
return response.Forbidden(c, "Insufficient permissions")
|
||||
}
|
||||
|
||||
// Continue to next handler
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CompanyAccessMiddleware checks if the authenticated user has access to the specified company
|
||||
func (h *Handler) CompanyAccessMiddleware() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
// Get user information from context
|
||||
userRole, ok := c.Get("user_role").(string)
|
||||
if !ok {
|
||||
return response.Unauthorized(c, "User role not found in context")
|
||||
}
|
||||
|
||||
// Admin users have access to all companies
|
||||
if userRole == string(UserRoleAdmin) {
|
||||
return next(c)
|
||||
}
|
||||
|
||||
// Get company ID from context
|
||||
userCompanyID, ok := c.Get("company_id").(string)
|
||||
if !ok || userCompanyID == "" {
|
||||
return response.Forbidden(c, "Company access not available")
|
||||
}
|
||||
|
||||
// Get company ID from URL parameter
|
||||
requestedCompanyID := c.Param("company_id")
|
||||
if requestedCompanyID == "" {
|
||||
// If no company ID in URL, allow access to user's own company
|
||||
return next(c)
|
||||
}
|
||||
|
||||
// Check if user has access to the requested company
|
||||
if userCompanyID != requestedCompanyID {
|
||||
return response.Forbidden(c, "Access to this company not allowed")
|
||||
}
|
||||
|
||||
// Continue to next handler
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetUserIDFromContext extracts user ID from Echo context
|
||||
func GetUserIDFromContext(c echo.Context) (uuid.UUID, error) {
|
||||
userID, ok := c.Get("user_id").(uuid.UUID)
|
||||
if !ok {
|
||||
return uuid.Nil, echo.NewHTTPError(http.StatusUnauthorized, "User ID not found in context")
|
||||
}
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
// GetUserEmailFromContext extracts user email from Echo context
|
||||
func GetUserEmailFromContext(c echo.Context) (string, error) {
|
||||
userEmail, ok := c.Get("user_email").(string)
|
||||
if !ok {
|
||||
return "", echo.NewHTTPError(http.StatusUnauthorized, "User email not found in context")
|
||||
}
|
||||
return userEmail, nil
|
||||
}
|
||||
|
||||
// GetUserRoleFromContext extracts user role from Echo context
|
||||
func GetUserRoleFromContext(c echo.Context) (string, error) {
|
||||
userRole, ok := c.Get("user_role").(string)
|
||||
if !ok {
|
||||
return "", echo.NewHTTPError(http.StatusUnauthorized, "User role not found in context")
|
||||
}
|
||||
return userRole, nil
|
||||
}
|
||||
|
||||
// GetCompanyIDFromContext extracts company ID from Echo context
|
||||
func GetCompanyIDFromContext(c echo.Context) (string, error) {
|
||||
companyID, ok := c.Get("company_id").(string)
|
||||
if !ok {
|
||||
return "", echo.NewHTTPError(http.StatusUnauthorized, "Company ID not found in context")
|
||||
}
|
||||
return companyID, nil
|
||||
}
|
||||
|
||||
// GetAccessTokenFromContext extracts access token from Echo context
|
||||
func GetAccessTokenFromContext(c echo.Context) (string, error) {
|
||||
accessToken, ok := c.Get("access_token").(string)
|
||||
if !ok {
|
||||
return "", echo.NewHTTPError(http.StatusUnauthorized, "Access token not found in context")
|
||||
}
|
||||
return accessToken, nil
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
"tm/pkg/logger"
|
||||
mongopkg "tm/pkg/mongo"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
// Repository defines methods for user data access
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, user *User) error
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*User, error)
|
||||
GetByEmail(ctx context.Context, email string) (*User, error)
|
||||
GetByUsername(ctx context.Context, username string) (*User, error)
|
||||
Update(ctx context.Context, user *User) error
|
||||
Delete(ctx context.Context, id uuid.UUID) error
|
||||
List(ctx context.Context, limit, offset int) ([]*User, error)
|
||||
Search(ctx context.Context, search string, status *string, role *string, companyID *uuid.UUID, limit, offset int, sortBy, sortOrder string) ([]*User, error)
|
||||
GetByCompanyID(ctx context.Context, companyID uuid.UUID, limit, offset int) ([]*User, error)
|
||||
GetByRole(ctx context.Context, role UserRole, limit, offset int) ([]*User, error)
|
||||
UpdateLastLogin(ctx context.Context, id uuid.UUID) error
|
||||
CountByCompanyID(ctx context.Context, companyID uuid.UUID) (int64, error)
|
||||
}
|
||||
|
||||
// userRepository implements the Repository interface
|
||||
type userRepository struct {
|
||||
collection *mongo.Collection
|
||||
logger logger.Logger
|
||||
}
|
||||
|
||||
// NewUserRepository creates a new user repository
|
||||
func NewUserRepository(mongoManager *mongopkg.ConnectionManager, logger logger.Logger) Repository {
|
||||
collection := mongoManager.GetCollection("users")
|
||||
|
||||
// Create indexes
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Email index (unique)
|
||||
emailIndex := mongo.IndexModel{
|
||||
Keys: bson.D{{Key: "email", Value: 1}},
|
||||
Options: options.Index().SetUnique(true),
|
||||
}
|
||||
|
||||
// Username index (unique)
|
||||
usernameIndex := mongo.IndexModel{
|
||||
Keys: bson.D{{Key: "username", Value: 1}},
|
||||
Options: options.Index().SetUnique(true),
|
||||
}
|
||||
|
||||
// Company ID index
|
||||
companyIndex := mongo.IndexModel{
|
||||
Keys: bson.D{{Key: "company_id", Value: 1}},
|
||||
}
|
||||
|
||||
// Role index
|
||||
roleIndex := mongo.IndexModel{
|
||||
Keys: bson.D{{Key: "role", Value: 1}},
|
||||
}
|
||||
|
||||
// Status index
|
||||
statusIndex := mongo.IndexModel{
|
||||
Keys: bson.D{{Key: "status", Value: 1}},
|
||||
}
|
||||
|
||||
// Created at index
|
||||
createdAtIndex := mongo.IndexModel{
|
||||
Keys: bson.D{{Key: "created_at", Value: -1}},
|
||||
}
|
||||
|
||||
// Full text search index
|
||||
textIndex := mongo.IndexModel{
|
||||
Keys: bson.D{
|
||||
{Key: "full_name", Value: "text"},
|
||||
{Key: "email", Value: "text"},
|
||||
{Key: "username", Value: "text"},
|
||||
{Key: "department", Value: "text"},
|
||||
{Key: "position", Value: "text"},
|
||||
},
|
||||
}
|
||||
|
||||
_, err := collection.Indexes().CreateMany(ctx, []mongo.IndexModel{
|
||||
emailIndex,
|
||||
usernameIndex,
|
||||
companyIndex,
|
||||
roleIndex,
|
||||
statusIndex,
|
||||
createdAtIndex,
|
||||
textIndex,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
logger.Warn("Failed to create user indexes", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
return &userRepository{
|
||||
collection: collection,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates a new user
|
||||
func (r *userRepository) Create(ctx context.Context, user *User) error {
|
||||
// Set created/updated timestamps using Unix timestamps
|
||||
now := time.Now().Unix()
|
||||
user.CreatedAt = now
|
||||
user.UpdatedAt = now
|
||||
|
||||
// Insert user
|
||||
_, err := r.collection.InsertOne(ctx, user)
|
||||
if err != nil {
|
||||
if mongo.IsDuplicateKeyError(err) {
|
||||
return errors.New("user already exists")
|
||||
}
|
||||
r.logger.Error("Failed to create user", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"email": user.Email,
|
||||
"user_id": user.ID.String(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
r.logger.Info("User created successfully", map[string]interface{}{
|
||||
"user_id": user.ID.String(),
|
||||
"email": user.Email,
|
||||
"role": user.Role,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByID retrieves a user by ID
|
||||
func (r *userRepository) GetByID(ctx context.Context, id uuid.UUID) (*User, error) {
|
||||
var user User
|
||||
|
||||
filter := bson.M{"_id": id}
|
||||
err := r.collection.FindOne(ctx, filter).Decode(&user)
|
||||
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
r.logger.Error("Failed to get user by ID", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": id.String(),
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// GetByEmail retrieves a user by email
|
||||
func (r *userRepository) GetByEmail(ctx context.Context, email string) (*User, error) {
|
||||
var user User
|
||||
|
||||
filter := bson.M{"email": email}
|
||||
err := r.collection.FindOne(ctx, filter).Decode(&user)
|
||||
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
r.logger.Error("Failed to get user by email", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"email": email,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// GetByUsername retrieves a user by username
|
||||
func (r *userRepository) GetByUsername(ctx context.Context, username string) (*User, error) {
|
||||
var user User
|
||||
|
||||
filter := bson.M{"username": username}
|
||||
err := r.collection.FindOne(ctx, filter).Decode(&user)
|
||||
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
r.logger.Error("Failed to get user by username", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"username": username,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// Update updates a user
|
||||
func (r *userRepository) Update(ctx context.Context, user *User) error {
|
||||
// Set updated timestamp using Unix timestamp
|
||||
user.UpdatedAt = time.Now().Unix()
|
||||
|
||||
filter := bson.M{"_id": user.ID}
|
||||
update := bson.M{"$set": user}
|
||||
|
||||
result, err := r.collection.UpdateOne(ctx, filter, update)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to update user", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": user.ID.String(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
if result.MatchedCount == 0 {
|
||||
return errors.New("user not found")
|
||||
}
|
||||
|
||||
r.logger.Info("User updated successfully", map[string]interface{}{
|
||||
"user_id": user.ID.String(),
|
||||
"email": user.Email,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete deletes a user (soft delete by setting status to inactive)
|
||||
func (r *userRepository) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
filter := bson.M{"_id": id}
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"status": UserStatusInactive,
|
||||
"updated_at": time.Now().Unix(),
|
||||
},
|
||||
}
|
||||
|
||||
result, err := r.collection.UpdateOne(ctx, filter, update)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to delete user", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": id.String(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
if result.MatchedCount == 0 {
|
||||
return errors.New("user not found")
|
||||
}
|
||||
|
||||
r.logger.Info("User deleted successfully", map[string]interface{}{
|
||||
"user_id": id.String(),
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// List retrieves users with pagination
|
||||
func (r *userRepository) List(ctx context.Context, limit, offset int) ([]*User, error) {
|
||||
var users []*User
|
||||
|
||||
// Build options
|
||||
opts := options.Find()
|
||||
opts.SetLimit(int64(limit))
|
||||
opts.SetSkip(int64(offset))
|
||||
opts.SetSort(bson.D{{Key: "created_at", Value: -1}}) // Sort by created_at desc
|
||||
|
||||
// Only active users by default
|
||||
filter := bson.M{"status": bson.M{"$ne": UserStatusInactive}}
|
||||
|
||||
cursor, err := r.collection.Find(ctx, filter, opts)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to list users", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
|
||||
if err = cursor.All(ctx, &users); err != nil {
|
||||
r.logger.Error("Failed to decode users", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// Search retrieves users with search and filters
|
||||
func (r *userRepository) Search(ctx context.Context, search string, status *string, role *string, companyID *uuid.UUID, limit, offset int, sortBy, sortOrder string) ([]*User, error) {
|
||||
var users []*User
|
||||
|
||||
// Build filter
|
||||
filter := bson.M{}
|
||||
|
||||
if search != "" {
|
||||
filter["$text"] = bson.M{"$search": search}
|
||||
}
|
||||
|
||||
if status != nil {
|
||||
filter["status"] = *status
|
||||
}
|
||||
|
||||
if role != nil {
|
||||
filter["role"] = *role
|
||||
}
|
||||
|
||||
if companyID != nil {
|
||||
filter["company_id"] = *companyID
|
||||
}
|
||||
|
||||
// Build options
|
||||
opts := options.Find()
|
||||
opts.SetLimit(int64(limit))
|
||||
opts.SetSkip(int64(offset))
|
||||
|
||||
// Set sort
|
||||
if sortBy != "" {
|
||||
sortValue := 1
|
||||
if sortOrder == "desc" {
|
||||
sortValue = -1
|
||||
}
|
||||
opts.SetSort(bson.D{{Key: sortBy, Value: sortValue}})
|
||||
} else {
|
||||
opts.SetSort(bson.D{{Key: "created_at", Value: -1}}) // Default sort
|
||||
}
|
||||
|
||||
cursor, err := r.collection.Find(ctx, filter, opts)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to search users", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"search": search,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
|
||||
if err = cursor.All(ctx, &users); err != nil {
|
||||
r.logger.Error("Failed to decode users from search", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// GetByCompanyID retrieves users by company ID with pagination
|
||||
func (r *userRepository) GetByCompanyID(ctx context.Context, companyID uuid.UUID, limit, offset int) ([]*User, error) {
|
||||
var users []*User
|
||||
|
||||
// Build options
|
||||
opts := options.Find()
|
||||
opts.SetLimit(int64(limit))
|
||||
opts.SetSkip(int64(offset))
|
||||
opts.SetSort(bson.D{{Key: "created_at", Value: -1}}) // Sort by created_at desc
|
||||
|
||||
// Filter by company ID and active status
|
||||
filter := bson.M{
|
||||
"company_id": companyID,
|
||||
"status": bson.M{"$ne": UserStatusInactive},
|
||||
}
|
||||
|
||||
cursor, err := r.collection.Find(ctx, filter, opts)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to get users by company ID", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"company_id": companyID.String(),
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
|
||||
if err = cursor.All(ctx, &users); err != nil {
|
||||
r.logger.Error("Failed to decode users by company", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"company_id": companyID.String(),
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// GetByRole retrieves users by role with pagination
|
||||
func (r *userRepository) GetByRole(ctx context.Context, role UserRole, limit, offset int) ([]*User, error) {
|
||||
var users []*User
|
||||
|
||||
// Build options
|
||||
opts := options.Find()
|
||||
opts.SetLimit(int64(limit))
|
||||
opts.SetSkip(int64(offset))
|
||||
opts.SetSort(bson.D{{Key: "created_at", Value: -1}}) // Sort by created_at desc
|
||||
|
||||
// Filter by role and active status
|
||||
filter := bson.M{
|
||||
"role": role,
|
||||
"status": bson.M{"$ne": UserStatusInactive},
|
||||
}
|
||||
|
||||
cursor, err := r.collection.Find(ctx, filter, opts)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to get users by role", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"role": role,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
|
||||
if err = cursor.All(ctx, &users); err != nil {
|
||||
r.logger.Error("Failed to decode users by role", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"role": role,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// UpdateLastLogin updates the last login timestamp
|
||||
func (r *userRepository) UpdateLastLogin(ctx context.Context, id uuid.UUID) error {
|
||||
filter := bson.M{"_id": id}
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"last_login_at": time.Now().Unix(),
|
||||
"updated_at": time.Now().Unix(),
|
||||
},
|
||||
}
|
||||
|
||||
result, err := r.collection.UpdateOne(ctx, filter, update)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to update last login", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"user_id": id.String(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
if result.MatchedCount == 0 {
|
||||
return errors.New("user not found")
|
||||
}
|
||||
|
||||
r.logger.Info("Last login updated successfully", map[string]interface{}{
|
||||
"user_id": id.String(),
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CountByCompanyID counts users by company ID
|
||||
func (r *userRepository) CountByCompanyID(ctx context.Context, companyID uuid.UUID) (int64, error) {
|
||||
filter := bson.M{
|
||||
"company_id": companyID,
|
||||
"status": bson.M{"$ne": UserStatusInactive},
|
||||
}
|
||||
|
||||
count, err := r.collection.CountDocuments(ctx, filter)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to count users by company ID", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"company_id": companyID.String(),
|
||||
})
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package user
|
||||
|
||||
// ValidationService defines validation methods for user operations
|
||||
type ValidationService interface {
|
||||
IsValidRole(role UserRole) bool
|
||||
IsValidStatus(status UserStatus) bool
|
||||
}
|
||||
|
||||
// validationService implements the ValidationService interface
|
||||
type validationService struct{}
|
||||
|
||||
// NewValidationService creates a new validation service
|
||||
func NewValidationService() ValidationService {
|
||||
return &validationService{}
|
||||
}
|
||||
|
||||
// IsValidRole checks if a user role is valid
|
||||
func (v *validationService) IsValidRole(role UserRole) bool {
|
||||
switch role {
|
||||
case UserRoleAdmin, UserRoleManager, UserRoleOperator, UserRoleViewer:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// IsValidStatus checks if a user status is valid
|
||||
func (v *validationService) IsValidStatus(status UserStatus) bool {
|
||||
switch status {
|
||||
case UserStatusActive, UserStatusInactive, UserStatusSuspended:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user