diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..7918de0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +.git +.github +.cursor +logs +tmp +temp +vendor +*.md +*.log +coverage.out +coverage.html +config.local.yaml +docker-compose.override.yaml +docker-compose.override.yml +public/images/* +!public/images/.gitkeep diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml new file mode 100644 index 0000000..5a87074 --- /dev/null +++ b/.github/workflows/ci-cd.yml @@ -0,0 +1,84 @@ +name: CI/CD + +on: + push: + branches: [main] + tags: ["v*"] + pull_request: + workflow_dispatch: + +concurrency: + group: cicd-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !startsWith(github.ref, 'refs/tags/') }} + +permissions: + contents: read + +jobs: + ci: + name: Vet, test, build + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v5 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache-dependency-path: go.sum + + - name: Vet + run: go vet ./... + + - name: Test + run: go test -race -count=1 -shuffle=on ./... + + - name: Build + run: CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o myapp ./app.go + + image: + name: Docker image + needs: ci + if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - name: Checkout + uses: actions/checkout@v5 + + - name: Provide config for image build + run: test -f config.yaml || cp config.example.yaml config.yaml + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to GHCR + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ghcr.io/${{ github.repository }} + tags: | + type=raw,value=latest,enable={{is_default_branch}} + type=sha + type=semver,pattern={{version}} + type=ref,event=tag + + - name: Build and push + uses: docker/build-push-action@v6 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/db/migrations/20260702125108_init.down.sql b/db/migrations/20260702125108_init.down.sql index 784966e..6ded039 100644 --- a/db/migrations/20260702125108_init.down.sql +++ b/db/migrations/20260702125108_init.down.sql @@ -16,7 +16,7 @@ DROP TABLE IF EXISTS card_types; DROP TABLE IF EXISTS branch_user; DROP TABLE IF EXISTS branches; DROP TABLE IF EXISTS provinces; -DROP TABLE IF EXISTS permission_user; +DROP TABLE IF EXISTS permission_role; DROP TABLE IF EXISTS role_user; DROP TABLE IF EXISTS permissions; DROP TABLE IF EXISTS roles; diff --git a/db/migrations/20260702125108_init.up.sql b/db/migrations/20260702125108_init.up.sql index cbdddd0..20501d7 100644 --- a/db/migrations/20260702125108_init.up.sql +++ b/db/migrations/20260702125108_init.up.sql @@ -1,4 +1,3 @@ --- 1. Identity CREATE TABLE IF NOT EXISTS users ( id bigserial PRIMARY KEY, email character varying(250) NOT NULL DEFAULT '', @@ -68,15 +67,15 @@ CREATE TABLE IF NOT EXISTS role_user ( updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL ); -CREATE TABLE IF NOT EXISTS permission_user ( +CREATE TABLE IF NOT EXISTS permission_role ( id bigserial PRIMARY KEY, permission_id bigint REFERENCES permissions(id), - user_id bigint REFERENCES users(id), + role_id bigint REFERENCES roles(id), created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + CONSTRAINT permission_role_permission_id_role_id_key UNIQUE (permission_id, role_id) ); --- 2. Geography CREATE TABLE IF NOT EXISTS provinces ( id bigserial PRIMARY KEY, name json NOT NULL DEFAULT '{}'::json, @@ -117,7 +116,6 @@ CREATE TABLE IF NOT EXISTS branch_user ( updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL ); --- 3. Catalogs CREATE TABLE IF NOT EXISTS card_types ( id bigserial PRIMARY KEY, name json NOT NULL DEFAULT '{}'::json, @@ -158,7 +156,6 @@ CREATE TABLE IF NOT EXISTS loan_order_required_docs ( updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL ); --- 4. Cards CREATE TABLE IF NOT EXISTS cards ( id bigserial PRIMARY KEY, user_id bigint, @@ -247,7 +244,6 @@ CREATE TABLE IF NOT EXISTS card_pin_orders ( FOREIGN KEY (user_id) REFERENCES users(id) ); --- 5. Loans CREATE TABLE IF NOT EXISTS loan_orders ( id bigserial PRIMARY KEY, unique_id character varying(255), @@ -361,7 +357,6 @@ CREATE TABLE IF NOT EXISTS loan_paid_off_letters ( FOREIGN KEY (user_id) REFERENCES users(id) ); --- 6. Payments (Visa / Master student transfers) CREATE TABLE IF NOT EXISTS visa_master_payment_orders ( id bigserial PRIMARY KEY, unique_id character varying(255), @@ -396,7 +391,6 @@ CREATE TABLE IF NOT EXISTS visa_master_payment_orders ( FOREIGN KEY (user_id) REFERENCES users(id) ); --- 7. Logs CREATE TABLE IF NOT EXISTS activity_logs ( id bigserial PRIMARY KEY, user_id bigint, diff --git a/db/mock/seed.sql b/db/mock/seed.sql index 4503e25..414eedc 100644 --- a/db/mock/seed.sql +++ b/db/mock/seed.sql @@ -25,7 +25,7 @@ TRUNCATE TABLE branch_user, branches, provinces, - permission_user, + permission_role, role_user, permissions, roles, @@ -132,21 +132,24 @@ SELECT r.id, u.id FROM users u JOIN roles r ON r.code = u.role; -INSERT INTO permission_user (permission_id, user_id) -SELECT p.id, 1 FROM permissions p; +INSERT INTO permission_role (permission_id, role_id) +SELECT p.id, r.id +FROM permissions p +JOIN roles r ON r.code IN ('superadmin', 'admin'); -INSERT INTO permission_user (permission_id, user_id) -SELECT p.id, 2 FROM permissions p; - -INSERT INTO permission_user (permission_id, user_id) -SELECT p.id, 3 FROM permissions p +INSERT INTO permission_role (permission_id, role_id) +SELECT p.id, r.id +FROM permissions p +JOIN roles r ON r.code = 'manager' WHERE p.code IN ( 'branches.view', 'provinces.view', 'cards.view', 'card-orders.view', 'card-orders.manage', 'loans.view', 'loans.manage' ); -INSERT INTO permission_user (permission_id, user_id) -SELECT p.id, 4 FROM permissions p +INSERT INTO permission_role (permission_id, role_id) +SELECT p.id, r.id +FROM permissions p +JOIN roles r ON r.code = 'operator' WHERE p.code IN ( 'card-orders.view', 'loans.view', 'cards.view', 'branches.view' ); @@ -686,6 +689,7 @@ COMMIT; SELECT 'users' AS table_name, count(*) FROM users UNION ALL SELECT 'roles', count(*) FROM roles UNION ALL SELECT 'role_user', count(*) FROM role_user +UNION ALL SELECT 'permission_role', count(*) FROM permission_role UNION ALL SELECT 'branch_user', count(*) FROM branch_user UNION ALL SELECT 'permissions', count(*) FROM permissions UNION ALL SELECT 'provinces', count(*) FROM provinces diff --git a/docs/docs.go b/docs/docs.go index 9c287bd..5ec2443 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -3721,57 +3721,14 @@ const docTemplate = `{ } } }, - "/permission-users": { - "get": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Returns the authenticated user's permission-user assignments with the related user and permission", - "produces": [ - "application/json" - ], - "tags": [ - "permission-users" - ], - "summary": "List permission users", - "parameters": [ - { - "type": "string", - "description": "Filter by permission name", - "name": "permission_name", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - }, + "/permission-roles": { "post": { "security": [ { "BearerAuth": [] } ], - "description": "Creates a permission-user assignment", + "description": "Creates a permission-role assignment, or updates the existing pair if already assigned", "consumes": [ "application/json" ], @@ -3779,17 +3736,17 @@ const docTemplate = `{ "application/json" ], "tags": [ - "permission-users" + "permission-roles" ], - "summary": "Assign user to permission", + "summary": "Assign permission to role", "parameters": [ { - "description": "Permission-user payload", + "description": "Permission-role payload", "name": "body", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/permissionuser.CreatePermissionUserDTO" + "$ref": "#/definitions/permissionrole.CreatePermissionRoleDTO" } } ], @@ -3815,25 +3772,25 @@ const docTemplate = `{ } } }, - "/permission-users/{id}": { + "/permission-roles/{id}": { "delete": { "security": [ { "BearerAuth": [] } ], - "description": "Deletes a permission-user assignment", + "description": "Deletes a permission-role assignment", "produces": [ "application/json" ], "tags": [ - "permission-users" + "permission-roles" ], - "summary": "Remove user from permission", + "summary": "Remove permission from role", "parameters": [ { "type": "integer", - "description": "Permission-user ID", + "description": "Permission-role ID", "name": "id", "in": "path", "required": true @@ -4146,7 +4103,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Returns the authenticated user's profile with role and branches", + "description": "Returns the authenticated user's profile with role, branches, and permissions", "produces": [ "application/json" ], @@ -7573,17 +7530,17 @@ const docTemplate = `{ } } }, - "permissionuser.CreatePermissionUserDTO": { + "permissionrole.CreatePermissionRoleDTO": { "type": "object", "required": [ "permissionId", - "userId" + "roleId" ], "properties": { "permissionId": { "type": "integer" }, - "userId": { + "roleId": { "type": "integer" } } diff --git a/docs/swagger.json b/docs/swagger.json index a1dcdd1..46e0c85 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -3715,57 +3715,14 @@ } } }, - "/permission-users": { - "get": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Returns the authenticated user's permission-user assignments with the related user and permission", - "produces": [ - "application/json" - ], - "tags": [ - "permission-users" - ], - "summary": "List permission users", - "parameters": [ - { - "type": "string", - "description": "Filter by permission name", - "name": "permission_name", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - }, + "/permission-roles": { "post": { "security": [ { "BearerAuth": [] } ], - "description": "Creates a permission-user assignment", + "description": "Creates a permission-role assignment, or updates the existing pair if already assigned", "consumes": [ "application/json" ], @@ -3773,17 +3730,17 @@ "application/json" ], "tags": [ - "permission-users" + "permission-roles" ], - "summary": "Assign user to permission", + "summary": "Assign permission to role", "parameters": [ { - "description": "Permission-user payload", + "description": "Permission-role payload", "name": "body", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/permissionuser.CreatePermissionUserDTO" + "$ref": "#/definitions/permissionrole.CreatePermissionRoleDTO" } } ], @@ -3809,25 +3766,25 @@ } } }, - "/permission-users/{id}": { + "/permission-roles/{id}": { "delete": { "security": [ { "BearerAuth": [] } ], - "description": "Deletes a permission-user assignment", + "description": "Deletes a permission-role assignment", "produces": [ "application/json" ], "tags": [ - "permission-users" + "permission-roles" ], - "summary": "Remove user from permission", + "summary": "Remove permission from role", "parameters": [ { "type": "integer", - "description": "Permission-user ID", + "description": "Permission-role ID", "name": "id", "in": "path", "required": true @@ -4140,7 +4097,7 @@ "BearerAuth": [] } ], - "description": "Returns the authenticated user's profile with role and branches", + "description": "Returns the authenticated user's profile with role, branches, and permissions", "produces": [ "application/json" ], @@ -7567,17 +7524,17 @@ } } }, - "permissionuser.CreatePermissionUserDTO": { + "permissionrole.CreatePermissionRoleDTO": { "type": "object", "required": [ "permissionId", - "userId" + "roleId" ], "properties": { "permissionId": { "type": "integer" }, - "userId": { + "roleId": { "type": "integer" } } diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 680221f..f43061b 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1076,15 +1076,15 @@ definitions: - guardName - name type: object - permissionuser.CreatePermissionUserDTO: + permissionrole.CreatePermissionRoleDTO: properties: permissionId: type: integer - userId: + roleId: type: integer required: - permissionId - - userId + - roleId type: object province.CreateProvinceDTO: properties: @@ -3769,46 +3769,19 @@ paths: summary: Update payment card active tags: - payment-card - /permission-users: - get: - description: Returns the authenticated user's permission-user assignments with - the related user and permission - parameters: - - description: Filter by permission name - in: query - name: permission_name - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/appresult.AppSuccess' - "401": - description: Unauthorized - schema: - $ref: '#/definitions/appresult.AppError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/appresult.AppError' - security: - - BearerAuth: [] - summary: List permission users - tags: - - permission-users + /permission-roles: post: consumes: - application/json - description: Creates a permission-user assignment + description: Creates a permission-role assignment, or updates the existing pair + if already assigned parameters: - - description: Permission-user payload + - description: Permission-role payload in: body name: body required: true schema: - $ref: '#/definitions/permissionuser.CreatePermissionUserDTO' + $ref: '#/definitions/permissionrole.CreatePermissionRoleDTO' produces: - application/json responses: @@ -3826,14 +3799,14 @@ paths: $ref: '#/definitions/appresult.AppError' security: - BearerAuth: [] - summary: Assign user to permission + summary: Assign permission to role tags: - - permission-users - /permission-users/{id}: + - permission-roles + /permission-roles/{id}: delete: - description: Deletes a permission-user assignment + description: Deletes a permission-role assignment parameters: - - description: Permission-user ID + - description: Permission-role ID in: path name: id required: true @@ -3859,9 +3832,9 @@ paths: $ref: '#/definitions/appresult.AppError' security: - BearerAuth: [] - summary: Remove user from permission + summary: Remove permission from role tags: - - permission-users + - permission-roles /permissions: get: description: Returns paginated permissions with optional filters @@ -4038,7 +4011,8 @@ paths: - permission /profile: get: - description: Returns the authenticated user's profile with role and branches + description: Returns the authenticated user's profile with role, branches, and + permissions produces: - application/json responses: diff --git a/docs/tag_order.go b/docs/tag_order.go index a3fda2e..9dd5381 100644 --- a/docs/tag_order.go +++ b/docs/tag_order.go @@ -15,7 +15,7 @@ var swaggerTagOrder = []struct { {Name: "role", Description: "Roles"}, {Name: "role-users", Description: "Role users"}, {Name: "permission", Description: "Permissions"}, - {Name: "permission-users", Description: "Permission users"}, + {Name: "permission-roles", Description: "Permission roles"}, {Name: "payment-card", Description: "Payment cards"}, {Name: "reason-card", Description: "Reason cards"}, {Name: "cards", Description: "Cards"}, diff --git a/internal/appresult/error.go b/internal/appresult/error.go index 6f126d3..5a30d8c 100755 --- a/internal/appresult/error.go +++ b/internal/appresult/error.go @@ -7,6 +7,7 @@ var ( ErrUnauthorized = NewAppError(nil, "Invalid credentials or unauthorized access.", "SE-00002") ErrNotFound = NewAppError(nil, "The requested resource was not found.", "SE-00003") ErrInternalServer = NewAppError(nil, "An internal server error occurred. Please try again later.", "SE-00004") + ErrForbidden = NewAppError(nil, "Sana rugsat yok.", "SE-00011") ErrNotAcceptable = NewAppError(nil, "The request could not be processed.", "SE-00007") ErrConflict = NewAppError(nil, "A user with this phone or username already exists.", "SE-00008") ErrInvalidCode = NewAppError(nil, "Invalid or expired verification code.", "SE-00009") diff --git a/internal/cards/cardorder/db/postgresql.go b/internal/cards/cardorder/db/postgresql.go index a3ac21b..027a445 100644 --- a/internal/cards/cardorder/db/postgresql.go +++ b/internal/cards/cardorder/db/postgresql.go @@ -7,6 +7,7 @@ import ( "time" "online-back/internal/cards/cardorder" + "online-back/internal/identity/rbac" "online-back/pkg/client/postgresql" "online-back/pkg/logging" "online-back/pkg/repository/genericrepo" @@ -110,7 +111,9 @@ func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []int conditions = append(conditions, fmt.Sprintf("status = $%d", len(args))) } - if filter.BranchId != nil { + if len(filter.BranchIds) > 0 { + conditions, args = rbac.AppendBranchIDs(conditions, args, "branch_id", filter.BranchIds) + } else if filter.BranchId != nil { args = append(args, *filter.BranchId) conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args))) } diff --git a/internal/cards/cardorder/dto.go b/internal/cards/cardorder/dto.go index 331ad4d..3495227 100644 --- a/internal/cards/cardorder/dto.go +++ b/internal/cards/cardorder/dto.go @@ -212,6 +212,7 @@ type UpdateCardOrderDTO struct { type ListFilter struct { Status *string BranchId *int64 + BranchIds []int64 UserId *int64 CardStateId *int64 CardTypeId *int64 diff --git a/internal/cards/cardorder/handler.go b/internal/cards/cardorder/handler.go index 9709f2d..0c19732 100644 --- a/internal/cards/cardorder/handler.go +++ b/internal/cards/cardorder/handler.go @@ -8,6 +8,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" "online-back/pkg/logging" "github.com/gin-gonic/gin" @@ -98,6 +99,9 @@ func (h *handler) getByID(c *gin.Context) { c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } + if !rbac.GuardBranch(c, item.BranchId) { + return + } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } @@ -153,6 +157,10 @@ func (h *handler) update(c *gin.Context) { return } + if !h.guardBranchByID(c, id) { + return + } + var dto UpdateCardOrderDTO if err := c.ShouldBindBodyWithJSON(&dto); err != nil { h.logger.Errorf("update card order bind failed: %v", err) @@ -193,6 +201,10 @@ func (h *handler) delete(c *gin.Context) { return } + if !h.guardBranchByID(c, id) { + return + } + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return @@ -276,9 +288,26 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) { filter.Region = raw } + rbac.BindBranchIDs(c, &filter.BranchIds) return filter, true } +func (h *handler) guardBranchByID(c *gin.Context, id int64) bool { + if !rbac.HasBranchScope(c) { + return true + } + item, err := h.repository.GetByID(c.Request.Context(), id) + if errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return false + } + if err != nil { + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return false + } + return rbac.GuardBranch(c, item.BranchId) +} + func queryValue(c *gin.Context, keys ...string) string { for _, key := range keys { if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" { diff --git a/internal/cards/cardpinorders/db/postgresql.go b/internal/cards/cardpinorders/db/postgresql.go index c983dfb..d39cb87 100644 --- a/internal/cards/cardpinorders/db/postgresql.go +++ b/internal/cards/cardpinorders/db/postgresql.go @@ -6,6 +6,7 @@ import ( "strings" "online-back/internal/cards/cardpinorders" + "online-back/internal/identity/rbac" "online-back/pkg/client/postgresql" "online-back/pkg/logging" "online-back/pkg/repository/genericrepo" @@ -77,7 +78,9 @@ func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args [ conditions = append(conditions, fmt.Sprintf("status = $%d", len(args))) } - if filter.BranchId != nil { + if len(filter.BranchIds) > 0 { + conditions, args = rbac.AppendBranchIDs(conditions, args, "branch_id", filter.BranchIds) + } else if filter.BranchId != nil { args = append(args, *filter.BranchId) conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args))) } diff --git a/internal/cards/cardpinorders/dto.go b/internal/cards/cardpinorders/dto.go index 4f4f5ed..a732c5a 100644 --- a/internal/cards/cardpinorders/dto.go +++ b/internal/cards/cardpinorders/dto.go @@ -74,6 +74,7 @@ type UpdateCardPinOrderDTO struct { type ListFilter struct { Status *string BranchId *int64 + BranchIds []int64 UserId *int64 CardTypeId *int64 Region string diff --git a/internal/cards/cardpinorders/handler.go b/internal/cards/cardpinorders/handler.go index 9822a1d..6ae4a33 100644 --- a/internal/cards/cardpinorders/handler.go +++ b/internal/cards/cardpinorders/handler.go @@ -8,6 +8,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" "online-back/pkg/logging" "github.com/gin-gonic/gin" @@ -97,6 +98,9 @@ func (h *handler) getByID(c *gin.Context) { c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } + if !rbac.GuardBranch(c, item.BranchId) { + return + } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } @@ -151,6 +155,10 @@ func (h *handler) update(c *gin.Context) { return } + if !h.guardBranchByID(c, id) { + return + } + var dto UpdateCardPinOrderDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) @@ -190,6 +198,10 @@ func (h *handler) delete(c *gin.Context) { return } + if !h.guardBranchByID(c, id) { + return + } + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return @@ -270,5 +282,22 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) { filter.Region = raw } + rbac.BindBranchIDs(c, &filter.BranchIds) return filter, true } + +func (h *handler) guardBranchByID(c *gin.Context, id int64) bool { + if !rbac.HasBranchScope(c) { + return true + } + item, err := h.repository.GetByID(c.Request.Context(), id) + if errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return false + } + if err != nil { + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return false + } + return rbac.GuardBranch(c, item.BranchId) +} diff --git a/internal/cards/cards/db/postgresql.go b/internal/cards/cards/db/postgresql.go index a28f4c6..cdde4cf 100644 --- a/internal/cards/cards/db/postgresql.go +++ b/internal/cards/cards/db/postgresql.go @@ -6,6 +6,7 @@ import ( "strings" "online-back/internal/cards/cards" + "online-back/internal/identity/rbac" "online-back/pkg/client/postgresql" "online-back/pkg/logging" "online-back/pkg/repository/genericrepo" @@ -68,6 +69,11 @@ func buildListQuery(filter cards.ListFilter) (whereClause string, args []interfa conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args))) } + if len(filter.BranchIds) > 0 { + args = append(args, filter.BranchIds) + conditions = append(conditions, rbac.UserInBranchSQL("user_id", len(args))) + } + if filter.Type != nil { args = append(args, *filter.Type) conditions = append(conditions, fmt.Sprintf("type = $%d", len(args))) diff --git a/internal/cards/cards/dto.go b/internal/cards/cards/dto.go index c4fa3c4..c016183 100644 --- a/internal/cards/cards/dto.go +++ b/internal/cards/cards/dto.go @@ -33,10 +33,11 @@ type UpdateCardDTO struct { } type ListFilter struct { - UserId *int64 - Type *string - Page int - Limit int + UserId *int64 + BranchIds []int64 + Type *string + Page int + Limit int } type ListCardDTO struct { diff --git a/internal/cards/cards/handler.go b/internal/cards/cards/handler.go index 40379d2..a1b8773 100644 --- a/internal/cards/cards/handler.go +++ b/internal/cards/cards/handler.go @@ -8,6 +8,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" "online-back/pkg/logging" "github.com/gin-gonic/gin" @@ -94,6 +95,13 @@ func (h *handler) getByID(c *gin.Context) { c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } + if item.UserId != nil && !rbac.GuardUser(c, *item.UserId) { + return + } + if item.UserId == nil && rbac.HasBranchScope(c) { + c.JSON(http.StatusForbidden, appresult.ErrForbidden) + return + } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } @@ -148,6 +156,10 @@ func (h *handler) update(c *gin.Context) { return } + if !h.guardCardByID(c, id) { + return + } + var dto UpdateCardDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) @@ -187,6 +199,10 @@ func (h *handler) delete(c *gin.Context) { return } + if !h.guardCardByID(c, id) { + return + } + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return @@ -247,5 +263,26 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) { filter.Limit = limit } + rbac.BindBranchIDs(c, &filter.BranchIds) return filter, true } + +func (h *handler) guardCardByID(c *gin.Context, id int64) bool { + if !rbac.HasBranchScope(c) { + return true + } + item, err := h.repository.GetByID(c.Request.Context(), id) + if errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return false + } + if err != nil { + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return false + } + if item.UserId == nil { + c.JSON(http.StatusForbidden, appresult.ErrForbidden) + return false + } + return rbac.GuardUser(c, *item.UserId) +} diff --git a/internal/cards/visamaster/db/postgresql.go b/internal/cards/visamaster/db/postgresql.go index b4ef25e..018035c 100644 --- a/internal/cards/visamaster/db/postgresql.go +++ b/internal/cards/visamaster/db/postgresql.go @@ -7,6 +7,7 @@ import ( "strings" "online-back/internal/cards/visamaster" + "online-back/internal/identity/rbac" "online-back/pkg/client/postgresql" "online-back/pkg/logging" "online-back/pkg/repository/genericrepo" @@ -159,7 +160,9 @@ func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []in conditions = append(conditions, fmt.Sprintf("o.status = $%d", len(args))) } - if filter.BranchId != nil { + if len(filter.BranchIds) > 0 { + conditions, args = rbac.AppendBranchIDs(conditions, args, "o.branch_id", filter.BranchIds) + } else if filter.BranchId != nil { args = append(args, *filter.BranchId) conditions = append(conditions, fmt.Sprintf("o.branch_id = $%d", len(args))) } diff --git a/internal/cards/visamaster/dto.go b/internal/cards/visamaster/dto.go index 2e356e0..a8ca2ba 100644 --- a/internal/cards/visamaster/dto.go +++ b/internal/cards/visamaster/dto.go @@ -116,13 +116,14 @@ type UpdateVisaMasterPaymentOrderDTO struct { } type ListFilter struct { - Name string - Status *string - BranchId *int64 - UserId *int64 - Region string - Page int - Limit int + Name string + Status *string + BranchId *int64 + BranchIds []int64 + UserId *int64 + Region string + Page int + Limit int } type ListVisaMasterPaymentOrderDTO struct { diff --git a/internal/cards/visamaster/handler.go b/internal/cards/visamaster/handler.go index b005925..93a82ba 100644 --- a/internal/cards/visamaster/handler.go +++ b/internal/cards/visamaster/handler.go @@ -8,6 +8,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" "online-back/pkg/logging" "github.com/gin-gonic/gin" @@ -97,6 +98,9 @@ func (h *handler) getByID(c *gin.Context) { c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } + if !rbac.GuardBranch(c, item.BranchId) { + return + } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } @@ -151,6 +155,10 @@ func (h *handler) update(c *gin.Context) { return } + if !h.guardBranchByID(c, id) { + return + } + var dto UpdateVisaMasterPaymentOrderDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) @@ -190,6 +198,10 @@ func (h *handler) delete(c *gin.Context) { return } + if !h.guardBranchByID(c, id) { + return + } + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return @@ -266,5 +278,22 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) { filter.UserId = &id } + rbac.BindBranchIDs(c, &filter.BranchIds) return filter, true } + +func (h *handler) guardBranchByID(c *gin.Context, id int64) bool { + if !rbac.HasBranchScope(c) { + return true + } + item, err := h.repository.GetByID(c.Request.Context(), id) + if errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return false + } + if err != nil { + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return false + } + return rbac.GuardBranch(c, item.BranchId) +} diff --git a/internal/handlers/manager/manager.go b/internal/handlers/manager/manager.go index 0b186fe..fecde1f 100755 --- a/internal/handlers/manager/manager.go +++ b/internal/handlers/manager/manager.go @@ -8,6 +8,7 @@ import ( "online-back/internal/identity" "online-back/internal/identity/activitylog" activitylogdb "online-back/internal/identity/activitylog/db" + "online-back/internal/identity/rbac" "online-back/internal/lending" "online-back/internal/org" "online-back/pkg/logging" @@ -52,6 +53,7 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin. adminGroup := router.Group(adminAPIPrefix) adminGroup.Use(activitylog.Record(activitylogdb.NewRepository(client, logger), logger)) + adminGroup.Use(rbac.Guard(rbac.NewService(client))) // Each bounded context registers its own modules' handlers. // Add new modules inside the relevant context's router.go rather than here. diff --git a/internal/identity/auth/db/postgresql.go b/internal/identity/auth/db/postgresql.go index ef03685..22d625c 100755 --- a/internal/identity/auth/db/postgresql.go +++ b/internal/identity/auth/db/postgresql.go @@ -67,8 +67,19 @@ const profileBranchesJSON = `COALESCE(( ) b ), '[]'::json)` +const profilePermissionsJSON = `COALESCE(( + SELECT json_agg(jsonb_build_object( + 'id', p.id, + 'code', COALESCE(p.code, ''), + 'name', p.name + ) ORDER BY p.id) + FROM permission_role pr + JOIN permissions p ON p.id = pr.permission_id + WHERE pr.role_id = r.id +), '[]'::json)` + const profileQuery = `SELECT u.id, u.name, u.first_name, u.last_name, u.phone, u.avatar, u.created_at, - r.id, r.code, r.name, ` + profileBranchesJSON + profileFromClause + ` WHERE u.id = $1` + r.id, r.code, r.name, ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1` func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) { phone := strings.TrimSpace(dto.Phone) @@ -125,6 +136,7 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) { var roleID sql.NullInt64 var roleCode, roleName sql.NullString var branchesJSON []byte + var permissionsJSON []byte err := row.Scan( &profile.Id, @@ -138,6 +150,7 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) { &roleCode, &roleName, &branchesJSON, + &permissionsJSON, ) if err != nil { return auth.UserProfileDTO{}, err @@ -151,12 +164,18 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) { } } - if len(branchesJSON) == 0 || string(branchesJSON) == "null" { - profile.Branches = []auth.ProfileBranchDTO{} - return profile, nil + profile.Branches = []auth.ProfileBranchDTO{} + if len(branchesJSON) > 0 && string(branchesJSON) != "null" { + if err := json.Unmarshal(branchesJSON, &profile.Branches); err != nil { + return auth.UserProfileDTO{}, err + } } - if err := json.Unmarshal(branchesJSON, &profile.Branches); err != nil { - return auth.UserProfileDTO{}, err + + profile.Permissions = []auth.ProfilePermissionDTO{} + if len(permissionsJSON) > 0 && string(permissionsJSON) != "null" { + if err := json.Unmarshal(permissionsJSON, &profile.Permissions); err != nil { + return auth.UserProfileDTO{}, err + } } return profile, nil } diff --git a/internal/identity/auth/dto.go b/internal/identity/auth/dto.go index 979025e..e76dcac 100755 --- a/internal/identity/auth/dto.go +++ b/internal/identity/auth/dto.go @@ -30,16 +30,23 @@ type ProfileBranchDTO struct { Name LocalizedText `json:"name"` } +type ProfilePermissionDTO struct { + Id int64 `json:"id"` + Code string `json:"code"` + Name string `json:"name"` +} + type UserProfileDTO struct { - Id int `json:"id"` - Name string `json:"name"` - FirstName string `json:"firstName"` - LastName string `json:"lastName"` - Phone string `json:"phone"` - Avatar string `json:"avatar"` - Role *ProfileRoleDTO `json:"role"` - Branches []ProfileBranchDTO `json:"branches"` - CreatedAt time.Time `json:"createdAt"` + Id int `json:"id"` + Name string `json:"name"` + FirstName string `json:"firstName"` + LastName string `json:"lastName"` + Phone string `json:"phone"` + Avatar string `json:"avatar"` + Role *ProfileRoleDTO `json:"role"` + Branches []ProfileBranchDTO `json:"branches"` + Permissions []ProfilePermissionDTO `json:"permissions"` + CreatedAt time.Time `json:"createdAt"` } type UpdateProfileDTO struct { diff --git a/internal/identity/auth/handler.go b/internal/identity/auth/handler.go index 273d0da..d9f540f 100755 --- a/internal/identity/auth/handler.go +++ b/internal/identity/auth/handler.go @@ -242,7 +242,7 @@ func (h *handler) refreshToken(c *gin.Context) { // getProfile godoc // @Summary Get profile -// @Description Returns the authenticated user's profile with role and branches +// @Description Returns the authenticated user's profile with role, branches, and permissions // @Tags auth // @Produce json // @Security BearerAuth diff --git a/internal/identity/permissionrole/db/postgresql.go b/internal/identity/permissionrole/db/postgresql.go new file mode 100644 index 0000000..2c9eae8 --- /dev/null +++ b/internal/identity/permissionrole/db/postgresql.go @@ -0,0 +1,69 @@ +package db + +import ( + "context" + "errors" + + "online-back/internal/identity/permissionrole" + "online-back/pkg/client/postgresql" + "online-back/pkg/logging" + + "github.com/jackc/pgx/v4" +) + +type repository struct { + client postgresql.Client + logger *logging.Logger +} + +func NewRepository(client postgresql.Client, logger *logging.Logger) permissionrole.Repository { + return &repository{client: client, logger: logger} +} + +func (r *repository) Create(ctx context.Context, dto permissionrole.CreatePermissionRoleDTO) (permissionrole.PermissionRoleDTO, error) { + query := ` + WITH upserted AS ( + INSERT INTO permission_role (permission_id, role_id) + VALUES ($1, $2) + ON CONFLICT (permission_id, role_id) DO UPDATE SET + updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') + RETURNING id, permission_id, role_id, created_at, updated_at + ) + SELECT upserted.id, upserted.permission_id, p.name, upserted.role_id, r.name, upserted.created_at, upserted.updated_at + FROM upserted + JOIN permissions p ON p.id = upserted.permission_id + JOIN roles r ON r.id = upserted.role_id` + + row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.RoleId) + return scanPermissionRole(row) +} + +func (r *repository) Delete(ctx context.Context, id int64) error { + tag, err := r.client.Exec(ctx, `DELETE FROM permission_role WHERE id = $1`, id) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return pgx.ErrNoRows + } + return nil +} + +type scannable interface { + Scan(dest ...interface{}) error +} + +func scanPermissionRole(row scannable) (permissionrole.PermissionRoleDTO, error) { + var item permissionrole.PermissionRoleDTO + + err := row.Scan( + &item.Id, &item.PermissionId, &item.PermissionName, &item.RoleId, &item.RoleName, &item.CreatedAt, &item.UpdatedAt, + ) + if errors.Is(err, pgx.ErrNoRows) { + return permissionrole.PermissionRoleDTO{}, err + } + if err != nil { + return permissionrole.PermissionRoleDTO{}, err + } + return item, nil +} diff --git a/internal/identity/permissionrole/dto.go b/internal/identity/permissionrole/dto.go new file mode 100644 index 0000000..0321972 --- /dev/null +++ b/internal/identity/permissionrole/dto.go @@ -0,0 +1,18 @@ +package permissionrole + +import "time" + +type PermissionRoleDTO struct { + Id int64 `json:"id"` + RoleId int64 `json:"roleId"` + RoleName string `json:"roleName"` + PermissionId int64 `json:"permissionId"` + PermissionName string `json:"permissionName"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + +type CreatePermissionRoleDTO struct { + PermissionId int64 `json:"permissionId" binding:"required"` + RoleId int64 `json:"roleId" binding:"required"` +} diff --git a/internal/identity/permissionrole/handler.go b/internal/identity/permissionrole/handler.go new file mode 100644 index 0000000..9a2de55 --- /dev/null +++ b/internal/identity/permissionrole/handler.go @@ -0,0 +1,99 @@ +package permissionrole + +import ( + "errors" + "net/http" + "strconv" + + "online-back/internal/appresult" + "online-back/internal/handlers" + "online-back/pkg/logging" + + "github.com/gin-gonic/gin" + "github.com/jackc/pgx/v4" +) + +const baseURL = "/permission-roles" + +type handler struct { + logger *logging.Logger + repository Repository +} + +func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { + return &handler{logger: logger, repository: repository} +} + +func (h *handler) Register(router *gin.RouterGroup) { + group := router.Group(baseURL, appresult.JwtTokenCheck()) + group.POST("", h.create) + group.DELETE("/:id", h.delete) +} + +// create godoc +// @Summary Assign permission to role +// @Description Creates a permission-role assignment, or updates the existing pair if already assigned +// @Tags permission-roles +// @Accept json +// @Produce json +// @Security BearerAuth +// @Param body body CreatePermissionRoleDTO true "Permission-role payload" +// @Success 201 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /permission-roles [post] +func (h *handler) create(c *gin.Context) { + var dto CreatePermissionRoleDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + item, err := h.repository.Create(c.Request.Context(), dto) + if err != nil { + h.logger.Errorf("create permission role failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusCreated, appresult.SuccessWithData(item)) +} + +// delete godoc +// @Summary Remove permission from role +// @Description Deletes a permission-role assignment +// @Tags permission-roles +// @Produce json +// @Security BearerAuth +// @Param id path int true "Permission-role ID" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /permission-roles/{id} [delete] +func (h *handler) delete(c *gin.Context) { + id, ok := parseID(c.Param("id")) + if !ok { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + 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 permission role failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData("permission role removed")) +} + +func parseID(raw string) (int64, bool) { + id, err := strconv.ParseInt(raw, 10, 64) + if err != nil || id <= 0 { + return 0, false + } + return id, true +} diff --git a/internal/identity/permissionrole/storage.go b/internal/identity/permissionrole/storage.go new file mode 100644 index 0000000..d8d6363 --- /dev/null +++ b/internal/identity/permissionrole/storage.go @@ -0,0 +1,8 @@ +package permissionrole + +import "context" + +type Repository interface { + Create(ctx context.Context, dto CreatePermissionRoleDTO) (PermissionRoleDTO, error) + Delete(ctx context.Context, id int64) error +} diff --git a/internal/identity/permissionuser/db/postgresql.go b/internal/identity/permissionuser/db/postgresql.go deleted file mode 100644 index 545e8a1..0000000 --- a/internal/identity/permissionuser/db/postgresql.go +++ /dev/null @@ -1,132 +0,0 @@ -package db - -import ( - "context" - "errors" - "fmt" - "strings" - - "online-back/internal/identity/permissionuser" - "online-back/pkg/client/postgresql" - "online-back/pkg/logging" - - "github.com/jackc/pgx/v4" -) - -type repository struct { - client postgresql.Client - logger *logging.Logger -} - -func NewRepository(client postgresql.Client, logger *logging.Logger) permissionuser.Repository { - return &repository{client: client, logger: logger} -} - -const permissionUserFromClause = ` FROM permission_user pu - JOIN permissions p ON p.id = pu.permission_id - JOIN users u ON u.id = pu.user_id` - -const permissionUserSelectColumns = `pu.id, pu.permission_id, p.name, pu.user_id, u.name, pu.created_at, pu.updated_at` - -func (r *repository) List(ctx context.Context, filter permissionuser.ListFilter) (permissionuser.ListPermissionUserDTO, error) { - whereClause, args := buildListQuery(filter) - - var count int64 - if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+permissionUserFromClause+whereClause, args...).Scan(&count); err != nil { - return permissionuser.ListPermissionUserDTO{}, err - } - - query := `SELECT ` + permissionUserSelectColumns + permissionUserFromClause + whereClause + ` ORDER BY pu.id DESC` - rows, err := r.client.Query(ctx, query, args...) - if err != nil { - return permissionuser.ListPermissionUserDTO{}, err - } - defer rows.Close() - - var items []permissionuser.PermissionUserDTO - for rows.Next() { - item, err := scanPermissionUser(rows) - if err != nil { - return permissionuser.ListPermissionUserDTO{}, err - } - items = append(items, item) - } - if err := rows.Err(); err != nil { - return permissionuser.ListPermissionUserDTO{}, err - } - - return permissionuser.ListPermissionUserDTO{Count: count, Items: items}, nil -} - -func buildListQuery(filter permissionuser.ListFilter) (whereClause string, args []interface{}) { - var conditions []string - - if filter.UserId != nil { - args = append(args, *filter.UserId) - conditions = append(conditions, fmt.Sprintf("pu.user_id = $%d", len(args))) - } - - if filter.PermissionName != "" { - args = append(args, likePattern(filter.PermissionName)) - conditions = append(conditions, fmt.Sprintf("p.name ILIKE $%d", len(args))) - } - - if len(conditions) == 0 { - return "", args - } - - return " WHERE " + strings.Join(conditions, " AND "), args -} - -func likePattern(term string) string { - term = strings.ReplaceAll(term, `\`, `\\`) - term = strings.ReplaceAll(term, `%`, `\%`) - term = strings.ReplaceAll(term, `_`, `\_`) - return "%" + term + "%" -} - -func (r *repository) Create(ctx context.Context, dto permissionuser.CreatePermissionUserDTO) (permissionuser.PermissionUserDTO, error) { - query := ` - WITH inserted AS ( - INSERT INTO permission_user (permission_id, user_id) - VALUES ($1, $2) - RETURNING id, permission_id, user_id, created_at, updated_at - ) - SELECT inserted.id, inserted.permission_id, p.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at - FROM inserted - JOIN permissions p ON p.id = inserted.permission_id - JOIN users u ON u.id = inserted.user_id` - - row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.UserId) - return scanPermissionUser(row) -} - -func (r *repository) Delete(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, `DELETE FROM permission_user WHERE id = $1`, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil -} - -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanPermissionUser(row scannable) (permissionuser.PermissionUserDTO, error) { - var item permissionuser.PermissionUserDTO - - err := row.Scan( - &item.Id, &item.PermissionId, &item.PermissionName, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt, - ) - if errors.Is(err, pgx.ErrNoRows) { - return permissionuser.PermissionUserDTO{}, err - } - if err != nil { - return permissionuser.PermissionUserDTO{}, err - } - return item, nil -} diff --git a/internal/identity/permissionuser/dto.go b/internal/identity/permissionuser/dto.go deleted file mode 100644 index 3134645..0000000 --- a/internal/identity/permissionuser/dto.go +++ /dev/null @@ -1,28 +0,0 @@ -package permissionuser - -import "time" - -type PermissionUserDTO struct { - Id int64 `json:"id"` - UserId int64 `json:"userId"` - UserName string `json:"userName"` - PermissionId int64 `json:"permissionId"` - PermissionName string `json:"permissionName"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` -} - -type ListPermissionUserDTO struct { - Count int64 `json:"count"` - Items []PermissionUserDTO `json:"items"` -} - -type ListFilter struct { - UserId *int64 - PermissionName string -} - -type CreatePermissionUserDTO struct { - PermissionId int64 `json:"permissionId" binding:"required"` - UserId int64 `json:"userId" binding:"required"` -} diff --git a/internal/identity/permissionuser/handler.go b/internal/identity/permissionuser/handler.go deleted file mode 100644 index 7430a76..0000000 --- a/internal/identity/permissionuser/handler.go +++ /dev/null @@ -1,152 +0,0 @@ -package permissionuser - -import ( - "errors" - "net/http" - "strconv" - "strings" - - "online-back/internal/appresult" - "online-back/internal/handlers" - "online-back/pkg/logging" - - "github.com/gin-gonic/gin" - "github.com/jackc/pgx/v4" -) - -const baseURL = "/permission-users" - -type handler struct { - logger *logging.Logger - repository Repository -} - -func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { - return &handler{logger: logger, repository: repository} -} - -func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) - group.GET("", h.list) - group.POST("", h.create) - group.DELETE("/:id", h.delete) -} - -// list godoc -// @Summary List permission users -// @Description Returns the authenticated user's permission-user assignments with the related user and permission -// @Tags permission-users -// @Produce json -// @Security BearerAuth -// @Param permission_name query string false "Filter by permission name" -// @Success 200 {object} appresult.AppSuccess -// @Failure 401 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /permission-users [get] -func (h *handler) list(c *gin.Context) { - userID, ok := currentUserID(c) - if !ok { - c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) - return - } - - filter := ListFilter{ - UserId: &userID, - PermissionName: strings.TrimSpace(c.Query("permission_name")), - } - - result, err := h.repository.List(c.Request.Context(), filter) - if err != nil { - h.logger.Errorf("list permission users failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData(result)) -} - -// create godoc -// @Summary Assign user to permission -// @Description Creates a permission-user assignment -// @Tags permission-users -// @Accept json -// @Produce json -// @Security BearerAuth -// @Param body body CreatePermissionUserDTO true "Permission-user payload" -// @Success 201 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /permission-users [post] -func (h *handler) create(c *gin.Context) { - var dto CreatePermissionUserDTO - if err := c.ShouldBindJSON(&dto); err != nil { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - - item, err := h.repository.Create(c.Request.Context(), dto) - if err != nil { - h.logger.Errorf("create permission user failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusCreated, appresult.SuccessWithData(item)) -} - -// delete godoc -// @Summary Remove user from permission -// @Description Deletes a permission-user assignment -// @Tags permission-users -// @Produce json -// @Security BearerAuth -// @Param id path int true "Permission-user ID" -// @Success 200 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 404 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /permission-users/{id} [delete] -func (h *handler) delete(c *gin.Context) { - id, ok := parseID(c.Param("id")) - if !ok { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - 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 permission user failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData("permission user removed")) -} - -func parseID(raw string) (int64, bool) { - id, err := strconv.ParseInt(raw, 10, 64) - if err != nil || id <= 0 { - return 0, false - } - return id, true -} - -func currentUserID(c *gin.Context) (int64, bool) { - rawID, exists := c.Get("id") - if !exists { - return 0, false - } - - switch id := rawID.(type) { - case int64: - return id, id > 0 - case int: - return int64(id), id > 0 - case string: - return parseID(id) - default: - return 0, false - } -} diff --git a/internal/identity/permissionuser/storage.go b/internal/identity/permissionuser/storage.go deleted file mode 100644 index ea26ea0..0000000 --- a/internal/identity/permissionuser/storage.go +++ /dev/null @@ -1,9 +0,0 @@ -package permissionuser - -import "context" - -type Repository interface { - List(ctx context.Context, filter ListFilter) (ListPermissionUserDTO, error) - Create(ctx context.Context, dto CreatePermissionUserDTO) (PermissionUserDTO, error) - Delete(ctx context.Context, id int64) error -} diff --git a/internal/identity/rbac/middleware.go b/internal/identity/rbac/middleware.go index d038f6c..73e5343 100644 --- a/internal/identity/rbac/middleware.go +++ b/internal/identity/rbac/middleware.go @@ -1,38 +1,371 @@ package rbac import ( + "bytes" + "encoding/json" + "io" "net/http" "strconv" + "strings" "online-back/internal/appresult" + "online-back/internal/config" "github.com/gin-gonic/gin" + "github.com/golang-jwt/jwt" +) + +const ( + roleUser = "user" + roleOperator = "operator" + adminPrefix = "/api/admin" + contextRole = "role" ) -// RequirePermission returns a gin middleware that 403s unless the -// authenticated user (set by appresult.JwtTokenCheck, which must run first) -// has been directly granted the given permission code. Not currently -// attached to any route. func RequirePermission(service *Service, code string) gin.HandlerFunc { return func(c *gin.Context) { rawID, exists := c.Get("id") if !exists { - c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized) + c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) return } userID, err := strconv.ParseInt(rawID.(string), 10, 64) if err != nil { - c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized) + c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) return } granted, err := service.HasPermission(c.Request.Context(), userID, code) if err != nil || !granted { - c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized) + c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) return } c.Next() } } + +func Guard(service *Service) gin.HandlerFunc { + return func(c *gin.Context) { + if c.Request.Method == http.MethodOptions || isPublicAdminPath(c.Request.URL.Path) { + c.Next() + return + } + + userID, ok := requestUserID(c) + if !ok { + c.Next() + return + } + + code, err := service.RoleCode(c.Request.Context(), userID) + if err != nil { + c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.Set("id", strconv.FormatInt(userID, 10)) + c.Set(contextRole, code) + c.Set(contextService, service) + + switch code { + case roleOperator: + enforceOperator(c, service, userID) + return + case roleUser, "": + if !userRoleAllows(c.Request.Method, c.Request.URL.Path) { + c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) + return + } + scopeOwnedLists(c, userID) + c.Next() + return + default: + c.Next() + return + } + } +} + +func enforceOperator(c *gin.Context, service *Service, userID int64) { + ids, err := service.BranchIDs(c.Request.Context(), userID) + if err != nil { + c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + c.Set(contextBranchIDs, ids) + + if !operatorRoleAllows(c.Request.Method, c.Request.URL.Path) { + c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) + return + } + + if !operatorProfileOrFile(c.Request.URL.Path) && len(ids) == 0 { + c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) + return + } + + if !operatorWriteAllowed(c, service, ids) { + return + } + + c.Next() +} + +func isPublicAdminPath(path string) bool { + switch strings.TrimSuffix(path, "/") { + case adminPrefix + "/login", + adminPrefix + "/token", + adminPrefix + "/register", + adminPrefix + "/register/verify", + adminPrefix + "/forgot-password", + adminPrefix + "/forgot-password/verify": + return true + default: + return false + } +} + +func userRoleAllows(method, path string) bool { + if method != http.MethodGet { + return false + } + + rest := strings.TrimSuffix(strings.TrimPrefix(path, adminPrefix), "/") + if rest == "" { + return false + } + if !strings.HasPrefix(rest, "/") { + rest = "/" + rest + } + + for _, prefix := range userRolePrefixes { + if rest == prefix || strings.HasPrefix(rest, prefix+"/") { + return true + } + } + return false +} + +func scopeOwnedLists(c *gin.Context, userID int64) { + rest := strings.TrimSuffix(strings.TrimPrefix(c.Request.URL.Path, adminPrefix), "/") + if rest == "" { + return + } + if !strings.HasPrefix(rest, "/") { + rest = "/" + rest + } + + owned := false + for _, prefix := range userOwnedPrefixes { + if rest == prefix || strings.HasPrefix(rest, prefix+"/") { + owned = true + break + } + } + if !owned { + return + } + + query := c.Request.URL.Query() + query.Set("user_id", strconv.FormatInt(userID, 10)) + c.Request.URL.RawQuery = query.Encode() +} + +func requestUserID(c *gin.Context) (int64, bool) { + if id, ok := parseContextUserID(c); ok { + return id, true + } + + token := bearerToken(c.GetHeader("Authorization")) + if token == "" { + return 0, false + } + + claims, err := appresult.TokenClaims(token, config.GetConfig().JwtKey) + if err != nil { + return 0, false + } + return claimUserID(claims) +} + +func parseContextUserID(c *gin.Context) (int64, bool) { + rawID, exists := c.Get("id") + if !exists { + return 0, false + } + switch id := rawID.(type) { + case int64: + return id, id > 0 + case int: + return int64(id), id > 0 + case string: + parsed, err := strconv.ParseInt(id, 10, 64) + return parsed, err == nil && parsed > 0 + default: + return 0, false + } +} + +func claimUserID(claims jwt.MapClaims) (int64, bool) { + switch id := claims["id"].(type) { + case float64: + return int64(id), id > 0 + case int64: + return id, id > 0 + case int: + return int64(id), id > 0 + case string: + parsed, err := strconv.ParseInt(id, 10, 64) + return parsed, err == nil && parsed > 0 + default: + return 0, false + } +} + +func bearerToken(header string) string { + const prefix = "Bearer " + if strings.HasPrefix(header, prefix) { + return strings.TrimSpace(header[len(prefix):]) + } + return strings.TrimSpace(header) +} + +var userRolePrefixes = []string{ + "/profile", + "/cards", + "/card-orders", + "/card-pin-orders", + "/payment-cards", + "/reasons-cards", + "/visa-master-payment-orders", + "/loan-orders", + "/loan-types", + "/loans-documents", + "/loans-repayment", + "/loan-paid-off-letters", +} + +var userOwnedPrefixes = []string{ + "/cards", + "/card-orders", + "/card-pin-orders", + "/visa-master-payment-orders", + "/loan-orders", +} + +func operatorRoleAllows(method, path string) bool { + rest := adminREST(path) + if rest == "" { + return false + } + if method == http.MethodGet { + for _, prefix := range operatorGetPrefixes { + if rest == prefix || strings.HasPrefix(rest, prefix+"/") { + return true + } + } + } + for _, prefix := range operatorWritePrefixes { + if rest == prefix || strings.HasPrefix(rest, prefix+"/") { + return true + } + } + return false +} + +func operatorProfileOrFile(path string) bool { + rest := adminREST(path) + return rest == "/profile" || rest == "/file" || strings.HasPrefix(rest, "/file/") +} + +func operatorWriteAllowed(c *gin.Context, service *Service, branchIDs []int64) bool { + switch c.Request.Method { + case http.MethodPost, http.MethodPut, http.MethodPatch: + default: + return true + } + if operatorProfileOrFile(c.Request.URL.Path) || len(branchIDs) == 0 { + return true + } + + body, err := io.ReadAll(c.Request.Body) + if err != nil { + c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam) + return false + } + c.Request.Body = io.NopCloser(bytes.NewBuffer(body)) + if len(bytes.TrimSpace(body)) == 0 { + return true + } + + var payload struct { + BranchId *int64 `json:"branchId"` + UserId *int64 `json:"userId"` + } + if err := json.Unmarshal(body, &payload); err != nil { + return true + } + + if payload.BranchId != nil && *payload.BranchId > 0 && !containsInt64(branchIDs, *payload.BranchId) { + c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) + return false + } + if payload.UserId != nil && *payload.UserId > 0 { + visible, err := service.UserVisibleInBranches(c.Request.Context(), *payload.UserId, branchIDs) + if err != nil { + c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return false + } + if !visible { + c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) + return false + } + } + return true +} + +func adminREST(path string) string { + rest := strings.TrimSuffix(strings.TrimPrefix(path, adminPrefix), "/") + if rest == "" { + return "" + } + if !strings.HasPrefix(rest, "/") { + rest = "/" + rest + } + return rest +} + +var operatorWritePrefixes = []string{ + "/profile", + "/file", + "/users", + "/branch-users", + "/cards", + "/card-orders", + "/card-pin-orders", + "/visa-master-payment-orders", + "/loan-orders", + "/loans-repayment", + "/loan-paid-off-letters", +} + +var operatorGetPrefixes = []string{ + "/profile", + "/file", + "/users", + "/cards", + "/card-orders", + "/card-pin-orders", + "/payment-cards", + "/reasons-cards", + "/visa-master-payment-orders", + "/loan-orders", + "/loan-types", + "/loans-documents", + "/loans-repayment", + "/loan-paid-off-letters", + "/provinces", + "/branches", +} diff --git a/internal/identity/rbac/scope.go b/internal/identity/rbac/scope.go new file mode 100644 index 0000000..73a1824 --- /dev/null +++ b/internal/identity/rbac/scope.go @@ -0,0 +1,104 @@ +package rbac + +import ( + "fmt" + "net/http" + + "online-back/internal/appresult" + + "github.com/gin-gonic/gin" +) + +const ( + contextBranchIDs = "branchIds" + contextService = "rbacService" +) + +func BranchIDsFrom(c *gin.Context) []int64 { + raw, ok := c.Get(contextBranchIDs) + if !ok { + return nil + } + ids, _ := raw.([]int64) + return ids +} + +func HasBranchScope(c *gin.Context) bool { + return len(BranchIDsFrom(c)) > 0 +} + +func AllowsBranch(c *gin.Context, branchID int64) bool { + ids := BranchIDsFrom(c) + if len(ids) == 0 { + return true + } + return containsInt64(ids, branchID) +} + +func BindBranchIDs(c *gin.Context, dest *[]int64) { + ids := BranchIDsFrom(c) + if len(ids) == 0 { + return + } + *dest = ids +} + +func GuardBranch(c *gin.Context, branchID int64) bool { + if AllowsBranch(c, branchID) { + return true + } + c.JSON(http.StatusForbidden, appresult.ErrForbidden) + return false +} + +func GuardUser(c *gin.Context, userID int64) bool { + ids := BranchIDsFrom(c) + if len(ids) == 0 { + return true + } + raw, ok := c.Get(contextService) + if !ok { + c.JSON(http.StatusForbidden, appresult.ErrForbidden) + return false + } + service, _ := raw.(*Service) + if service == nil { + c.JSON(http.StatusForbidden, appresult.ErrForbidden) + return false + } + visible, err := service.UserVisibleInBranches(c.Request.Context(), userID, ids) + if err != nil || !visible { + c.JSON(http.StatusForbidden, appresult.ErrForbidden) + return false + } + return true +} + +func AppendBranchIDs(conditions []string, args []interface{}, column string, ids []int64) ([]string, []interface{}) { + if len(ids) == 0 { + return conditions, args + } + args = append(args, ids) + conditions = append(conditions, fmt.Sprintf("%s = ANY($%d)", column, len(args))) + return conditions, args +} + +func UserInBranchSQL(userExpr string, placeholder int) string { + return fmt.Sprintf(`( + EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = %s AND bu.branch_id = ANY($%d)) + OR EXISTS (SELECT 1 FROM card_orders co WHERE co.user_id = %s AND co.branch_id = ANY($%d)) + OR EXISTS (SELECT 1 FROM loan_orders lo WHERE lo.user_id = %s AND lo.branch_id = ANY($%d)) + OR EXISTS (SELECT 1 FROM card_pin_orders cpo WHERE cpo.user_id = %s AND cpo.branch_id = ANY($%d)) + OR EXISTS (SELECT 1 FROM visa_master_payment_orders vmo WHERE vmo.user_id = %s AND vmo.branch_id = ANY($%d)) + OR EXISTS (SELECT 1 FROM loan_paid_off_letters lpl WHERE lpl.user_id = %s AND lpl.branch_id = ANY($%d)) + )`, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder) +} + +func containsInt64(ids []int64, want int64) bool { + for _, id := range ids { + if id == want { + return true + } + } + return false +} diff --git a/internal/identity/rbac/service.go b/internal/identity/rbac/service.go index 021228f..353cca7 100644 --- a/internal/identity/rbac/service.go +++ b/internal/identity/rbac/service.go @@ -1,18 +1,12 @@ -// Package rbac provides permission-check capability on top of the existing -// permissions/permission_user tables. It is not wired into any route yet — -// today every route is still gated only by appresult.JwtTokenCheck()'s -// admin-claim check. RequirePermission is available for routes to opt into -// once permission data is populated and specific routes are chosen. -// -// Note: the schema has no role_permission pivot table, so role-based -// permission resolution isn't possible yet — HasPermission only resolves -// permissions granted directly via permission_user. package rbac import ( "context" + "errors" "online-back/pkg/client/postgresql" + + "github.com/jackc/pgx/v4" ) type Service struct { @@ -23,15 +17,14 @@ func NewService(client postgresql.Client) *Service { return &Service{client: client} } -// HasPermission reports whether userID has been directly granted the -// permission identified by code (permissions.code) via permission_user. func (s *Service) HasPermission(ctx context.Context, userID int64, code string) (bool, error) { const query = ` SELECT EXISTS ( SELECT 1 - FROM permission_user pu - JOIN permissions p ON p.id = pu.permission_id - WHERE pu.user_id = $1 AND p.code = $2 + FROM role_user ru + JOIN permission_role pr ON pr.role_id = ru.role_id + JOIN permissions p ON p.id = pr.permission_id + WHERE ru.user_id = $1 AND p.code = $2 )` var granted bool @@ -40,3 +33,57 @@ func (s *Service) HasPermission(ctx context.Context, userID int64, code string) } return granted, nil } + +func (s *Service) RoleCode(ctx context.Context, userID int64) (string, error) { + const query = ` + SELECT r.code + FROM role_user ru + JOIN roles r ON r.id = ru.role_id + WHERE ru.user_id = $1 + ORDER BY ru.id + LIMIT 1` + + var code string + err := s.client.QueryRow(ctx, query, userID).Scan(&code) + if errors.Is(err, pgx.ErrNoRows) { + return "", nil + } + return code, err +} + +func (s *Service) BranchIDs(ctx context.Context, userID int64) ([]int64, error) { + const query = ` + SELECT bu.branch_id + FROM branch_user bu + WHERE bu.user_id = $1 + ORDER BY bu.id` + + rows, err := s.client.Query(ctx, query, userID) + if err != nil { + return nil, err + } + defer rows.Close() + + var ids []int64 + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return nil, err + } + ids = append(ids, id) + } + return ids, rows.Err() +} + +func (s *Service) UserVisibleInBranches(ctx context.Context, userID int64, branchIDs []int64) (bool, error) { + if len(branchIDs) == 0 { + return false, nil + } + query := `SELECT ` + UserInBranchSQL("u.id", 2) + ` FROM users u WHERE u.id = $1` + var ok bool + err := s.client.QueryRow(ctx, query, userID, branchIDs).Scan(&ok) + if errors.Is(err, pgx.ErrNoRows) { + return false, nil + } + return ok, err +} diff --git a/internal/identity/rbac/service_test.go b/internal/identity/rbac/service_test.go deleted file mode 100644 index faef505..0000000 --- a/internal/identity/rbac/service_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package rbac - -import ( - "context" - "testing" - - "github.com/jackc/pgconn" - "github.com/jackc/pgx/v4" -) - -type fakeClient struct { - granted bool -} - -func (f *fakeClient) Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error) { - return nil, nil -} - -func (f *fakeClient) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) { - return nil, nil -} - -func (f *fakeClient) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row { - return fakeRow{granted: f.granted} -} - -func (f *fakeClient) Begin(ctx context.Context) (pgx.Tx, error) { - return nil, nil -} - -type fakeRow struct { - granted bool -} - -func (r fakeRow) Scan(dest ...interface{}) error { - *dest[0].(*bool) = r.granted - return nil -} - -func TestHasPermission(t *testing.T) { - granted, err := NewService(&fakeClient{granted: true}).HasPermission(context.Background(), 1, "province.write") - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !granted { - t.Fatal("expected permission to be granted") - } - - granted, err = NewService(&fakeClient{granted: false}).HasPermission(context.Background(), 1, "province.write") - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if granted { - t.Fatal("expected permission to not be granted") - } -} diff --git a/internal/identity/router.go b/internal/identity/router.go index be7c228..d2fe7ae 100644 --- a/internal/identity/router.go +++ b/internal/identity/router.go @@ -1,6 +1,3 @@ -// Package identity groups authentication, users, and RBAC (roles, -// permissions, and their user/branch assignments) under one bounded -// context, replacing the flat internal/admin/* listing. package identity import ( @@ -11,8 +8,8 @@ import ( authdb "online-back/internal/identity/auth/db" "online-back/internal/identity/permission" permissiondb "online-back/internal/identity/permission/db" - "online-back/internal/identity/permissionuser" - permissionuserdb "online-back/internal/identity/permissionuser/db" + "online-back/internal/identity/permissionrole" + permissionroledb "online-back/internal/identity/permissionrole/db" "online-back/internal/identity/role" roledb "online-back/internal/identity/role/db" "online-back/internal/identity/roleusers" @@ -28,7 +25,6 @@ import ( "github.com/gin-gonic/gin" ) - func Register(router *gin.RouterGroup, engine *gin.Engine, client postgresql.Client, logger *logging.Logger) { userH := user.NewHandler(logger, userdb.NewRepository(client, logger)) userH.Register(router) @@ -46,7 +42,7 @@ func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handl role.NewHandler(logger, roledb.NewRepository(client, logger)), permission.NewHandler(logger, permissiondb.NewRepository(client, logger)), roleusers.NewHandler(logger, roleusersdb.NewRepository(client, logger)), - permissionuser.NewHandler(logger, permissionuserdb.NewRepository(client, logger)), + permissionrole.NewHandler(logger, permissionroledb.NewRepository(client, logger)), userbranch.NewHandler(logger, userbranchdb.NewRepository(client, logger)), } } diff --git a/internal/identity/user/db/postgresql.go b/internal/identity/user/db/postgresql.go index 43a64b9..72e9254 100644 --- a/internal/identity/user/db/postgresql.go +++ b/internal/identity/user/db/postgresql.go @@ -8,6 +8,7 @@ import ( "fmt" "strings" + "online-back/internal/identity/rbac" "online-back/internal/identity/user" "online-back/pkg/client/postgresql" "online-back/pkg/logging" @@ -98,7 +99,13 @@ func (r *repository) ListStaff(ctx context.Context, filter user.ListFilter) (use } func buildStaffWhere(filter user.ListFilter) (whereClause string, args []interface{}) { - conditions := []string{`EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`} + var conditions []string + if len(filter.BranchIds) > 0 { + args = append(args, filter.BranchIds) + conditions = append(conditions, fmt.Sprintf(`EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.branch_id = ANY($%d))`, len(args))) + } else { + conditions = append(conditions, `EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`) + } conditions, args = appendNameSearch(conditions, args, filter.Search) return " WHERE " + strings.Join(conditions, " AND "), args } @@ -145,17 +152,22 @@ func buildFilteredListQuery(filter user.ListFilter, roles ...string) (fromClause var conditions []string conditions, args = appendNameSearch(conditions, args, filter.Search) - if len(roles) == 1 { - args = append(args, roles[0]) - n := len(args) - conditions = append(conditions, fmt.Sprintf(`r.code = $%d`, n)) - } else if len(roles) > 0 { + if len(roles) > 0 { placeholders := make([]string, len(roles)) for i, role := range roles { args = append(args, role) placeholders[i] = fmt.Sprintf("$%d", len(args)) } - conditions = append(conditions, fmt.Sprintf(`r.code IN (%s)`, strings.Join(placeholders, ", "))) + if len(roles) == 1 { + conditions = append(conditions, fmt.Sprintf(`r.code = %s`, placeholders[0])) + } else { + conditions = append(conditions, fmt.Sprintf(`r.code IN (%s)`, strings.Join(placeholders, ", "))) + } + } + + if len(filter.BranchIds) > 0 { + args = append(args, filter.BranchIds) + conditions = append(conditions, rbac.UserInBranchSQL("u.id", len(args))) } if len(conditions) == 0 { @@ -187,11 +199,13 @@ func likePattern(term string) string { func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) { fromClause, whereClause, args := buildFilteredListQuery(filter, role) - excludeStaff := `NOT EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)` - if whereClause == "" { - whereClause = " WHERE " + excludeStaff - } else { - whereClause += " AND " + excludeStaff + if len(filter.BranchIds) == 0 { + excludeStaff := `NOT EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)` + if whereClause == "" { + whereClause = " WHERE " + excludeStaff + } else { + whereClause += " AND " + excludeStaff + } } return r.paginateUsers(ctx, filter, fromClause, whereClause, args) } diff --git a/internal/identity/user/dto.go b/internal/identity/user/dto.go index b922ba8..1d777d5 100644 --- a/internal/identity/user/dto.go +++ b/internal/identity/user/dto.go @@ -57,9 +57,10 @@ type UpdateUserDTO struct { } type ListFilter struct { - Search string - Page int - Limit int + Search string + BranchIds []int64 + Page int + Limit int } type ListUserDTO struct { diff --git a/internal/identity/user/handler.go b/internal/identity/user/handler.go index e715ee0..935c28b 100644 --- a/internal/identity/user/handler.go +++ b/internal/identity/user/handler.go @@ -13,6 +13,7 @@ import ( "online-back/internal/appresult" "online-back/internal/config" + "online-back/internal/identity/rbac" "online-back/pkg/logging" minioUpload "online-back/pkg/minio" @@ -180,6 +181,9 @@ func (h *handler) getByID(c *gin.Context) { c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } + if !rbac.GuardUser(c, item.Id) { + return + } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } @@ -234,6 +238,10 @@ func (h *handler) update(c *gin.Context) { 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) @@ -273,6 +281,10 @@ func (h *handler) delete(c *gin.Context) { return } + if rbac.HasBranchScope(c) && !rbac.GuardUser(c, id) { + return + } + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return @@ -327,6 +339,8 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) { filter.Search = raw } + rbac.BindBranchIDs(c, &filter.BranchIds) + return filter, true } diff --git a/internal/identity/userbranch/db/postgresql.go b/internal/identity/userbranch/db/postgresql.go index 93a08e7..32e2b75 100644 --- a/internal/identity/userbranch/db/postgresql.go +++ b/internal/identity/userbranch/db/postgresql.go @@ -50,6 +50,16 @@ func (r *repository) Create(ctx context.Context, dto userbranch.CreateUserBranch return scanUserBranch(row) } +func (r *repository) GetByID(ctx context.Context, id int64) (userbranch.UserBranchDTO, error) { + query := ` + SELECT bu.id, bu.branch_id, b.name, bu.user_id, u.name, bu.created_at, bu.updated_at + FROM branch_user bu + JOIN branches b ON b.id = bu.branch_id + JOIN users u ON u.id = bu.user_id + WHERE bu.id = $1` + return scanUserBranch(r.client.QueryRow(ctx, query, id)) +} + func (r *repository) Delete(ctx context.Context, id int64) error { tag, err := r.client.Exec(ctx, `DELETE FROM branch_user WHERE id = $1`, id) if err != nil { diff --git a/internal/identity/userbranch/handler.go b/internal/identity/userbranch/handler.go index 24fb7e2..5bb90be 100644 --- a/internal/identity/userbranch/handler.go +++ b/internal/identity/userbranch/handler.go @@ -7,6 +7,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" "online-back/pkg/logging" "github.com/gin-gonic/gin" @@ -78,6 +79,21 @@ func (h *handler) delete(c *gin.Context) { return } + if rbac.HasBranchScope(c) { + 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 { + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + if !rbac.GuardBranch(c, item.BranchId) { + return + } + } + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return diff --git a/internal/identity/userbranch/storage.go b/internal/identity/userbranch/storage.go index cb4c49f..75fc262 100644 --- a/internal/identity/userbranch/storage.go +++ b/internal/identity/userbranch/storage.go @@ -4,5 +4,6 @@ import "context" type Repository interface { Create(ctx context.Context, dto CreateUserBranchDTO) (UserBranchDTO, error) + GetByID(ctx context.Context, id int64) (UserBranchDTO, error) Delete(ctx context.Context, id int64) error } diff --git a/internal/lending/loanorders/db/postgresql.go b/internal/lending/loanorders/db/postgresql.go index 23c4b6f..668fb87 100644 --- a/internal/lending/loanorders/db/postgresql.go +++ b/internal/lending/loanorders/db/postgresql.go @@ -6,6 +6,7 @@ import ( "fmt" "strings" + "online-back/internal/identity/rbac" "online-back/internal/lending/loanorders" "online-back/pkg/client/postgresql" "online-back/pkg/logging" @@ -161,7 +162,9 @@ func buildListQuery(filter loanorders.ListFilter) (whereClause string, args []in conditions = append(conditions, fmt.Sprintf("lo.status = $%d", len(args))) } - if filter.BranchId != nil { + if len(filter.BranchIds) > 0 { + conditions, args = rbac.AppendBranchIDs(conditions, args, "lo.branch_id", filter.BranchIds) + } else if filter.BranchId != nil { args = append(args, *filter.BranchId) conditions = append(conditions, fmt.Sprintf("lo.branch_id = $%d", len(args))) } diff --git a/internal/lending/loanorders/dto.go b/internal/lending/loanorders/dto.go index 199ab9b..11a080a 100644 --- a/internal/lending/loanorders/dto.go +++ b/internal/lending/loanorders/dto.go @@ -227,13 +227,14 @@ type UpdateLoanOrderDTO struct { } type ListFilter struct { - Status *string - BranchId *int64 - UserId *int64 - Source string - Region string - Page int - Limit int + Status *string + BranchId *int64 + BranchIds []int64 + UserId *int64 + Source string + Region string + Page int + Limit int } type ListLoanOrderDTO struct { diff --git a/internal/lending/loanorders/handler.go b/internal/lending/loanorders/handler.go index 52642ca..6a26089 100644 --- a/internal/lending/loanorders/handler.go +++ b/internal/lending/loanorders/handler.go @@ -8,6 +8,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" "online-back/pkg/logging" "github.com/gin-gonic/gin" @@ -126,6 +127,9 @@ func (h *handler) getByID(c *gin.Context) { c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } + if !rbac.GuardBranch(c, item.BranchId) { + return + } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } @@ -180,6 +184,10 @@ func (h *handler) update(c *gin.Context) { return } + if !h.guardBranchByID(c, id) { + return + } + var dto UpdateLoanOrderDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) @@ -219,6 +227,10 @@ func (h *handler) delete(c *gin.Context) { return } + if !h.guardBranchByID(c, id) { + return + } + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return @@ -291,5 +303,22 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) { filter.Region = raw } + rbac.BindBranchIDs(c, &filter.BranchIds) return filter, true } + +func (h *handler) guardBranchByID(c *gin.Context, id int64) bool { + if !rbac.HasBranchScope(c) { + return true + } + item, err := h.repository.GetByID(c.Request.Context(), id) + if errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return false + } + if err != nil { + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return false + } + return rbac.GuardBranch(c, item.BranchId) +} diff --git a/internal/lending/loanpaidletter/db/postgresql.go b/internal/lending/loanpaidletter/db/postgresql.go index 151089c..d2dac0d 100644 --- a/internal/lending/loanpaidletter/db/postgresql.go +++ b/internal/lending/loanpaidletter/db/postgresql.go @@ -6,6 +6,7 @@ import ( "fmt" "strings" + "online-back/internal/identity/rbac" "online-back/internal/lending/loanpaidletter" "online-back/pkg/client/postgresql" "online-back/pkg/logging" @@ -137,7 +138,9 @@ func buildListQuery(filter loanpaidletter.ListFilter) (whereClause string, args conditions = append(conditions, fmt.Sprintf("l.status = $%d", len(args))) } - if filter.BranchId != nil { + if len(filter.BranchIds) > 0 { + conditions, args = rbac.AppendBranchIDs(conditions, args, "l.branch_id", filter.BranchIds) + } else if filter.BranchId != nil { args = append(args, *filter.BranchId) conditions = append(conditions, fmt.Sprintf("l.branch_id = $%d", len(args))) } diff --git a/internal/lending/loanpaidletter/dto.go b/internal/lending/loanpaidletter/dto.go index 317db8b..1995c34 100644 --- a/internal/lending/loanpaidletter/dto.go +++ b/internal/lending/loanpaidletter/dto.go @@ -80,6 +80,7 @@ type ListFilter struct { Name string Status *string BranchId *int64 + BranchIds []int64 Region string Page int Limit int diff --git a/internal/lending/loanpaidletter/handler.go b/internal/lending/loanpaidletter/handler.go index e9ffedb..76e7090 100644 --- a/internal/lending/loanpaidletter/handler.go +++ b/internal/lending/loanpaidletter/handler.go @@ -8,6 +8,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" "online-back/pkg/logging" "github.com/gin-gonic/gin" @@ -137,6 +138,9 @@ func (h *handler) getByID(c *gin.Context) { c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } + if !rbac.GuardBranch(c, item.BranchId) { + return + } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } @@ -191,6 +195,10 @@ func (h *handler) update(c *gin.Context) { return } + if !h.guardBranchByID(c, id) { + return + } + var dto UpdateLoanPaidLetterDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) @@ -230,6 +238,10 @@ func (h *handler) delete(c *gin.Context) { return } + if !h.guardBranchByID(c, id) { + return + } + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return @@ -302,5 +314,22 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) { filter.BranchId = &id } + rbac.BindBranchIDs(c, &filter.BranchIds) return filter, true } + +func (h *handler) guardBranchByID(c *gin.Context, id int64) bool { + if !rbac.HasBranchScope(c) { + return true + } + item, err := h.repository.GetByID(c.Request.Context(), id) + if errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return false + } + if err != nil { + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return false + } + return rbac.GuardBranch(c, item.BranchId) +} diff --git a/internal/lending/loansrepayment/db/postgresql.go b/internal/lending/loansrepayment/db/postgresql.go index f1f2732..9075cc9 100644 --- a/internal/lending/loansrepayment/db/postgresql.go +++ b/internal/lending/loansrepayment/db/postgresql.go @@ -6,6 +6,7 @@ import ( "fmt" "strings" + "online-back/internal/identity/rbac" "online-back/internal/lending/loansrepayment" "online-back/pkg/client/postgresql" "online-back/pkg/logging" @@ -81,6 +82,11 @@ func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args conditions = append(conditions, fmt.Sprintf("l.passport_id ILIKE $%d", len(args))) } + if len(filter.BranchIds) > 0 { + args = append(args, filter.BranchIds) + conditions = append(conditions, rbac.UserInBranchSQL("l.user_id", len(args))) + } + if len(conditions) == 0 { return "", args } diff --git a/internal/lending/loansrepayment/dto.go b/internal/lending/loansrepayment/dto.go index b37832c..fb8f038 100644 --- a/internal/lending/loansrepayment/dto.go +++ b/internal/lending/loansrepayment/dto.go @@ -29,6 +29,7 @@ type UpdateLoanRepaymentDTO struct { type ListFilter struct { PassportId string + BranchIds []int64 Page int Limit int } diff --git a/internal/lending/loansrepayment/handler.go b/internal/lending/loansrepayment/handler.go index a02949a..b4e6de1 100644 --- a/internal/lending/loansrepayment/handler.go +++ b/internal/lending/loansrepayment/handler.go @@ -8,6 +8,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" "online-back/pkg/logging" "github.com/gin-gonic/gin" @@ -93,6 +94,9 @@ func (h *handler) getByID(c *gin.Context) { c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } + if !rbac.GuardUser(c, item.UserId) { + return + } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } @@ -147,6 +151,10 @@ func (h *handler) update(c *gin.Context) { return } + if !h.guardUserByID(c, id) { + return + } + var dto UpdateLoanRepaymentDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) @@ -186,6 +194,10 @@ func (h *handler) delete(c *gin.Context) { return } + if !h.guardUserByID(c, id) { + return + } + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return @@ -238,5 +250,22 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) { filter.PassportId = raw } + rbac.BindBranchIDs(c, &filter.BranchIds) return filter, true } + +func (h *handler) guardUserByID(c *gin.Context, id int64) bool { + if !rbac.HasBranchScope(c) { + return true + } + item, err := h.repository.GetByID(c.Request.Context(), id) + if errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return false + } + if err != nil { + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return false + } + return rbac.GuardUser(c, item.UserId) +} diff --git a/internal/org/branches/db/postgresql.go b/internal/org/branches/db/postgresql.go index af7341c..95227a8 100644 --- a/internal/org/branches/db/postgresql.go +++ b/internal/org/branches/db/postgresql.go @@ -7,6 +7,7 @@ import ( "fmt" "strings" + "online-back/internal/identity/rbac" "online-back/internal/org/branches" "online-back/pkg/client/postgresql" "online-back/pkg/logging" @@ -125,6 +126,10 @@ func buildListQuery(filter branches.ListFilter) (whereClause string, args []inte conditions = append(conditions, fmt.Sprintf("b.unique_code ILIKE $%d", n)) } + if len(filter.BranchIds) > 0 { + conditions, args = rbac.AppendBranchIDs(conditions, args, "b.id", filter.BranchIds) + } + if len(conditions) == 0 { return "", args } diff --git a/internal/org/branches/dto.go b/internal/org/branches/dto.go index fe10a71..137f03e 100644 --- a/internal/org/branches/dto.go +++ b/internal/org/branches/dto.go @@ -7,23 +7,23 @@ type LocalizedText struct { } type BranchDTO struct { - Id int64 `json:"id"` - UniqueCode string `json:"uniqueCode"` - Name LocalizedText `json:"name"` - Address LocalizedText `json:"address"` - Region string `json:"region"` - ProvinceId *int64 `json:"provinceId"` - ProvinceName LocalizedText `json:"provinceName"` - PhoneNumbers string `json:"phoneNumbers"` - BillingUsername string `json:"billingUsername"` - BillingPassword string `json:"billingPassword"` - BillingSberUsername string `json:"billingSberUsername"` - BillingSberPassword string `json:"billingSberPassword"` - BillingVisaMasterUsername string `json:"billingVisaMasterUsername"` - BillingVisaMasterPassword string `json:"billingVisaMasterPassword"` - BillingSwiftUsername string `json:"billingSwiftUsername"` - BillingSwiftPassword string `json:"billingSwiftPassword"` - Active bool `json:"active"` + Id int64 `json:"id"` + UniqueCode string `json:"uniqueCode"` + Name LocalizedText `json:"name"` + Address LocalizedText `json:"address"` + Region string `json:"region"` + ProvinceId *int64 `json:"provinceId"` + ProvinceName LocalizedText `json:"provinceName"` + PhoneNumbers string `json:"phoneNumbers"` + BillingUsername string `json:"billingUsername"` + BillingPassword string `json:"billingPassword"` + BillingSberUsername string `json:"billingSberUsername"` + BillingSberPassword string `json:"billingSberPassword"` + BillingVisaMasterUsername string `json:"billingVisaMasterUsername"` + BillingVisaMasterPassword string `json:"billingVisaMasterPassword"` + BillingSwiftUsername string `json:"billingSwiftUsername"` + BillingSwiftPassword string `json:"billingSwiftPassword"` + Active bool `json:"active"` } type CreateBranchDTO struct { @@ -67,6 +67,7 @@ type ListFilter struct { ProvinceName string BranchName string UniqueCode string + BranchIds []int64 Page int Limit int } diff --git a/internal/org/branches/handler.go b/internal/org/branches/handler.go index 1d32932..db5fe5f 100644 --- a/internal/org/branches/handler.go +++ b/internal/org/branches/handler.go @@ -8,6 +8,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" "online-back/internal/org/province" "online-back/pkg/logging" @@ -163,6 +164,9 @@ func (h *handler) getByID(c *gin.Context) { c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } + if !rbac.GuardBranch(c, item.Id) { + return + } c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } @@ -349,5 +353,6 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) { filter.UniqueCode = raw } + rbac.BindBranchIDs(c, &filter.BranchIds) return filter, true }