package controller import ( "net/http" "users_management/m/middleware" "users_management/m/usecase" "users_management/m/utils/common" "github.com/gin-gonic/gin" ) type UserManagementController struct { userUC usecase.UsersUsecase rg *gin.RouterGroup } func NewUserManagementController(userUC usecase.UsersUsecase, rg *gin.RouterGroup) *UserManagementController { return &UserManagementController{ userUC: userUC, rg: rg, } } func (c *UserManagementController) Route() { users := c.rg.Group("/user-management") { // Only superadmin can manage user roles users.PUT("/role", middleware.RequireSuperAdminRole(), c.updateUserRole) // Admins and superadmins can view all users users.GET("/users", middleware.RequireAdminRole(), c.getAllUsers) // Users can view their own profile users.GET("/profile", c.getMyProfile) } } type UpdateRoleRequest struct { NomorInduk string `json:"nomor_induk" binding:"required"` RoleName string `json:"role_name" binding:"required"` } func (c *UserManagementController) updateUserRole(ctx *gin.Context) { var req UpdateRoleRequest if err := ctx.ShouldBindJSON(&req); err != nil { common.ErrorResponses(ctx, http.StatusBadRequest, err.Error()) return } err := c.userUC.UpdateUserRole(req.NomorInduk, req.RoleName) if err != nil { common.ErrorResponses(ctx, http.StatusInternalServerError, err.Error()) return } common.SingleResponses(ctx, "User role updated successfully", nil) } func (c *UserManagementController) getAllUsers(ctx *gin.Context) { users, err := c.userUC.GetAllUsers() if err != nil { common.ErrorResponses(ctx, http.StatusInternalServerError, err.Error()) return } common.SingleResponses(ctx, "Users retrieved successfully", users) } func (c *UserManagementController) getMyProfile(ctx *gin.Context) { userID, exists := ctx.Get("userID") if !exists { common.ErrorResponses(ctx, http.StatusUnauthorized, "User ID not found") return } nomorInduk, ok := userID.(string) if !ok { common.ErrorResponses(ctx, http.StatusBadRequest, "Invalid user ID") return } user, err := c.userUC.GetUserByNomorInduk(nomorInduk) if err != nil { common.ErrorResponses(ctx, http.StatusNotFound, "User not found") return } common.SingleResponses(ctx, "User profile retrieved successfully", user) }