package user import ( "context" "errors" "fmt" "io" "net/http" "path/filepath" "strconv" "strings" "time" "online-back/internal/appresult" "online-back/internal/config" "online-back/internal/identity/rbac" "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" minioUpload "online-back/pkg/minio" "github.com/gin-gonic/gin" "github.com/jackc/pgx/v4" "github.com/minio/minio-go/v7" ) const ( baseURL = "/users" fileUploadURL = "/file" publicFileURL = "/file/:file_name" ) type handler struct { logger *logging.Logger repository Repository } func NewHandler(logger *logging.Logger, repository Repository) *handler { return &handler{logger: logger, repository: repository} } func (h *handler) Register(router *gin.RouterGroup) { group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Users)) group.GET("", h.list) group.GET("/staff", h.listStaff) group.GET("/:id", h.getByID) group.POST("", h.create) group.PUT("/:id", h.update) group.PUT("/:id/role", h.setRole) group.DELETE("/:id", h.delete) // Operators pick a client for a new order without holding users. rbac.Group(router, baseURL+"/clients", rbac.Staff()).GET("", h.listClients) // Upload/delete stay on the admin API (JWT). GET is public at /file/:file_name // so nginx can serve avatars as https://host/file/. files := rbac.Group(router, fileUploadURL, rbac.Authenticated()) files.POST("", h.fileUpload) files.DELETE("/:id", h.deleteFile) } func (h *handler) RegisterPublic(engine *gin.Engine) { engine.GET(publicFileURL, h.getFile) } // list godoc // @Summary List users // @Description Returns paginated users, including roleId. All-scope callers see users of every role; branch-scope callers see role=user only, scoped to their branches. // @Tags user // @Produce json // @Security BearerAuth // @Param search query string false "Search by username, first name, or last name" // @Param username query string false "Alias for search" // @Param page query int false "Page number" default(1) // @Param limit query int false "Items per page" default(10) // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /users [get] func (h *handler) list(c *gin.Context) { filter, ok := parseListFilter(c) if !ok { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } filter.AllRoles = rbac.HasAllScope(c) rbac.BindBranchIDs(c, &filter.BranchIds) result, err := h.repository.List(c.Request.Context(), filter) if err != nil { h.logger.Errorf("list users failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } // listClients godoc // @Summary List client users // @Description Returns paginated client users (role user, not assigned to any branch), including roleId // @Tags user // @Produce json // @Security BearerAuth // @Param search query string false "Search by username, first name, or last name" // @Param username query string false "Alias for search" // @Param page query int false "Page number" default(1) // @Param limit query int false "Items per page" default(10) // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /users/clients [get] func (h *handler) listClients(c *gin.Context) { filter, ok := parseListFilter(c) if !ok { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } item, err := h.repository.GetByRole(c.Request.Context(), "user", filter) if err != nil { h.logger.Errorf("list client users failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } // listStaff godoc // @Summary List staff users // @Description Returns paginated users assigned to branches (from branch_user), including each user's branches and roleId. // @Tags user // @Produce json // @Security BearerAuth // @Param search query string false "Search by username, first name, or last name" // @Param username query string false "Alias for search" // @Param page query int false "Page number" default(1) // @Param limit query int false "Items per page" default(10) // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /users/staff [get] func (h *handler) listStaff(c *gin.Context) { filter, ok := parseListFilter(c) if !ok { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } rbac.BindBranchIDs(c, &filter.BranchIds) result, err := h.repository.ListStaff(c.Request.Context(), filter) if err != nil { h.logger.Errorf("list staff users failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } // getByID godoc // @Summary Get user by ID // @Description Returns a single user with assigned branches, roleId, and effective permissions // @Tags user // @Produce json // @Security BearerAuth // @Param id path int true "User ID" // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 404 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /users/{id} [get] func (h *handler) getByID(c *gin.Context) { id, ok := shared.ParseID(c.Param("id")) if !ok { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } item, err := h.repository.GetByID(c.Request.Context(), id) if errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return } if err != nil { h.logger.Errorf("get user failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } if !rbac.GuardUser(c, item.Id) { return } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } // create godoc // @Summary Create user // @Description Creates a new user. The role (roleId or role code, default "user") must be one the caller could grant: no wider scope, no permission the caller lacks, superadmin only from a superadmin. // @Tags user // @Accept json // @Produce json // @Security BearerAuth // @Param body body CreateUserDTO true "User payload" // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 201 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 403 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /users [post] func (h *handler) create(c *gin.Context) { var dto CreateUserDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } next, ok := h.requestedRole(c, dto.RoleId, dto.Role, "user") if !ok { return } if !h.authorizeRoleChange(c, 0, nil, next) { return } item, err := h.repository.Create(c.Request.Context(), dto, next.ID) if err != nil { h.logger.Errorf("create user failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } c.JSON(http.StatusCreated, appresult.SuccessWithData(item)) } // update godoc // @Summary Update user // @Description Updates an existing user. Sending roleId or role changes the role (same rules as create); sending neither keeps it. Callers cannot manage a user whose role they could not grant, nor change their own role. // @Tags user // @Accept json // @Produce json // @Security BearerAuth // @Param id path int true "User ID" // @Param body body UpdateUserDTO true "User payload" // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 403 {object} appresult.AppError // @Failure 404 {object} appresult.AppError // @Failure 409 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /users/{id} [put] func (h *handler) update(c *gin.Context) { id, ok := shared.ParseID(c.Param("id")) if !ok { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } if rbac.HasBranchScope(c) && !rbac.GuardUser(c, id) { return } var dto UpdateUserDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } current, ok := h.currentRole(c, id) if !ok { return } next := current if dto.RoleId != nil || strings.TrimSpace(dto.Role) != "" { if next, ok = h.requestedRole(c, dto.RoleId, dto.Role, ""); !ok { return } } if !h.authorizeRoleChange(c, id, current, next) { return } item, err := h.repository.Update(c.Request.Context(), id, dto, next.ID) if errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return } if err != nil { h.logger.Errorf("update user failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } // setRole godoc // @Summary Set user role // @Description Gives the user exactly one role. Same rules as create/update. // @Tags user // @Accept json // @Produce json // @Security BearerAuth // @Param id path int true "User ID" // @Param body body SetUserRoleDTO true "Role" // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 403 {object} appresult.AppError // @Failure 404 {object} appresult.AppError // @Failure 409 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /users/{id}/role [put] func (h *handler) setRole(c *gin.Context) { id, ok := shared.ParseID(c.Param("id")) if !ok { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } if rbac.HasBranchScope(c) && !rbac.GuardUser(c, id) { return } var dto SetUserRoleDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } current, ok := h.currentRole(c, id) if !ok { return } next, ok := h.requestedRole(c, &dto.RoleId, "", "") if !ok { return } if !h.authorizeRoleChange(c, id, current, next) { return } if err := h.repository.SetRole(c.Request.Context(), id, next.ID); errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return } else if err != nil { h.logger.Errorf("set user role failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } item, err := h.repository.GetByID(c.Request.Context(), id) if err != nil { h.logger.Errorf("get user after role change failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } // delete godoc // @Summary Delete user // @Description Deletes a user. Callers cannot delete themselves, a user whose role they could not grant, or the last superadmin. // @Tags user // @Produce json // @Security BearerAuth // @Param id path int true "User ID" // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 403 {object} appresult.AppError // @Failure 404 {object} appresult.AppError // @Failure 409 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /users/{id} [delete] func (h *handler) delete(c *gin.Context) { id, ok := shared.ParseID(c.Param("id")) if !ok { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } if rbac.HasBranchScope(c) && !rbac.GuardUser(c, id) { return } current, ok := h.currentRole(c, id) if !ok { return } p := rbac.PrincipalFrom(c) if id == p.UserID { h.forbid(c, "cannot delete yourself", nil) return } if err := p.CanGrant(*current); err != nil { h.forbid(c, "cannot manage this user", err) return } if current.IsSuper && !h.otherSuperExists(c) { return } if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return } else if err != nil { h.logger.Errorf("delete user failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } c.JSON(http.StatusOK, appresult.SuccessWithData("user removed")) } // requestedRole resolves roleID (preferred) or code, falling back to // fallbackCode when both are empty. It answers 400 for an unknown role. func (h *handler) requestedRole(c *gin.Context, roleID *int64, code, fallbackCode string) (*rbac.RoleInfo, bool) { ctx := c.Request.Context() code = strings.TrimSpace(code) if code == "" { code = fallbackCode } var role *rbac.RoleInfo var err error switch { case roleID != nil: role, err = h.repository.RoleByID(ctx, *roleID) case code != "": role, err = h.repository.RoleByCode(ctx, code) } if err != nil { h.logger.Errorf("resolve role failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return nil, false } if role == nil { c.JSON(http.StatusBadRequest, appresult.ErrUnknownRole) return nil, false } return role, true } // currentRole answers 404 when the user does not exist. func (h *handler) currentRole(c *gin.Context, userID int64) (*rbac.RoleInfo, bool) { role, err := h.repository.RoleOfUser(c.Request.Context(), userID) if err != nil { h.logger.Errorf("load user role failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return nil, false } if role == nil { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return nil, false } return role, true } // authorizeRoleChange enforces the grant rules for moving user targetID // (0 = new user) from current (nil = new user) to next: // - the caller must be able to grant the user's current role, so nobody // edits a user who outranks them; // - a role change must be one the caller could grant (scope, permissions, // superadmin), must not be the caller's own role, and must not demote // the last superadmin. func (h *handler) authorizeRoleChange(c *gin.Context, targetID int64, current, next *rbac.RoleInfo) bool { p := rbac.PrincipalFrom(c) if current != nil { if err := p.CanGrant(*current); err != nil { h.forbid(c, "cannot manage this user", err) return false } if current.ID == next.ID { return true } if targetID == p.UserID { h.forbid(c, "cannot change your own role", nil) return false } } if err := p.CanGrant(*next); err != nil { h.forbid(c, "cannot grant this role", err) return false } if current != nil && current.IsSuper && !next.IsSuper { return h.otherSuperExists(c) } return true } // otherSuperExists answers 409 when removing one superadmin would leave none. func (h *handler) otherSuperExists(c *gin.Context) bool { count, err := h.repository.CountSuperUsers(c.Request.Context()) if err != nil { h.logger.Errorf("count superadmins failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return false } if count <= 1 { c.JSON(http.StatusConflict, appresult.ErrLastSuperadmin) return false } return true } func (h *handler) forbid(c *gin.Context, reason string, err error) { h.logger.Warnf("user role check denied (%s): %v", reason, err) c.JSON(http.StatusForbidden, appresult.ErrForbidden) } func parseListFilter(c *gin.Context) (ListFilter, bool) { filter := ListFilter{ Page: shared.DefaultPage, Limit: shared.DefaultLimit, } if raw := c.Query("page"); raw != "" { page, err := strconv.Atoi(raw) if err != nil || page < 1 { return ListFilter{}, false } filter.Page = page } if raw := c.Query("limit"); raw != "" { limit, err := strconv.Atoi(raw) if err != nil || limit < 1 || limit > shared.MaxLimit { return ListFilter{}, false } filter.Limit = limit } if raw := strings.TrimSpace(c.Query("search")); raw != "" { filter.Search = raw } else if raw := strings.TrimSpace(c.Query("username")); raw != "" { filter.Search = raw } return filter, true } // fileUpload godoc // @Description file upload // @Tags file-upload // // @Accept multipart/form-data // @Produce json // @Param file formData file true "this is a test file" // // @Security BearerAuth // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /file [post] func (h *handler) fileUpload(c *gin.Context) { file, header, err := c.Request.FormFile("file") if err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } defer file.Close() minioCfg := config.GetConfig().Minio minioClient, ok := h.connectMinio(c, minioCfg) if !ok { return } ctx := c.Request.Context() if err := ensureBucket(ctx, minioClient, minioCfg.Bucket); err != nil { h.logger.Errorf("ensure minio bucket failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } objectName := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(header.Filename)) contentType := header.Header.Get("Content-Type") if _, err := minioClient.PutObject(ctx, minioCfg.Bucket, objectName, file, header.Size, minio.PutObjectOptions{ContentType: contentType}); err != nil { h.logger.Errorf("upload file to minio failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } c.JSON(http.StatusOK, appresult.SuccessWithData(objectName)) } // getFile godoc // @Description download file by object name (public; not under /api/admin) // @Tags file-upload // @Produce octet-stream // @Param file_name path string true "object name" // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {file} binary // @Failure 400 {object} appresult.AppError // @Failure 404 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /file/{file_name} [get] func (h *handler) getFile(c *gin.Context) { fileName := c.Param("file_name") if fileName == "" || strings.Contains(fileName, "..") || strings.ContainsAny(fileName, "/\\") { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } minioCfg := config.GetConfig().Minio minioClient, ok := h.connectMinio(c, minioCfg) if !ok { return } object, err := minioClient.GetObject(c.Request.Context(), minioCfg.Bucket, fileName, minio.GetObjectOptions{}) if err != nil { h.logger.Errorf("get object from minio failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable) return } defer object.Close() content, err := io.ReadAll(object) if err != nil { h.logger.Errorf("read object from minio failed: %v", err) c.JSON(http.StatusNotFound, appresult.ErrNotFound) return } c.Data(http.StatusOK, http.DetectContentType(content), content) } // deleteFile godoc // @Description remove file // @Tags file-upload // @Produce json // @Param id path string true "object name" // @Security BearerAuth // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} appresult.AppSuccess // @Failure 500 {object} appresult.AppError // @Router /file/{id} [delete] func (h *handler) deleteFile(c *gin.Context) { id := c.Param("id") minioCfg := config.GetConfig().Minio minioClient, ok := h.connectMinio(c, minioCfg) if !ok { return } if err := minioClient.RemoveObject(c.Request.Context(), minioCfg.Bucket, id, minio.RemoveObjectOptions{GovernanceBypass: true}); err != nil { h.logger.Errorf("remove object from minio failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } c.JSON(http.StatusOK, appresult.SuccessWithData("file removed")) } // connectMinio opens a MinIO client, writing an error response and returning // ok=false if the connection fails so callers can bail out immediately. func (h *handler) connectMinio(c *gin.Context, cfg config.MinioConfig) (*minio.Client, bool) { client, err := minioUpload.Connect(cfg.Endpoint, cfg.AccessKey, cfg.SecretKey, cfg.UseSSL) if err != nil { h.logger.Errorf("minio connection failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return nil, false } return client, true } func ensureBucket(ctx context.Context, client *minio.Client, bucket string) error { exists, err := client.BucketExists(ctx, bucket) if err != nil { return err } if exists { return nil } return client.MakeBucket(ctx, bucket, minio.MakeBucketOptions{}) }