From 323e131216a8256a8685553045664df683895edb Mon Sep 17 00:00:00 2001 From: GuwandykA Date: Sat, 26 Sep 2026 16:34:28 +0500 Subject: [PATCH] changed role permission --- .DS_Store | Bin 10244 -> 10244 bytes README.md | 9 + README_2.md | 2 +- db/migrations/20260926120000_rbac_v2.down.sql | 88 ++ db/migrations/20260926120000_rbac_v2.up.sql | 162 ++++ db/seed.sql | 187 ++-- docs/docs.go | 881 +++++------------ docs/swagger.json | 881 +++++------------ docs/swagger.yaml | 615 ++++-------- docs/tag_order.go | 2 - internal/appresult/error.go | 4 + internal/backup/handler.go | 4 +- internal/cards/cardbalance/handler.go | 3 +- internal/cards/cardorder/handler.go | 3 +- internal/cards/cardpinorders/handler.go | 3 +- internal/cards/cardrekwizit/handler.go | 3 +- internal/cards/cards/handler.go | 3 +- internal/cards/paymentcard/handler.go | 4 +- internal/cards/reasonscard/handler.go | 4 +- internal/cards/visamaster/handler.go | 3 +- internal/currency/handler.go | 4 +- internal/dashboard/db/postgresql.go | 2 +- internal/dashboard/handler.go | 34 +- internal/handlers/manager/manager.go | 10 + .../identity/activitylog/db/postgresql.go | 18 +- internal/identity/activitylog/handler.go | 6 +- internal/identity/auth/db/postgresql.go | 70 +- internal/identity/auth/dto.go | 24 +- internal/identity/auth/handler.go | 19 +- internal/identity/auth/profile_modules.go | 37 - internal/identity/permission/db/postgresql.go | 139 --- internal/identity/permission/dto.go | 54 -- internal/identity/permission/handler.go | 258 +---- internal/identity/permission/module.go | 43 - internal/identity/permission/storage.go | 12 - internal/identity/permission/tree.go | 67 -- .../identity/permissionrole/db/postgresql.go | 101 -- internal/identity/permissionrole/dto.go | 24 - internal/identity/permissionrole/handler.go | 91 -- internal/identity/permissionrole/storage.go | 10 - internal/identity/rbac/middleware.go | 729 ++++---------- internal/identity/rbac/middleware_test.go | 895 ------------------ internal/identity/rbac/perm/perm.go | 99 ++ internal/identity/rbac/principal.go | 141 +++ internal/identity/rbac/rbac_test.go | 373 ++++++++ internal/identity/rbac/registry.go | 126 +++ internal/identity/rbac/roleinfo.go | 36 + internal/identity/rbac/scope.go | 88 +- internal/identity/rbac/service.go | 167 ++-- internal/identity/role/db/postgresql.go | 179 +++- internal/identity/role/dto.go | 47 +- internal/identity/role/handler.go | 101 +- internal/identity/role/storage.go | 11 +- internal/identity/roleusers/db/postgresql.go | 70 -- internal/identity/roleusers/dto.go | 18 - internal/identity/roleusers/handler.go | 59 -- internal/identity/roleusers/storage.go | 8 - internal/identity/router.go | 9 +- internal/identity/user/db/postgresql.go | 151 +-- internal/identity/user/dto.go | 28 +- internal/identity/user/handler.go | 243 ++++- internal/identity/user/handler_test.go | 97 -- internal/identity/user/storage.go | 22 +- internal/identity/userbranch/handler.go | 3 +- internal/lending/loanorders/handler.go | 3 +- internal/lending/loanpaidletter/handler.go | 3 +- internal/lending/loansdocument/handler.go | 4 +- internal/lending/loansrepayment/handler.go | 3 +- internal/lending/loantype/handler.go | 4 +- internal/org/branches/handler.go | 7 +- internal/org/province/handler.go | 4 +- internal/payment/paymenthistory/handler.go | 3 +- internal/payment/paymentsettings/handler.go | 4 +- internal/payment/visamasterpay/handler.go | 9 +- 74 files changed, 2915 insertions(+), 4713 deletions(-) create mode 100644 db/migrations/20260926120000_rbac_v2.down.sql create mode 100644 db/migrations/20260926120000_rbac_v2.up.sql delete mode 100644 internal/identity/auth/profile_modules.go delete mode 100644 internal/identity/permission/db/postgresql.go delete mode 100644 internal/identity/permission/dto.go delete mode 100644 internal/identity/permission/module.go delete mode 100644 internal/identity/permission/storage.go delete mode 100644 internal/identity/permission/tree.go delete mode 100644 internal/identity/permissionrole/db/postgresql.go delete mode 100644 internal/identity/permissionrole/dto.go delete mode 100644 internal/identity/permissionrole/handler.go delete mode 100644 internal/identity/permissionrole/storage.go delete mode 100644 internal/identity/rbac/middleware_test.go create mode 100644 internal/identity/rbac/perm/perm.go create mode 100644 internal/identity/rbac/principal.go create mode 100644 internal/identity/rbac/rbac_test.go create mode 100644 internal/identity/rbac/registry.go create mode 100644 internal/identity/rbac/roleinfo.go delete mode 100644 internal/identity/roleusers/db/postgresql.go delete mode 100644 internal/identity/roleusers/dto.go delete mode 100644 internal/identity/roleusers/handler.go delete mode 100644 internal/identity/roleusers/storage.go delete mode 100644 internal/identity/user/handler_test.go diff --git a/.DS_Store b/.DS_Store index 5eba961ae6e1c0c804999d3f4850abb3b7d5027e..3883513c089bbf6d1f0c21e1b97c208a161280ff 100644 GIT binary patch delta 118 zcmZn(XbIRLDaIr%HCbBh&g3@|(vxoqS&1hlFn~ZvUVdIGr?Nu;n8(05SzB0 'own' AND deleted_at IS NULL +ON CONFLICT DO NOTHING; + +-- --------------------------------------------------------------------------- +-- users.role_id +-- --------------------------------------------------------------------------- +ALTER TABLE users ADD COLUMN role_id bigint REFERENCES roles(id); + +UPDATE users u SET role_id = x.role_id +FROM ( + SELECT DISTINCT ON (ru.user_id) ru.user_id, ru.role_id + FROM role_user ru + JOIN roles r ON r.id = ru.role_id AND r.deleted_at IS NULL + WHERE ru.deleted_at IS NULL + ORDER BY ru.user_id, ru.id +) x +WHERE u.id = x.user_id; + +UPDATE users u SET role_id = r.id +FROM roles r +WHERE u.role_id IS NULL AND r.code = u.role AND r.deleted_at IS NULL; + +UPDATE users SET role_id = (SELECT id FROM roles WHERE code = 'user' AND deleted_at IS NULL) +WHERE role_id IS NULL; + +ALTER TABLE users ALTER COLUMN role_id SET NOT NULL; +CREATE INDEX idx_users_role_id ON users (role_id); + +-- --------------------------------------------------------------------------- +-- Köne gurluşy aýyrmak +-- --------------------------------------------------------------------------- +DROP TABLE permission_role; +DROP TABLE role_user; +DROP TABLE permissions_old; +ALTER TABLE roles DROP COLUMN guard_name; +ALTER TABLE users DROP COLUMN role; + +-- --------------------------------------------------------------------------- +-- Cache wersiýasy +-- --------------------------------------------------------------------------- +CREATE TABLE rbac_version ( + id int PRIMARY KEY DEFAULT 1 CHECK (id = 1), + version bigint NOT NULL DEFAULT 0 +); +INSERT INTO rbac_version (id, version) VALUES (1, 0); + +CREATE OR REPLACE FUNCTION rbac_bump_version() RETURNS trigger AS $$ +BEGIN + UPDATE rbac_version SET version = version + 1 WHERE id = 1; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER rbac_bump_roles + AFTER INSERT OR UPDATE OR DELETE ON roles + FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version(); +CREATE TRIGGER rbac_bump_role_permissions + AFTER INSERT OR UPDATE OR DELETE ON role_permissions + FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version(); +CREATE TRIGGER rbac_bump_users + AFTER UPDATE OF role_id, deleted_at OR DELETE ON users + FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version(); +CREATE TRIGGER rbac_bump_branch_user + AFTER INSERT OR UPDATE OR DELETE ON branch_user + FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version(); +CREATE TRIGGER rbac_bump_branches + AFTER UPDATE OF deleted_at OR DELETE ON branches + FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version(); + +COMMIT; diff --git a/db/seed.sql b/db/seed.sql index ff58148..aae2ec4 100644 --- a/db/seed.sql +++ b/db/seed.sql @@ -2,14 +2,15 @@ -- Usage: make seed -- or: PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/seed.sql -- Login (password = test1234): --- superadmin@bank.tm / +993 61 92 92 48 (hemme zada rugsatly, ýeke-täk bypass rol) --- admin@bank.tm (ähli permission berlen) --- manager@bank.tm (admin guard, ýöne diňe cards + loans saha) --- operator@bank.tm (cards saha) --- loanop@bank.tm (loans saha) --- bothop@bank.tm (cards + loans) --- currency@bank.tm (admin guard — diňe walýuta sahasy) --- serdar@bank.tm … leyla@bank.tm (role=user) +-- superadmin@bank.tm / +993 61 92 92 48 (is_super: ähli permission awtomatik) +-- admin@bank.tm (scope=all, roles we backups-dan başga ähli) +-- manager@bank.tm (scope=branch: cards, loans, users, dashboard) +-- operator@bank.tm (scope=branch: cards) +-- loanop@bank.tm (scope=branch: loans) +-- bothop@bank.tm (scope=branch: cards + loans) +-- loanhead@bank.tm (scope=all: loans — ähli filiallaryň karz bölümi) +-- currency@bank.tm (scope=all: diňe walýuta) +-- serdar@bank.tm … leyla@bank.tm (role=user, scope=own) BEGIN; @@ -33,178 +34,151 @@ TRUNCATE TABLE branch_user, branches, provinces, - permission_role, - role_user, - permissions, + role_permissions, roles, registration_verifications, users RESTART IDENTITY CASCADE; -- --------------------------------------------------------------------------- --- Users (13): superadmin, admin, manager, operator, +-- Roles & permissions. Permission katalogy (permissions tablisasy) app +-- tarapyndan başlanda sinhronlanýar (rbac/perm); bu ýerde diňe rollar. +-- --------------------------------------------------------------------------- +INSERT INTO roles (code, name, scope, is_super, is_system) VALUES + ('user', 'User', 'own', false, true), + ('operator', 'Operator', 'branch', false, false), + ('loan_operator', 'Loan Operator', 'branch', false, false), + ('full_operator', 'Full Operator (cards + loans)','branch', false, false), + ('admin', 'Admin', 'all', false, false), + ('superadmin', 'Superadmin', 'all', true, true), + ('manager', 'Branch Manager', 'branch', false, false), + ('loan_head', 'Karz bölüminiň başlygy', 'all', false, false), + ('currency_maintainer', 'Walyuta kursy operator', 'all', false, false); + +INSERT INTO role_permissions (role_id, permission_code) +SELECT r.id, x.code +FROM (VALUES + ('user', 'cards'), + ('user', 'loans'), + ('operator', 'cards'), + ('operator', 'dashboard'), + ('loan_operator', 'loans'), + ('loan_operator', 'dashboard'), + ('full_operator', 'cards'), + ('full_operator', 'loans'), + ('full_operator', 'dashboard'), + ('admin', 'dashboard'), + ('admin', 'cards'), + ('admin', 'loans'), + ('admin', 'users'), + ('admin', 'branches'), + ('admin', 'provinces'), + ('admin', 'currencies'), + ('admin', 'payment-settings'), + ('admin', 'activity-logs'), + ('manager', 'cards'), + ('manager', 'loans'), + ('manager', 'users'), + ('manager', 'dashboard'), + ('loan_head', 'loans'), + ('loan_head', 'dashboard'), + ('currency_maintainer', 'currencies') +) AS x(role, code) +JOIN roles r ON r.code = x.role; + +-- --------------------------------------------------------------------------- +-- Users (14): superadmin, admin, manager, operator, -- 1 branch-assigned user (serdar), 5 users (gulnar…leyla), --- 1 currency maintainer, 1 loan operator, 1 cards+loans operator. +-- 1 currency maintainer, 1 loan operator, 1 cards+loans operator, +-- 1 head of loans (all branches). -- Password = test1234 for all. Phone unique (idx_users_phone). -- --------------------------------------------------------------------------- -INSERT INTO users (email, password, name, first_name, last_name, username, phone, role, active) VALUES +INSERT INTO users (email, password, name, first_name, last_name, username, phone, role_id, active) VALUES ( 'superadmin@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Super Admin', 'Myrat', 'Nazarow', 'superadmin', - '+993 61 92 92 48', 'superadmin', true + '+993 61 92 92 48', (SELECT id FROM roles WHERE code = 'superadmin'), true ), ( 'admin@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Admin', 'Nurmuhammet', 'Allanow', 'admin', - '+993 61 92 92 41', 'admin', true + '+993 61 92 92 41', (SELECT id FROM roles WHERE code = 'admin'), true ), ( 'manager@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Branch Manager', 'Mergen', 'Berdiyew', 'manager', - '+993 61 92 92 42', 'manager', true + '+993 61 92 92 42', (SELECT id FROM roles WHERE code = 'manager'), true ), ( 'operator@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Operator', 'Aygul', 'Hojayeva', 'operator', - '+993 61 92 92 43', 'operator', true + '+993 61 92 92 43', (SELECT id FROM roles WHERE code = 'operator'), true ), ( 'serdar@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Serdar Myradow', 'Serdar', 'Myradow', 'serdar', - '+993 61 92 92 44', 'user', true + '+993 61 92 92 44', (SELECT id FROM roles WHERE code = 'user'), true ), ( 'gulnar@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Gulnar Orazowa', 'Gulnar', 'Orazowa', 'gulnar', - '+993 61 92 92 45', 'user', true + '+993 61 92 92 45', (SELECT id FROM roles WHERE code = 'user'), true ), ( 'dovran@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Dovran Annayew', 'Dovran', 'Annayew', 'dovran', - '+993 61 92 92 46', 'user', true + '+993 61 92 92 46', (SELECT id FROM roles WHERE code = 'user'), true ), ( 'maya@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Maya Halylowa', 'Maya', 'Halylowa', 'maya', - '+993 61 92 92 47', 'user', true + '+993 61 92 92 47', (SELECT id FROM roles WHERE code = 'user'), true ), ( 'kerim@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Kerim Atayew', 'Kerim', 'Atayew', 'kerim', - '+993 61 92 92 49', 'user', true + '+993 61 92 92 49', (SELECT id FROM roles WHERE code = 'user'), true ), ( 'leyla@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Leyla Gurbanowa', 'Leyla', 'Gurbanowa', 'leyla', - '+993 61 92 92 40', 'user', true + '+993 61 92 92 40', (SELECT id FROM roles WHERE code = 'user'), true ), ( 'currency@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Walýuta operator', 'Berdi', 'Hojayew', 'currency', - '+993 61 92 92 38', 'currency_maintainer', true + '+993 61 92 92 38', (SELECT id FROM roles WHERE code = 'currency_maintainer'), true ), ( 'loanop@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Loan Operator', 'Jeren', 'Atayeva', 'loanop', - '+993 61 92 92 37', 'loan_operator', true + '+993 61 92 92 37', (SELECT id FROM roles WHERE code = 'loan_operator'), true ), ( 'bothop@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', 'Full Operator', 'Batyr', 'Myradow', 'bothop', - '+993 61 92 92 36', 'full_operator', true + '+993 61 92 92 36', (SELECT id FROM roles WHERE code = 'full_operator'), true +), +( + 'loanhead@bank.tm', + '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', + 'Loan Head', 'Aman', 'Orazow', 'loanhead', + '+993 61 92 92 35', (SELECT id FROM roles WHERE code = 'loan_head'), true ); --- --------------------------------------------------------------------------- --- Roles & permissions --- --------------------------------------------------------------------------- -INSERT INTO roles (code, name, guard_name) VALUES - ('user', 'User', 'web'), - ('operator', 'Operator', 'operator'), - ('loan_operator', 'Loan Operator', 'operator'), - ('full_operator', 'Full Operator (cards + loans)', 'operator'), - ('admin', 'Admin', 'admin'), - ('superadmin', 'Superadmin', 'admin'), - ('manager', 'Branch Manager', 'admin'), - ('currency_maintainer', 'Walyuta kursy operator', 'admin'); - -INSERT INTO permissions (code, name, guard_name, module) VALUES - -- admin-only sahalar - ('users.view', 'View users', 'admin', 'users'), - ('users.manage', 'Manage users', 'admin', 'users'), - ('roles.view', 'View roles', 'admin', 'roles'), - ('roles.manage', 'Manage roles', 'admin', 'roles'), - ('branches.view', 'View branches', 'admin', 'branches'), - ('branches.manage', 'Manage branches', 'admin', 'branches'), - ('provinces.view', 'View provinces', 'admin', 'provinces'), - ('provinces.manage', 'Manage provinces', 'admin', 'provinces'), - ('activity-logs.view', 'View activity logs', 'admin', 'activity-logs'), - ('backups.view', 'View backups', 'admin', 'backups'), - ('backups.manage', 'Manage backups', 'admin', 'backups'), - ('currencies.view', 'View currencies', 'admin', 'currencies'), - ('currencies.manage', 'Manage currencies', 'admin', 'currencies'), - ('payment-settings.view', 'View payment settings', 'admin', 'payment-settings'), - ('payment-settings.manage', 'Manage payment settings', 'admin', 'payment-settings'), - -- operator: two sahalar only - ('cards', 'Cards', 'operator', 'cards'), - ('loans', 'Loans', 'operator', 'loans'); - -INSERT INTO role_user (role_id, user_id) -SELECT r.id, u.id -FROM users u -JOIN roles r ON r.code = u.role; - -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_role (permission_id, role_id) -SELECT p.id, r.id -FROM permissions p -JOIN roles r ON r.code = 'manager' -WHERE p.code IN ('cards', 'loans'); - --- Operator role default: cards saha only. -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 = 'cards'; - --- loanop (user 12): loans saha only. -INSERT INTO permission_role (permission_id, role_id) -SELECT p.id, r.id -FROM permissions p -JOIN roles r ON r.code = 'loan_operator' -WHERE p.code = 'loans'; - --- bothop (user 13): cards + loans sahalary. -INSERT INTO permission_role (permission_id, role_id) -SELECT p.id, r.id -FROM permissions p -JOIN roles r ON r.code = 'full_operator' -WHERE p.code IN ('cards', 'loans'); - --- currency@bank.tm: diňe walýuta sahasy (admin guard, superadmin däl). -INSERT INTO permission_role (permission_id, role_id) -SELECT p.id, r.id -FROM permissions p -JOIN roles r ON r.code = 'currency_maintainer' -WHERE p.code IN ('currencies.view', 'currencies.manage'); - -- --------------------------------------------------------------------------- -- Provinces — name = etrap, region = welaýat (admin location list) -- --------------------------------------------------------------------------- @@ -720,8 +694,7 @@ COMMIT; -- Quick counts 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 'role_permissions', count(*) FROM role_permissions 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 0afbee9..7098bf2 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -22,7 +22,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Returns a paginated audit trail of user actions (create/update/delete). Each log includes the actor's username and role from role_user.", + "description": "Returns a paginated audit trail of user actions (create/update/delete). Each log includes the actor's username and role code.", "produces": [ "application/json" ], @@ -5118,109 +5118,6 @@ const docTemplate = `{ } } }, - "/permission-roles/bulk": { - "post": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Replaces roleId's whole permission set with permissionIds - pairs not listed are removed, missing ones are added, an empty list clears all permissions from the role", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "permission-roles" - ], - "summary": "Set a role's permissions", - "parameters": [ - { - "description": "Role + the permission IDs it should have", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/permissionrole.SetRolePermissionsDTO" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - } - }, - "/permission-roles/{id}": { - "delete": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Deletes a permission-role assignment", - "produces": [ - "application/json" - ], - "tags": [ - "permission-roles" - ], - "summary": "Remove permission from role", - "parameters": [ - { - "type": "integer", - "description": "Permission-role ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - } - }, "/permissions": { "get": { "security": [ @@ -5228,7 +5125,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Returns paginated permissions with optional filters", + "description": "Returns the permission catalog: one code per module, in display order. Holding a code grants read and write in that module; the role's scope decides which records.", "produces": [ "application/json" ], @@ -5236,310 +5133,12 @@ const docTemplate = `{ "permission" ], "summary": "List permissions", - "parameters": [ - { - "type": "string", - "description": "Filter by name", - "name": "permission_name", - "in": "query" - }, - { - "type": "string", - "description": "Filter by guard (web, operator, admin)", - "name": "guard_name", - "in": "query" - }, - { - "type": "string", - "description": "Filter by saha (cards, loans, …)", - "name": "module", - "in": "query" - }, - { - "type": "integer", - "default": 1, - "description": "Page number", - "name": "page", - "in": "query" - }, - { - "type": "integer", - "default": 10, - "description": "Items per page", - "name": "limit", - "in": "query" - } - ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/appresult.AppSuccess" } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - }, - "post": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Creates a new permission", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "permission" - ], - "summary": "Create permission", - "parameters": [ - { - "description": "Permission payload", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/permission.CreatePermissionDTO" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - } - }, - "/permissions/tree": { - "get": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Returns permissions grouped as guard → module (saha) → permissions", - "produces": [ - "application/json" - ], - "tags": [ - "permission" - ], - "summary": "Permission tree", - "parameters": [ - { - "type": "string", - "description": "Filter by guard (web, operator, admin)", - "name": "guard_name", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - } - }, - "/permissions/{id}": { - "get": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Returns a single permission", - "produces": [ - "application/json" - ], - "tags": [ - "permission" - ], - "summary": "Get permission by ID", - "parameters": [ - { - "type": "integer", - "description": "Permission ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - }, - "put": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Updates an existing permission", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "permission" - ], - "summary": "Update permission", - "parameters": [ - { - "type": "integer", - "description": "Permission ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "Permission payload", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/permission.UpdatePermissionDTO" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - }, - "delete": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Deletes a permission", - "produces": [ - "application/json" - ], - "tags": [ - "permission" - ], - "summary": "Delete permission", - "parameters": [ - { - "type": "integer", - "description": "Permission ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } } } } @@ -6290,109 +5889,6 @@ const docTemplate = `{ } } }, - "/role-users": { - "post": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Creates a role-user assignment, or updates the user's existing role if one is already assigned", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "role-users" - ], - "summary": "Assign user to role", - "parameters": [ - { - "description": "Role-user payload", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/roleusers.CreateRoleUserDTO" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - } - }, - "/role-users/{id}": { - "delete": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Deletes a role-user assignment", - "produces": [ - "application/json" - ], - "tags": [ - "role-users" - ], - "summary": "Remove user from role", - "parameters": [ - { - "type": "integer", - "description": "Role-user ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - } - }, "/roles": { "get": { "security": [ @@ -6411,7 +5907,7 @@ const docTemplate = `{ "parameters": [ { "type": "string", - "description": "Filter by name", + "description": "Filter by name or code", "name": "role_name", "in": "query" }, @@ -6457,7 +5953,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Creates a new role", + "description": "Creates a role with a scope (own, branch, all) and its permission codes. The caller cannot create a role wider than their own scope or holding permissions they lack.", "consumes": [ "application/json" ], @@ -6492,6 +5988,18 @@ const docTemplate = `{ "$ref": "#/definitions/appresult.AppError" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -6558,7 +6066,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Updates an existing role", + "description": "Replaces the role's name, scope and whole permission set. System roles keep their scope; the caller must be able to grant the role both before and after the change.", "consumes": [ "application/json" ], @@ -6600,6 +6108,12 @@ const docTemplate = `{ "$ref": "#/definitions/appresult.AppError" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "404": { "description": "Not Found", "schema": { @@ -6620,7 +6134,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Deletes a role", + "description": "Deletes a role. System roles and roles still assigned to users cannot be deleted.", "produces": [ "application/json" ], @@ -6650,12 +6164,24 @@ const docTemplate = `{ "$ref": "#/definitions/appresult.AppError" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "404": { "description": "Not Found", "schema": { "$ref": "#/definitions/appresult.AppError" } }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -6718,7 +6244,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Returns paginated users, including roleId. Admin-guard callers (admin, superadmin, and other admin-guard roles) see users of every role; branch-scoped operators see role=user only, scoped to their branches.", + "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.", "produces": [ "application/json" ], @@ -6781,7 +6307,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Creates a new 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.", "consumes": [ "application/json" ], @@ -6816,6 +6342,12 @@ const docTemplate = `{ "$ref": "#/definitions/appresult.AppError" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -7012,7 +6544,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Updates an existing 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.", "consumes": [ "application/json" ], @@ -7054,12 +6586,24 @@ const docTemplate = `{ "$ref": "#/definitions/appresult.AppError" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "404": { "description": "Not Found", "schema": { "$ref": "#/definitions/appresult.AppError" } }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -7074,7 +6618,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Deletes a user", + "description": "Deletes a user. Callers cannot delete themselves, a user whose role they could not grant, or the last superadmin.", "produces": [ "application/json" ], @@ -7104,12 +6648,100 @@ const docTemplate = `{ "$ref": "#/definitions/appresult.AppError" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "404": { "description": "Not Found", "schema": { "$ref": "#/definitions/appresult.AppError" } }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/users/{id}/role": { + "put": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Gives the user exactly one role. Same rules as create/update.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Set user role", + "parameters": [ + { + "type": "integer", + "description": "User ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Role", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/user.SetUserRoleDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -9633,79 +9265,34 @@ const docTemplate = `{ } } }, - "permission.CreatePermissionDTO": { - "type": "object", - "required": [ - "code", - "guardName", - "module", - "name" + "perm.Code": { + "type": "string", + "enum": [ + "dashboard", + "cards", + "loans", + "users", + "roles", + "branches", + "provinces", + "currencies", + "payment-settings", + "backups", + "activity-logs" ], - "properties": { - "code": { - "type": "string" - }, - "guardName": { - "type": "string", - "enum": [ - "web", - "operator", - "admin" - ] - }, - "module": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "permission.UpdatePermissionDTO": { - "type": "object", - "required": [ - "code", - "guardName", - "module", - "name" - ], - "properties": { - "code": { - "type": "string" - }, - "guardName": { - "type": "string", - "enum": [ - "web", - "operator", - "admin" - ] - }, - "module": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "permissionrole.SetRolePermissionsDTO": { - "type": "object", - "required": [ - "permissionIds", - "roleId" - ], - "properties": { - "permissionIds": { - "type": "array", - "items": { - "type": "integer" - } - }, - "roleId": { - "type": "integer" - } - } + "x-enum-varnames": [ + "Dashboard", + "Cards", + "Loans", + "Users", + "Roles", + "Branches", + "Provinces", + "Currencies", + "PaymentSettings", + "Backups", + "ActivityLogs" + ] }, "province.CreateProvinceDTO": { "type": "object", @@ -9757,6 +9344,29 @@ const docTemplate = `{ } } }, + "rbac.Scope": { + "type": "string", + "enum": [ + "own", + "branch", + "all" + ], + "x-enum-comments": { + "ScopeAll": "every branch", + "ScopeBranch": "records of the caller's branch_user branches", + "ScopeOwn": "only records the caller owns (clients)" + }, + "x-enum-descriptions": [ + "only records the caller owns (clients)", + "records of the caller's branch_user branches", + "every branch" + ], + "x-enum-varnames": [ + "ScopeOwn", + "ScopeBranch", + "ScopeAll" + ] + }, "reasonscard.CreateReasonCardDTO": { "type": "object", "required": [ @@ -9803,62 +9413,66 @@ const docTemplate = `{ "type": "object", "required": [ "code", - "guardName", - "name" + "name", + "permissions", + "scope" ], "properties": { "code": { - "type": "string" - }, - "guardName": { "type": "string", - "enum": [ - "web", - "operator", - "admin" - ] + "maxLength": 64 }, "name": { "type": "string" + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/definitions/perm.Code" + } + }, + "scope": { + "enum": [ + "own", + "branch", + "all" + ], + "allOf": [ + { + "$ref": "#/definitions/rbac.Scope" + } + ] } } }, "role.UpdateRoleDTO": { "type": "object", "required": [ - "code", - "guardName", - "name" + "name", + "permissions", + "scope" ], "properties": { - "code": { - "type": "string" - }, - "guardName": { - "type": "string", - "enum": [ - "web", - "operator", - "admin" - ] - }, "name": { "type": "string" - } - } - }, - "roleusers.CreateRoleUserDTO": { - "type": "object", - "required": [ - "roleId", - "userId" - ], - "properties": { - "roleId": { - "type": "integer" }, - "userId": { - "type": "integer" + "permissions": { + "type": "array", + "items": { + "$ref": "#/definitions/perm.Code" + } + }, + "scope": { + "enum": [ + "own", + "branch", + "all" + ], + "allOf": [ + { + "$ref": "#/definitions/rbac.Scope" + } + ] } } }, @@ -9910,13 +9524,28 @@ const docTemplate = `{ "type": "string" }, "role": { + "description": "Role is a role code; RoleId wins when both are sent. Neither → \"user\".", "type": "string" }, + "roleId": { + "type": "integer" + }, "username": { "type": "string" } } }, + "user.SetUserRoleDTO": { + "type": "object", + "required": [ + "roleId" + ], + "properties": { + "roleId": { + "type": "integer" + } + } + }, "user.UpdateUserDTO": { "type": "object", "required": [ @@ -9947,8 +9576,12 @@ const docTemplate = `{ "type": "string" }, "role": { + "description": "Role is a role code; RoleId wins when both are sent. Neither keeps\nthe user's current role.", "type": "string" }, + "roleId": { + "type": "integer" + }, "username": { "type": "string" } diff --git a/docs/swagger.json b/docs/swagger.json index 3a7689a..5b5debe 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -16,7 +16,7 @@ "BearerAuth": [] } ], - "description": "Returns a paginated audit trail of user actions (create/update/delete). Each log includes the actor's username and role from role_user.", + "description": "Returns a paginated audit trail of user actions (create/update/delete). Each log includes the actor's username and role code.", "produces": [ "application/json" ], @@ -5112,109 +5112,6 @@ } } }, - "/permission-roles/bulk": { - "post": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Replaces roleId's whole permission set with permissionIds - pairs not listed are removed, missing ones are added, an empty list clears all permissions from the role", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "permission-roles" - ], - "summary": "Set a role's permissions", - "parameters": [ - { - "description": "Role + the permission IDs it should have", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/permissionrole.SetRolePermissionsDTO" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - } - }, - "/permission-roles/{id}": { - "delete": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Deletes a permission-role assignment", - "produces": [ - "application/json" - ], - "tags": [ - "permission-roles" - ], - "summary": "Remove permission from role", - "parameters": [ - { - "type": "integer", - "description": "Permission-role ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - } - }, "/permissions": { "get": { "security": [ @@ -5222,7 +5119,7 @@ "BearerAuth": [] } ], - "description": "Returns paginated permissions with optional filters", + "description": "Returns the permission catalog: one code per module, in display order. Holding a code grants read and write in that module; the role's scope decides which records.", "produces": [ "application/json" ], @@ -5230,310 +5127,12 @@ "permission" ], "summary": "List permissions", - "parameters": [ - { - "type": "string", - "description": "Filter by name", - "name": "permission_name", - "in": "query" - }, - { - "type": "string", - "description": "Filter by guard (web, operator, admin)", - "name": "guard_name", - "in": "query" - }, - { - "type": "string", - "description": "Filter by saha (cards, loans, …)", - "name": "module", - "in": "query" - }, - { - "type": "integer", - "default": 1, - "description": "Page number", - "name": "page", - "in": "query" - }, - { - "type": "integer", - "default": 10, - "description": "Items per page", - "name": "limit", - "in": "query" - } - ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/appresult.AppSuccess" } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - }, - "post": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Creates a new permission", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "permission" - ], - "summary": "Create permission", - "parameters": [ - { - "description": "Permission payload", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/permission.CreatePermissionDTO" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - } - }, - "/permissions/tree": { - "get": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Returns permissions grouped as guard → module (saha) → permissions", - "produces": [ - "application/json" - ], - "tags": [ - "permission" - ], - "summary": "Permission tree", - "parameters": [ - { - "type": "string", - "description": "Filter by guard (web, operator, admin)", - "name": "guard_name", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - } - }, - "/permissions/{id}": { - "get": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Returns a single permission", - "produces": [ - "application/json" - ], - "tags": [ - "permission" - ], - "summary": "Get permission by ID", - "parameters": [ - { - "type": "integer", - "description": "Permission ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - }, - "put": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Updates an existing permission", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "permission" - ], - "summary": "Update permission", - "parameters": [ - { - "type": "integer", - "description": "Permission ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "Permission payload", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/permission.UpdatePermissionDTO" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - }, - "delete": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Deletes a permission", - "produces": [ - "application/json" - ], - "tags": [ - "permission" - ], - "summary": "Delete permission", - "parameters": [ - { - "type": "integer", - "description": "Permission ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } } } } @@ -6284,109 +5883,6 @@ } } }, - "/role-users": { - "post": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Creates a role-user assignment, or updates the user's existing role if one is already assigned", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "role-users" - ], - "summary": "Assign user to role", - "parameters": [ - { - "description": "Role-user payload", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/roleusers.CreateRoleUserDTO" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - } - }, - "/role-users/{id}": { - "delete": { - "security": [ - { - "BearerAuth": [] - } - ], - "description": "Deletes a role-user assignment", - "produces": [ - "application/json" - ], - "tags": [ - "role-users" - ], - "summary": "Remove user from role", - "parameters": [ - { - "type": "integer", - "description": "Role-user ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/appresult.AppSuccess" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/appresult.AppError" - } - } - } - } - }, "/roles": { "get": { "security": [ @@ -6405,7 +5901,7 @@ "parameters": [ { "type": "string", - "description": "Filter by name", + "description": "Filter by name or code", "name": "role_name", "in": "query" }, @@ -6451,7 +5947,7 @@ "BearerAuth": [] } ], - "description": "Creates a new role", + "description": "Creates a role with a scope (own, branch, all) and its permission codes. The caller cannot create a role wider than their own scope or holding permissions they lack.", "consumes": [ "application/json" ], @@ -6486,6 +5982,18 @@ "$ref": "#/definitions/appresult.AppError" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -6552,7 +6060,7 @@ "BearerAuth": [] } ], - "description": "Updates an existing role", + "description": "Replaces the role's name, scope and whole permission set. System roles keep their scope; the caller must be able to grant the role both before and after the change.", "consumes": [ "application/json" ], @@ -6594,6 +6102,12 @@ "$ref": "#/definitions/appresult.AppError" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "404": { "description": "Not Found", "schema": { @@ -6614,7 +6128,7 @@ "BearerAuth": [] } ], - "description": "Deletes a role", + "description": "Deletes a role. System roles and roles still assigned to users cannot be deleted.", "produces": [ "application/json" ], @@ -6644,12 +6158,24 @@ "$ref": "#/definitions/appresult.AppError" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "404": { "description": "Not Found", "schema": { "$ref": "#/definitions/appresult.AppError" } }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -6712,7 +6238,7 @@ "BearerAuth": [] } ], - "description": "Returns paginated users, including roleId. Admin-guard callers (admin, superadmin, and other admin-guard roles) see users of every role; branch-scoped operators see role=user only, scoped to their branches.", + "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.", "produces": [ "application/json" ], @@ -6775,7 +6301,7 @@ "BearerAuth": [] } ], - "description": "Creates a new 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.", "consumes": [ "application/json" ], @@ -6810,6 +6336,12 @@ "$ref": "#/definitions/appresult.AppError" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -7006,7 +6538,7 @@ "BearerAuth": [] } ], - "description": "Updates an existing 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.", "consumes": [ "application/json" ], @@ -7048,12 +6580,24 @@ "$ref": "#/definitions/appresult.AppError" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "404": { "description": "Not Found", "schema": { "$ref": "#/definitions/appresult.AppError" } }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -7068,7 +6612,7 @@ "BearerAuth": [] } ], - "description": "Deletes a user", + "description": "Deletes a user. Callers cannot delete themselves, a user whose role they could not grant, or the last superadmin.", "produces": [ "application/json" ], @@ -7098,12 +6642,100 @@ "$ref": "#/definitions/appresult.AppError" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "404": { "description": "Not Found", "schema": { "$ref": "#/definitions/appresult.AppError" } }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/users/{id}/role": { + "put": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Gives the user exactly one role. Same rules as create/update.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Set user role", + "parameters": [ + { + "type": "integer", + "description": "User ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Role", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/user.SetUserRoleDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -9627,79 +9259,34 @@ } } }, - "permission.CreatePermissionDTO": { - "type": "object", - "required": [ - "code", - "guardName", - "module", - "name" + "perm.Code": { + "type": "string", + "enum": [ + "dashboard", + "cards", + "loans", + "users", + "roles", + "branches", + "provinces", + "currencies", + "payment-settings", + "backups", + "activity-logs" ], - "properties": { - "code": { - "type": "string" - }, - "guardName": { - "type": "string", - "enum": [ - "web", - "operator", - "admin" - ] - }, - "module": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "permission.UpdatePermissionDTO": { - "type": "object", - "required": [ - "code", - "guardName", - "module", - "name" - ], - "properties": { - "code": { - "type": "string" - }, - "guardName": { - "type": "string", - "enum": [ - "web", - "operator", - "admin" - ] - }, - "module": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "permissionrole.SetRolePermissionsDTO": { - "type": "object", - "required": [ - "permissionIds", - "roleId" - ], - "properties": { - "permissionIds": { - "type": "array", - "items": { - "type": "integer" - } - }, - "roleId": { - "type": "integer" - } - } + "x-enum-varnames": [ + "Dashboard", + "Cards", + "Loans", + "Users", + "Roles", + "Branches", + "Provinces", + "Currencies", + "PaymentSettings", + "Backups", + "ActivityLogs" + ] }, "province.CreateProvinceDTO": { "type": "object", @@ -9751,6 +9338,29 @@ } } }, + "rbac.Scope": { + "type": "string", + "enum": [ + "own", + "branch", + "all" + ], + "x-enum-comments": { + "ScopeAll": "every branch", + "ScopeBranch": "records of the caller's branch_user branches", + "ScopeOwn": "only records the caller owns (clients)" + }, + "x-enum-descriptions": [ + "only records the caller owns (clients)", + "records of the caller's branch_user branches", + "every branch" + ], + "x-enum-varnames": [ + "ScopeOwn", + "ScopeBranch", + "ScopeAll" + ] + }, "reasonscard.CreateReasonCardDTO": { "type": "object", "required": [ @@ -9797,62 +9407,66 @@ "type": "object", "required": [ "code", - "guardName", - "name" + "name", + "permissions", + "scope" ], "properties": { "code": { - "type": "string" - }, - "guardName": { "type": "string", - "enum": [ - "web", - "operator", - "admin" - ] + "maxLength": 64 }, "name": { "type": "string" + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/definitions/perm.Code" + } + }, + "scope": { + "enum": [ + "own", + "branch", + "all" + ], + "allOf": [ + { + "$ref": "#/definitions/rbac.Scope" + } + ] } } }, "role.UpdateRoleDTO": { "type": "object", "required": [ - "code", - "guardName", - "name" + "name", + "permissions", + "scope" ], "properties": { - "code": { - "type": "string" - }, - "guardName": { - "type": "string", - "enum": [ - "web", - "operator", - "admin" - ] - }, "name": { "type": "string" - } - } - }, - "roleusers.CreateRoleUserDTO": { - "type": "object", - "required": [ - "roleId", - "userId" - ], - "properties": { - "roleId": { - "type": "integer" }, - "userId": { - "type": "integer" + "permissions": { + "type": "array", + "items": { + "$ref": "#/definitions/perm.Code" + } + }, + "scope": { + "enum": [ + "own", + "branch", + "all" + ], + "allOf": [ + { + "$ref": "#/definitions/rbac.Scope" + } + ] } } }, @@ -9904,13 +9518,28 @@ "type": "string" }, "role": { + "description": "Role is a role code; RoleId wins when both are sent. Neither → \"user\".", "type": "string" }, + "roleId": { + "type": "integer" + }, "username": { "type": "string" } } }, + "user.SetUserRoleDTO": { + "type": "object", + "required": [ + "roleId" + ], + "properties": { + "roleId": { + "type": "integer" + } + } + }, "user.UpdateUserDTO": { "type": "object", "required": [ @@ -9941,8 +9570,12 @@ "type": "string" }, "role": { + "description": "Role is a role code; RoleId wins when both are sent. Neither keeps\nthe user's current role.", "type": "string" }, + "roleId": { + "type": "integer" + }, "username": { "type": "string" } diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 5468a14..c4caa33 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1400,58 +1400,32 @@ definitions: - sberBankFeeTmt - tvebFeeUsd type: object - permission.CreatePermissionDTO: - properties: - code: - type: string - guardName: - enum: - - web - - operator - - admin - type: string - module: - type: string - name: - type: string - required: - - code - - guardName - - module - - name - type: object - permission.UpdatePermissionDTO: - properties: - code: - type: string - guardName: - enum: - - web - - operator - - admin - type: string - module: - type: string - name: - type: string - required: - - code - - guardName - - module - - name - type: object - permissionrole.SetRolePermissionsDTO: - properties: - permissionIds: - items: - type: integer - type: array - roleId: - type: integer - required: - - permissionIds - - roleId - type: object + perm.Code: + enum: + - dashboard + - cards + - loans + - users + - roles + - branches + - provinces + - currencies + - payment-settings + - backups + - activity-logs + type: string + x-enum-varnames: + - Dashboard + - Cards + - Loans + - Users + - Roles + - Branches + - Provinces + - Currencies + - PaymentSettings + - Backups + - ActivityLogs province.CreateProvinceDTO: properties: active: @@ -1485,6 +1459,24 @@ definitions: - name - region type: object + rbac.Scope: + enum: + - own + - branch + - all + type: string + x-enum-comments: + ScopeAll: every branch + ScopeBranch: records of the caller's branch_user branches + ScopeOwn: only records the caller owns (clients) + x-enum-descriptions: + - only records the caller owns (clients) + - records of the caller's branch_user branches + - every branch + x-enum-varnames: + - ScopeOwn + - ScopeBranch + - ScopeAll reasonscard.CreateReasonCardDTO: properties: active: @@ -1516,46 +1508,46 @@ definitions: role.CreateRoleDTO: properties: code: - type: string - guardName: - enum: - - web - - operator - - admin + maxLength: 64 type: string name: type: string + permissions: + items: + $ref: '#/definitions/perm.Code' + type: array + scope: + allOf: + - $ref: '#/definitions/rbac.Scope' + enum: + - own + - branch + - all required: - code - - guardName - name + - permissions + - scope type: object role.UpdateRoleDTO: properties: - code: - type: string - guardName: - enum: - - web - - operator - - admin - type: string name: type: string + permissions: + items: + $ref: '#/definitions/perm.Code' + type: array + scope: + allOf: + - $ref: '#/definitions/rbac.Scope' + enum: + - own + - branch + - all required: - - code - - guardName - name - type: object - roleusers.CreateRoleUserDTO: - properties: - roleId: - type: integer - userId: - type: integer - required: - - roleId - - userId + - permissions + - scope type: object shared.LocalizedText: properties: @@ -1585,7 +1577,11 @@ definitions: phone: type: string role: + description: Role is a role code; RoleId wins when both are sent. Neither + → "user". type: string + roleId: + type: integer username: type: string required: @@ -1594,6 +1590,13 @@ definitions: - password - username type: object + user.SetUserRoleDTO: + properties: + roleId: + type: integer + required: + - roleId + type: object user.UpdateUserDTO: properties: active: @@ -1611,7 +1614,12 @@ definitions: phone: type: string role: + description: |- + Role is a role code; RoleId wins when both are sent. Neither keeps + the user's current role. type: string + roleId: + type: integer username: type: string required: @@ -1857,7 +1865,7 @@ paths: /activity-logs: get: description: Returns a paginated audit trail of user actions (create/update/delete). - Each log includes the actor's username and role from role_user. + Each log includes the actor's username and role code. parameters: - description: Filter by user ID in: query @@ -5135,99 +5143,11 @@ paths: summary: Update payment settings tags: - payment-settings - /permission-roles/{id}: - delete: - description: Deletes a permission-role assignment - parameters: - - description: Permission-role ID - in: path - name: id - required: true - type: integer - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/appresult.AppSuccess' - "400": - description: Bad Request - schema: - $ref: '#/definitions/appresult.AppError' - "404": - description: Not Found - schema: - $ref: '#/definitions/appresult.AppError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/appresult.AppError' - security: - - BearerAuth: [] - summary: Remove permission from role - tags: - - permission-roles - /permission-roles/bulk: - post: - consumes: - - application/json - description: Replaces roleId's whole permission set with permissionIds - pairs - not listed are removed, missing ones are added, an empty list clears all permissions - from the role - parameters: - - description: Role + the permission IDs it should have - in: body - name: body - required: true - schema: - $ref: '#/definitions/permissionrole.SetRolePermissionsDTO' - produces: - - application/json - responses: - "201": - description: Created - schema: - $ref: '#/definitions/appresult.AppSuccess' - "400": - description: Bad Request - schema: - $ref: '#/definitions/appresult.AppError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/appresult.AppError' - security: - - BearerAuth: [] - summary: Set a role's permissions - tags: - - permission-roles /permissions: get: - description: Returns paginated permissions with optional filters - parameters: - - description: Filter by name - in: query - name: permission_name - type: string - - description: Filter by guard (web, operator, admin) - in: query - name: guard_name - type: string - - description: Filter by saha (cards, loans, …) - in: query - name: module - type: string - - default: 1 - description: Page number - in: query - name: page - type: integer - - default: 10 - description: Items per page - in: query - name: limit - type: integer + description: 'Returns the permission catalog: one code per module, in display + order. Holding a code grants read and write in that module; the role''s scope + decides which records.' produces: - application/json responses: @@ -5235,179 +5155,11 @@ paths: description: OK schema: $ref: '#/definitions/appresult.AppSuccess' - "400": - description: Bad Request - schema: - $ref: '#/definitions/appresult.AppError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/appresult.AppError' security: - BearerAuth: [] summary: List permissions tags: - permission - post: - consumes: - - application/json - description: Creates a new permission - parameters: - - description: Permission payload - in: body - name: body - required: true - schema: - $ref: '#/definitions/permission.CreatePermissionDTO' - produces: - - application/json - responses: - "201": - description: Created - schema: - $ref: '#/definitions/appresult.AppSuccess' - "400": - description: Bad Request - schema: - $ref: '#/definitions/appresult.AppError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/appresult.AppError' - security: - - BearerAuth: [] - summary: Create permission - tags: - - permission - /permissions/{id}: - delete: - description: Deletes a permission - parameters: - - description: Permission ID - in: path - name: id - required: true - type: integer - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/appresult.AppSuccess' - "400": - description: Bad Request - schema: - $ref: '#/definitions/appresult.AppError' - "404": - description: Not Found - schema: - $ref: '#/definitions/appresult.AppError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/appresult.AppError' - security: - - BearerAuth: [] - summary: Delete permission - tags: - - permission - get: - description: Returns a single permission - parameters: - - description: Permission ID - in: path - name: id - required: true - type: integer - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/appresult.AppSuccess' - "400": - description: Bad Request - schema: - $ref: '#/definitions/appresult.AppError' - "404": - description: Not Found - schema: - $ref: '#/definitions/appresult.AppError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/appresult.AppError' - security: - - BearerAuth: [] - summary: Get permission by ID - tags: - - permission - put: - consumes: - - application/json - description: Updates an existing permission - parameters: - - description: Permission ID - in: path - name: id - required: true - type: integer - - description: Permission payload - in: body - name: body - required: true - schema: - $ref: '#/definitions/permission.UpdatePermissionDTO' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/appresult.AppSuccess' - "400": - description: Bad Request - schema: - $ref: '#/definitions/appresult.AppError' - "404": - description: Not Found - schema: - $ref: '#/definitions/appresult.AppError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/appresult.AppError' - security: - - BearerAuth: [] - summary: Update permission - tags: - - permission - /permissions/tree: - get: - description: Returns permissions grouped as guard → module (saha) → permissions - parameters: - - description: Filter by guard (web, operator, admin) - in: query - name: guard_name - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/appresult.AppSuccess' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/appresult.AppError' - security: - - BearerAuth: [] - summary: Permission tree - tags: - - permission /profile: get: description: Returns the authenticated user's profile with role, branches, and @@ -5888,77 +5640,11 @@ paths: summary: Verify phone tags: - auth - /role-users: - post: - consumes: - - application/json - description: Creates a role-user assignment, or updates the user's existing - role if one is already assigned - parameters: - - description: Role-user payload - in: body - name: body - required: true - schema: - $ref: '#/definitions/roleusers.CreateRoleUserDTO' - produces: - - application/json - responses: - "201": - description: Created - schema: - $ref: '#/definitions/appresult.AppSuccess' - "400": - description: Bad Request - schema: - $ref: '#/definitions/appresult.AppError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/appresult.AppError' - security: - - BearerAuth: [] - summary: Assign user to role - tags: - - role-users - /role-users/{id}: - delete: - description: Deletes a role-user assignment - parameters: - - description: Role-user ID - in: path - name: id - required: true - type: integer - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/appresult.AppSuccess' - "400": - description: Bad Request - schema: - $ref: '#/definitions/appresult.AppError' - "404": - description: Not Found - schema: - $ref: '#/definitions/appresult.AppError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/appresult.AppError' - security: - - BearerAuth: [] - summary: Remove user from role - tags: - - role-users /roles: get: description: Returns paginated roles with optional filters parameters: - - description: Filter by name + - description: Filter by name or code in: query name: role_name type: string @@ -5995,7 +5681,9 @@ paths: post: consumes: - application/json - description: Creates a new role + description: Creates a role with a scope (own, branch, all) and its permission + codes. The caller cannot create a role wider than their own scope or holding + permissions they lack. parameters: - description: Role payload in: body @@ -6014,6 +5702,14 @@ paths: description: Bad Request schema: $ref: '#/definitions/appresult.AppError' + "403": + description: Forbidden + schema: + $ref: '#/definitions/appresult.AppError' + "409": + description: Conflict + schema: + $ref: '#/definitions/appresult.AppError' "500": description: Internal Server Error schema: @@ -6025,7 +5721,8 @@ paths: - role /roles/{id}: delete: - description: Deletes a role + description: Deletes a role. System roles and roles still assigned to users + cannot be deleted. parameters: - description: Role ID in: path @@ -6043,10 +5740,18 @@ paths: description: Bad Request schema: $ref: '#/definitions/appresult.AppError' + "403": + description: Forbidden + schema: + $ref: '#/definitions/appresult.AppError' "404": description: Not Found schema: $ref: '#/definitions/appresult.AppError' + "409": + description: Conflict + schema: + $ref: '#/definitions/appresult.AppError' "500": description: Internal Server Error schema: @@ -6091,7 +5796,9 @@ paths: put: consumes: - application/json - description: Updates an existing role + description: Replaces the role's name, scope and whole permission set. System + roles keep their scope; the caller must be able to grant the role both before + and after the change. parameters: - description: Role ID in: path @@ -6115,6 +5822,10 @@ paths: description: Bad Request schema: $ref: '#/definitions/appresult.AppError' + "403": + description: Forbidden + schema: + $ref: '#/definitions/appresult.AppError' "404": description: Not Found schema: @@ -6160,9 +5871,9 @@ paths: - auth /users: get: - description: Returns paginated users, including roleId. Admin-guard callers - (admin, superadmin, and other admin-guard roles) see users of every role; - branch-scoped operators see role=user only, scoped to their branches. + 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. parameters: - description: Search by username, first name, or last name in: query @@ -6205,7 +5916,9 @@ paths: post: consumes: - application/json - description: Creates a new 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.' parameters: - description: User payload in: body @@ -6224,6 +5937,10 @@ paths: description: Bad Request schema: $ref: '#/definitions/appresult.AppError' + "403": + description: Forbidden + schema: + $ref: '#/definitions/appresult.AppError' "500": description: Internal Server Error schema: @@ -6235,7 +5952,8 @@ paths: - user /users/{id}: delete: - description: Deletes a user + description: Deletes a user. Callers cannot delete themselves, a user whose + role they could not grant, or the last superadmin. parameters: - description: User ID in: path @@ -6253,10 +5971,18 @@ paths: description: Bad Request schema: $ref: '#/definitions/appresult.AppError' + "403": + description: Forbidden + schema: + $ref: '#/definitions/appresult.AppError' "404": description: Not Found schema: $ref: '#/definitions/appresult.AppError' + "409": + description: Conflict + schema: + $ref: '#/definitions/appresult.AppError' "500": description: Internal Server Error schema: @@ -6302,7 +6028,9 @@ paths: put: consumes: - application/json - description: Updates an existing 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. parameters: - description: User ID in: path @@ -6326,10 +6054,18 @@ paths: description: Bad Request schema: $ref: '#/definitions/appresult.AppError' + "403": + description: Forbidden + schema: + $ref: '#/definitions/appresult.AppError' "404": description: Not Found schema: $ref: '#/definitions/appresult.AppError' + "409": + description: Conflict + schema: + $ref: '#/definitions/appresult.AppError' "500": description: Internal Server Error schema: @@ -6339,6 +6075,55 @@ paths: summary: Update user tags: - user + /users/{id}/role: + put: + consumes: + - application/json + description: Gives the user exactly one role. Same rules as create/update. + parameters: + - description: User ID + in: path + name: id + required: true + type: integer + - description: Role + in: body + name: body + required: true + schema: + $ref: '#/definitions/user.SetUserRoleDTO' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "403": + description: Forbidden + schema: + $ref: '#/definitions/appresult.AppError' + "404": + description: Not Found + schema: + $ref: '#/definitions/appresult.AppError' + "409": + description: Conflict + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: Set user role + tags: + - user /users/clients: get: description: Returns paginated client users (role user, not assigned to any diff --git a/docs/tag_order.go b/docs/tag_order.go index a0f494d..e239bdd 100644 --- a/docs/tag_order.go +++ b/docs/tag_order.go @@ -13,9 +13,7 @@ var swaggerTagOrder = []struct { {Name: "branch-users", Description: "Branch users"}, {Name: "user", Description: "Users"}, {Name: "role", Description: "Roles"}, - {Name: "role-users", Description: "Role users"}, {Name: "permission", Description: "Permissions"}, - {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 a053239..20165b8 100755 --- a/internal/appresult/error.go +++ b/internal/appresult/error.go @@ -13,6 +13,10 @@ var ( ErrInvalidCode = NewAppError(nil, "Invalid or expired verification code.", "SE-00009") ErrPasswordMismatch = NewAppError(nil, "Password confirmation does not match.", "SE-00010") ErrDuplicate = NewAppError(nil, "A record with these values already exists.", "SE-00012") + ErrRoleInUse = NewAppError(nil, "The role is still assigned to users.", "SE-00013") + ErrLastSuperadmin = NewAppError(nil, "The last superadmin cannot be removed or demoted.", "SE-00014") + ErrUnknownRole = NewAppError(nil, "Role not found.", "SE-00015") + ErrSystemRole = NewAppError(nil, "System roles cannot be deleted or have their scope changed.", "SE-00016") ) type AppError struct { diff --git a/internal/backup/handler.go b/internal/backup/handler.go index 6d72852..b79d959 100644 --- a/internal/backup/handler.go +++ b/internal/backup/handler.go @@ -7,6 +7,8 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -26,7 +28,7 @@ func NewHandler(logger *logging.Logger, service *Service) handlers.Handler { } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Backups)) group.GET("", h.list) group.POST("", h.create) group.GET("/:id/download", h.download) diff --git a/internal/cards/cardbalance/handler.go b/internal/cards/cardbalance/handler.go index eb6ac0a..d322ae5 100644 --- a/internal/cards/cardbalance/handler.go +++ b/internal/cards/cardbalance/handler.go @@ -7,6 +7,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Require(perm.Cards)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) diff --git a/internal/cards/cardorder/handler.go b/internal/cards/cardorder/handler.go index cb41ee5..e8de076 100644 --- a/internal/cards/cardorder/handler.go +++ b/internal/cards/cardorder/handler.go @@ -7,6 +7,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Require(perm.Cards)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) diff --git a/internal/cards/cardpinorders/handler.go b/internal/cards/cardpinorders/handler.go index 9e63760..866d049 100644 --- a/internal/cards/cardpinorders/handler.go +++ b/internal/cards/cardpinorders/handler.go @@ -7,6 +7,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Require(perm.Cards)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) diff --git a/internal/cards/cardrekwizit/handler.go b/internal/cards/cardrekwizit/handler.go index 51d1a7d..44caaa1 100644 --- a/internal/cards/cardrekwizit/handler.go +++ b/internal/cards/cardrekwizit/handler.go @@ -7,6 +7,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Require(perm.Cards)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) diff --git a/internal/cards/cards/handler.go b/internal/cards/cards/handler.go index 162fe24..3cd2e1d 100644 --- a/internal/cards/cards/handler.go +++ b/internal/cards/cards/handler.go @@ -7,6 +7,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Require(perm.Cards)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) diff --git a/internal/cards/paymentcard/handler.go b/internal/cards/paymentcard/handler.go index 9217a76..1627e89 100644 --- a/internal/cards/paymentcard/handler.go +++ b/internal/cards/paymentcard/handler.go @@ -7,6 +7,8 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -26,7 +28,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Catalog(perm.Cards)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) diff --git a/internal/cards/reasonscard/handler.go b/internal/cards/reasonscard/handler.go index 24b5352..5ef4238 100644 --- a/internal/cards/reasonscard/handler.go +++ b/internal/cards/reasonscard/handler.go @@ -6,6 +6,8 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -25,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Catalog(perm.Cards)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) diff --git a/internal/cards/visamaster/handler.go b/internal/cards/visamaster/handler.go index 6b5a881..12ed2b0 100644 --- a/internal/cards/visamaster/handler.go +++ b/internal/cards/visamaster/handler.go @@ -7,6 +7,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Require(perm.Cards)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) diff --git a/internal/currency/handler.go b/internal/currency/handler.go index 77b3829..4a2a6db 100644 --- a/internal/currency/handler.go +++ b/internal/currency/handler.go @@ -8,6 +8,8 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -27,7 +29,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Catalog(perm.Currencies)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) diff --git a/internal/dashboard/db/postgresql.go b/internal/dashboard/db/postgresql.go index ae8bba5..c7e96e7 100644 --- a/internal/dashboard/db/postgresql.go +++ b/internal/dashboard/db/postgresql.go @@ -153,7 +153,7 @@ func (r *repository) activeCardsMetric(ctx context.Context, branchIds []int64, w } func (r *repository) activeCustomersMetric(ctx context.Context, branchIds []int64, win periodWindow) (dashboard.StatMetricDTO, error) { - where := " AND u.role = 'user' AND u.active = true" + where := " AND u.role_id = (SELECT id FROM roles WHERE code = 'user' AND deleted_at IS NULL) AND u.active = true" var extra []interface{} if len(branchIds) > 0 { extra = append(extra, branchIds) diff --git a/internal/dashboard/handler.go b/internal/dashboard/handler.go index 60ac223..a294e3b 100644 --- a/internal/dashboard/handler.go +++ b/internal/dashboard/handler.go @@ -8,6 +8,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/pkg/logging" "github.com/gin-gonic/gin" @@ -30,7 +31,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Dashboard)) group.GET("/overview", h.overview) } @@ -59,6 +60,7 @@ func (h *handler) overview(c *gin.Context) { c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } + redactByPermission(&result, rbac.Can(c, perm.Cards), rbac.Can(c, perm.Loans)) c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } @@ -91,3 +93,33 @@ func parseOverviewFilter(c *gin.Context) (OverviewFilter, bool) { rbac.BindBranchIDs(c, &filter.BranchIds) return filter, true } + +// redactByPermission blanks the widgets of modules the caller cannot open, so +// e.g. a head of loans sees every branch's loan numbers but no card numbers. +func redactByPermission(o *OverviewDTO, cards, loans bool) { + if !cards { + o.Stats.ActiveCards = StatMetricDTO{} + o.Stats.OnlinePayments = StatMetricDTO{} + } + if !loans { + o.Stats.LoanOrders = StatMetricDTO{} + o.LoanStatus = []LoanStatusShareDTO{} + o.RecentActivity = []RecentActivityDTO{} + } + for i := range o.Trend.Points { + if !cards { + o.Trend.Points[i].Cards = 0 + } + if !loans { + o.Trend.Points[i].Loans = 0 + } + } + for i := range o.WeeklyOrders { + if !cards { + o.WeeklyOrders[i].Cards = 0 + } + if !loans { + o.WeeklyOrders[i].Loans = 0 + } + } +} diff --git a/internal/handlers/manager/manager.go b/internal/handlers/manager/manager.go index cc890a2..b81f086 100755 --- a/internal/handlers/manager/manager.go +++ b/internal/handlers/manager/manager.go @@ -1,6 +1,7 @@ package handlermanager import ( + "context" "net/http" "path/filepath" @@ -16,6 +17,7 @@ import ( "online-back/internal/identity/activitylog" activitylogdb "online-back/internal/identity/activitylog/db" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/lending" "online-back/internal/org" "online-back/internal/payment" @@ -62,6 +64,9 @@ 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)) + if err := perm.Sync(context.Background(), client); err != nil { + logger.Fatalf("rbac: sync permission catalog: %v", err) + } adminGroup.Use(rbac.Guard(rbac.NewService(client))) // Each bounded context registers its own modules' handlers. @@ -84,6 +89,11 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin. ) backup.NewHandler(logger, backupSvc).Register(adminGroup) + // Deny by default: every admin route must declare its policy via rbac.Group. + if err := rbac.VerifyRoutes(router.Routes(), adminAPIPrefix); err != nil { + logger.Fatal(err) + } + return router } diff --git a/internal/identity/activitylog/db/postgresql.go b/internal/identity/activitylog/db/postgresql.go index 53141cb..c31d040 100644 --- a/internal/identity/activitylog/db/postgresql.go +++ b/internal/identity/activitylog/db/postgresql.go @@ -31,14 +31,7 @@ var activityLogColumnsSQL = strings.Join(activityLogColumns, ", ") const activityLogFromClause = ` FROM activity_logs al LEFT JOIN users u ON u.id = al.user_id -LEFT JOIN LATERAL ( - SELECT ru.role_id - FROM role_user ru - WHERE ru.user_id = u.id - ORDER BY ru.id - LIMIT 1 -) ru ON true -LEFT JOIN roles r ON r.id = ru.role_id` +LEFT JOIN roles r ON r.id = u.role_id` const activityLogSelectColumns = `al.id, al.user_id, al.method, al.path, al.module, al.action, al.status_code, al.request_body, al.ip, al.created_at, COALESCE(u.username, ''), COALESCE(r.code, '')` @@ -119,14 +112,7 @@ func (r *repository) Create(ctx context.Context, dto activitylog.CreateActivityL SELECT ` + activityLogSelectColumns + ` FROM inserted al LEFT JOIN users u ON u.id = al.user_id - LEFT JOIN LATERAL ( - SELECT ru.role_id - FROM role_user ru - WHERE ru.user_id = u.id - ORDER BY ru.id - LIMIT 1 - ) ru ON true - LEFT JOIN roles r ON r.id = ru.role_id` + LEFT JOIN roles r ON r.id = u.role_id` row := r.client.QueryRow(ctx, query, dto.UserId, dto.Method, dto.Path, dto.Module, dto.Action, dto.StatusCode, dto.RequestBody, dto.Ip, diff --git a/internal/identity/activitylog/handler.go b/internal/identity/activitylog/handler.go index 0e674ec..6d32d89 100644 --- a/internal/identity/activitylog/handler.go +++ b/internal/identity/activitylog/handler.go @@ -8,6 +8,8 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -29,14 +31,14 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler // Register only wires read endpoints: activity log entries are written by // the Record middleware, never through the API. func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.ActivityLogs)) group.GET("", h.list) group.GET("/:id", h.getByID) } // list godoc // @Summary List activity logs -// @Description Returns a paginated audit trail of user actions (create/update/delete). Each log includes the actor's username and role from role_user. +// @Description Returns a paginated audit trail of user actions (create/update/delete). Each log includes the actor's username and role code. // @Tags activity-logs // @Produce json // @Security BearerAuth diff --git a/internal/identity/auth/db/postgresql.go b/internal/identity/auth/db/postgresql.go index a815353..c6312d0 100755 --- a/internal/identity/auth/db/postgresql.go +++ b/internal/identity/auth/db/postgresql.go @@ -5,10 +5,12 @@ import ( "database/sql" "encoding/json" "errors" + "sort" "strings" "unicode" "online-back/internal/identity/auth" + "online-back/internal/identity/rbac/perm" "online-back/pkg/client/postgresql" "online-back/pkg/logging" "online-back/pkg/repository/genericrepo" @@ -46,14 +48,7 @@ const ( ) const profileFromClause = ` FROM users u -LEFT JOIN LATERAL ( - SELECT ru.role_id - FROM role_user ru - WHERE ru.user_id = u.id AND ru.deleted_at IS NULL - ORDER BY ru.id - LIMIT 1 -) ru ON true -LEFT JOIN roles r ON r.id = ru.role_id AND r.deleted_at IS NULL` +LEFT JOIN roles r ON r.id = u.role_id AND r.deleted_at IS NULL` const profileBranchesJSON = `COALESCE(( SELECT json_agg(jsonb_build_object( @@ -70,24 +65,18 @@ const profileBranchesJSON = `COALESCE(( ) b ), '[]'::json)` +// profilePermissionsJSON: every permission for an is_super role, else the +// role's own; ordered as rbac/perm.All by the caller. const profilePermissionsJSON = `COALESCE(( - SELECT json_agg(jsonb_build_object( - 'id', p.id, - 'code', COALESCE(p.code, ''), - 'name', p.name, - 'guardName', p.guard_name, - 'module', COALESCE(p.module, '') - ) ORDER BY p.module, p.id) + SELECT json_agg(jsonb_build_object('code', p.code, 'name', p.name)) FROM permissions p - WHERE p.deleted_at IS NULL - AND EXISTS ( - SELECT 1 FROM permission_role pr - WHERE pr.role_id = r.id AND pr.permission_id = p.id AND pr.deleted_at IS NULL + WHERE r.is_super OR EXISTS ( + SELECT 1 FROM role_permissions rp WHERE rp.role_id = r.id AND rp.permission_code = p.code ) ), '[]'::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, r.guard_name, ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1 AND u.deleted_at IS NULL` + r.id, r.code, r.name, r.scope, COALESCE(r.is_super, false), ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1 AND u.deleted_at IS NULL` func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) { phone := strings.TrimSpace(dto.Phone) @@ -138,7 +127,8 @@ func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateP func scanProfile(row genericrepo.Scanner) (auth.UserProfileDTO, error) { var profile auth.UserProfileDTO var roleID sql.NullInt64 - var roleCode, roleName, roleGuard sql.NullString + var roleCode, roleName, roleScope sql.NullString + var roleSuper bool var branchesJSON []byte var permissionsJSON []byte @@ -153,7 +143,8 @@ func scanProfile(row genericrepo.Scanner) (auth.UserProfileDTO, error) { &roleID, &roleCode, &roleName, - &roleGuard, + &roleScope, + &roleSuper, &branchesJSON, &permissionsJSON, ) @@ -163,10 +154,11 @@ func scanProfile(row genericrepo.Scanner) (auth.UserProfileDTO, error) { if roleID.Valid { profile.Role = &auth.ProfileRoleDTO{ - Id: roleID.Int64, - Code: roleCode.String, - Name: roleName.String, - GuardName: roleGuard.String, + Id: roleID.Int64, + Code: roleCode.String, + Name: roleName.String, + Scope: roleScope.String, + IsSuper: roleSuper, } } @@ -183,7 +175,7 @@ func scanProfile(row genericrepo.Scanner) (auth.UserProfileDTO, error) { return auth.UserProfileDTO{}, err } } - profile.Modules = auth.GroupProfileModules(profile.Permissions) + sortByCatalog(profile.Permissions) return profile, nil } @@ -260,8 +252,8 @@ func (r *repository) CompleteRegistration(ctx context.Context, v auth.Verificati var userID int err = tx.QueryRow(ctx, ` - INSERT INTO users (name, username, phone, password, role, active, email) - VALUES ($1, $2, $3, $4, 'user', true, '') + INSERT INTO users (name, username, phone, password, role_id, active, email) + VALUES ($1, $2, $3, $4, (SELECT id FROM roles WHERE code = 'user' AND deleted_at IS NULL), true, '') RETURNING id`, v.Name, v.Username, v.Phone, v.Password, ).Scan(&userID) @@ -273,16 +265,6 @@ func (r *repository) CompleteRegistration(ctx context.Context, v auth.Verificati return 0, err } - tag, err := tx.Exec(ctx, ` - INSERT INTO role_user (role_id, user_id) - SELECT r.id, $1 FROM roles r WHERE r.code = 'user'`, userID) - if err != nil { - return 0, err - } - if tag.RowsAffected() == 0 { - return 0, errors.New(`role "user" not found`) - } - if _, err := tx.Exec(ctx, `DELETE FROM registration_verifications WHERE id = $1`, v.ID); err != nil { return 0, err } @@ -342,3 +324,13 @@ func digitString(s string) string { } return b.String() } + +func sortByCatalog(perms []auth.ProfilePermissionDTO) { + order := make(map[perm.Code]int, len(perm.All)) + for i, d := range perm.All { + order[d.Code] = i + } + sort.SliceStable(perms, func(i, j int) bool { + return order[perm.Code(perms[i].Code)] < order[perm.Code(perms[j].Code)] + }) +} diff --git a/internal/identity/auth/dto.go b/internal/identity/auth/dto.go index 13d0b5f..f06b418 100755 --- a/internal/identity/auth/dto.go +++ b/internal/identity/auth/dto.go @@ -19,10 +19,11 @@ type LocalizedText struct { } type ProfileRoleDTO struct { - Id int64 `json:"id"` - Code string `json:"code"` - Name string `json:"name"` - GuardName string `json:"guardName"` + Id int64 `json:"id"` + Code string `json:"code"` + Name string `json:"name"` + Scope string `json:"scope"` + IsSuper bool `json:"isSuper"` } type ProfileBranchDTO struct { @@ -31,17 +32,11 @@ type ProfileBranchDTO struct { Name LocalizedText `json:"name"` } +// ProfilePermissionDTO is one module the caller can open; the front-end +// builds its menu from this list. type ProfilePermissionDTO struct { - Id int64 `json:"id"` - Code string `json:"code"` - Name string `json:"name"` - GuardName string `json:"guardName"` - Module string `json:"module"` -} - -type ProfileModuleDTO struct { - Module string `json:"module"` - Permissions []ProfilePermissionDTO `json:"permissions"` + Code string `json:"code"` + Name string `json:"name"` } type UserProfileDTO struct { @@ -53,7 +48,6 @@ type UserProfileDTO struct { Avatar string `json:"avatar"` Role *ProfileRoleDTO `json:"role"` Branches []ProfileBranchDTO `json:"branches"` - Modules []ProfileModuleDTO `json:"modules"` Permissions []ProfilePermissionDTO `json:"permissions"` CreatedAt time.Time `json:"createdAt"` } diff --git a/internal/identity/auth/handler.go b/internal/identity/auth/handler.go index 6e4ee9a..a00ecfd 100755 --- a/internal/identity/auth/handler.go +++ b/internal/identity/auth/handler.go @@ -7,6 +7,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" "online-back/pkg/logging" "online-back/pkg/sms" @@ -35,16 +36,16 @@ func NewHandler(logger *logging.Logger, repository Repository, sender sms.Sender } func (h *handler) Register(router *gin.RouterGroup) { - router.POST(loginURL, h.login) - router.POST(tokenURL, h.refreshToken) - router.POST(registerURL, h.register) - router.POST(verifyURL, h.verify) - router.POST(forgotPasswordURL, h.forgotPassword) - router.POST(resetPasswordURL, h.resetPassword) + rbac.Group(router, loginURL, rbac.Public()).POST("", h.login) + rbac.Group(router, tokenURL, rbac.Public()).POST("", h.refreshToken) + rbac.Group(router, registerURL, rbac.Public()).POST("", h.register) + rbac.Group(router, verifyURL, rbac.Public()).POST("", h.verify) + rbac.Group(router, forgotPasswordURL, rbac.Public()).POST("", h.forgotPassword) + rbac.Group(router, resetPasswordURL, rbac.Public()).POST("", h.resetPassword) - protected := router.Group("", appresult.JwtTokenCheck()) - protected.GET(profileURL, h.getProfile) - protected.PUT(profileURL, h.updateProfile) + profile := rbac.Group(router, profileURL, rbac.Authenticated()) + profile.GET("", h.getProfile) + profile.PUT("", h.updateProfile) } // login godoc diff --git a/internal/identity/auth/profile_modules.go b/internal/identity/auth/profile_modules.go deleted file mode 100644 index 2aef61a..0000000 --- a/internal/identity/auth/profile_modules.go +++ /dev/null @@ -1,37 +0,0 @@ -package auth - -import ( - "sort" - - "online-back/internal/identity/permission" -) - -func GroupProfileModules(perms []ProfilePermissionDTO) []ProfileModuleDTO { - buckets := make(map[string][]ProfilePermissionDTO) - seen := make(map[string]struct{}) - for _, p := range perms { - module := p.Module - buckets[module] = append(buckets[module], p) - seen[module] = struct{}{} - } - - modules := make([]ProfileModuleDTO, 0, len(seen)) - for _, name := range permission.ModuleOrder() { - ps, ok := buckets[name] - if !ok { - continue - } - modules = append(modules, ProfileModuleDTO{Module: name, Permissions: ps}) - delete(seen, name) - } - - var extra []string - for name := range seen { - extra = append(extra, name) - } - sort.Strings(extra) - for _, name := range extra { - modules = append(modules, ProfileModuleDTO{Module: name, Permissions: buckets[name]}) - } - return modules -} diff --git a/internal/identity/permission/db/postgresql.go b/internal/identity/permission/db/postgresql.go deleted file mode 100644 index b1223b3..0000000 --- a/internal/identity/permission/db/postgresql.go +++ /dev/null @@ -1,139 +0,0 @@ -package db - -import ( - "context" - "errors" - "fmt" - "strings" - - "online-back/internal/identity/permission" - "online-back/internal/shared" - "online-back/pkg/client/postgresql" - "online-back/pkg/logging" - "online-back/pkg/repository/genericrepo" - - "github.com/jackc/pgx/v4" -) - -type repository struct { - client postgresql.Client - generic *genericrepo.Repository[permission.PermissionDTO] - logger *logging.Logger -} - -func NewRepository(client postgresql.Client, logger *logging.Logger) permission.Repository { - return &repository{ - client: client, - generic: genericrepo.New(client, "permissions p", permissionColumns, scanPermission), - logger: logger, - } -} - -const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.module, p.created_at, p.updated_at` - -const permissionReturningColumns = `id, code, name, guard_name, module, created_at, updated_at` - -func (r *repository) List(ctx context.Context, filter permission.ListFilter) (permission.ListPermissionDTO, error) { - whereClause, args := buildListQuery(filter) - - items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") - if err != nil { - return permission.ListPermissionDTO{}, err - } - - return permission.ListPermissionDTO{Count: count, Permissions: items}, nil -} - -func buildListQuery(filter permission.ListFilter) (whereClause string, args []interface{}) { - var conditions []string - if filter.PermissionName != "" { - args = append(args, shared.LikePattern(filter.PermissionName)) - n := len(args) - conditions = append(conditions, fmt.Sprintf(`p.name ILIKE $%d`, n)) - } - if filter.GuardName != "" { - args = append(args, filter.GuardName) - conditions = append(conditions, fmt.Sprintf(`p.guard_name = $%d`, len(args))) - } - if filter.Module != "" { - args = append(args, filter.Module) - conditions = append(conditions, fmt.Sprintf(`p.module = $%d`, len(args))) - } - - if len(conditions) == 0 { - return "", args - } - - return " WHERE " + strings.Join(conditions, " AND "), args -} - -func (r *repository) GetByID(ctx context.Context, id int64) (permission.PermissionDTO, error) { - return r.generic.GetByID(ctx, id) -} - -func (r *repository) Tree(ctx context.Context, guardName string) (permission.PermissionTreeDTO, error) { - query := `SELECT ` + permissionColumns + ` FROM permissions p` - var args []interface{} - if guardName != "" { - query += ` WHERE p.guard_name = $1` - args = append(args, guardName) - } - query += ` ORDER BY p.guard_name, p.module, p.id` - - rows, err := r.client.Query(ctx, query, args...) - if err != nil { - return permission.PermissionTreeDTO{}, err - } - defer rows.Close() - - var items []permission.PermissionDTO - for rows.Next() { - item, err := scanPermission(rows) - if err != nil { - return permission.PermissionTreeDTO{}, err - } - items = append(items, item) - } - if err := rows.Err(); err != nil { - return permission.PermissionTreeDTO{}, err - } - return permission.BuildTree(items), nil -} - -func (r *repository) Create(ctx context.Context, dto permission.CreatePermissionDTO) (permission.PermissionDTO, error) { - query := fmt.Sprintf(` - INSERT INTO permissions (code, name, guard_name, module) - VALUES ($1, $2, $3, $4) - RETURNING %s`, permissionReturningColumns) - - return scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, dto.Module)) -} - -func (r *repository) Update(ctx context.Context, id int64, dto permission.UpdatePermissionDTO) (permission.PermissionDTO, error) { - query := fmt.Sprintf(` - UPDATE permissions SET - code = $1, name = $2, guard_name = $3, module = $4, - updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') - WHERE id = $5 AND deleted_at IS NULL - RETURNING %s`, permissionReturningColumns) - - item, err := scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, dto.Module, id)) - if errors.Is(err, pgx.ErrNoRows) { - return permission.PermissionDTO{}, err - } - return item, err -} - -func (r *repository) Delete(ctx context.Context, id int64) error { - return r.generic.Delete(ctx, id) -} - -func scanPermission(row genericrepo.Scanner) (permission.PermissionDTO, error) { - var item permission.PermissionDTO - if err := row.Scan( - &item.Id, &item.Code, &item.Name, &item.GuardName, &item.Module, &item.CreatedAt, &item.UpdatedAt, - ); err != nil { - return permission.PermissionDTO{}, err - } - return item, nil -} diff --git a/internal/identity/permission/dto.go b/internal/identity/permission/dto.go deleted file mode 100644 index be155ab..0000000 --- a/internal/identity/permission/dto.go +++ /dev/null @@ -1,54 +0,0 @@ -package permission - -import "time" - -type PermissionDTO struct { - Id int64 `json:"id"` - Code string `json:"code"` - Name string `json:"name"` - GuardName string `json:"guardName"` - Module string `json:"module"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` -} - -type CreatePermissionDTO struct { - Code string `json:"code" binding:"required"` - Name string `json:"name" binding:"required"` - GuardName string `json:"guardName" binding:"required,oneof=web operator admin"` - Module string `json:"module" binding:"required"` -} - -type UpdatePermissionDTO struct { - Code string `json:"code" binding:"required"` - Name string `json:"name" binding:"required"` - GuardName string `json:"guardName" binding:"required,oneof=web operator admin"` - Module string `json:"module" binding:"required"` -} - -type ListFilter struct { - PermissionName string - GuardName string - Module string - Page int - Limit int -} - -type ListPermissionDTO struct { - Count int64 `json:"count"` - Permissions []PermissionDTO `json:"permissions"` -} - -type PermissionTreeDTO struct { - Guards []GuardModulesDTO `json:"guards"` -} - -type GuardModulesDTO struct { - GuardName string `json:"guardName"` - Modules []ModulePermissionsDTO `json:"modules"` -} - -type ModulePermissionsDTO struct { - Module string `json:"module"` - Permissions []PermissionDTO `json:"permissions"` -} diff --git a/internal/identity/permission/handler.go b/internal/identity/permission/handler.go index 2628136..27fa166 100644 --- a/internal/identity/permission/handler.go +++ b/internal/identity/permission/handler.go @@ -1,276 +1,40 @@ package permission import ( - "errors" "net/http" - "strconv" - "strings" "online-back/internal/appresult" "online-back/internal/handlers" - "online-back/internal/shared" - "online-back/pkg/logging" + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "github.com/gin-gonic/gin" - "github.com/jackc/pgx/v4" ) const baseURL = "/permissions" -type handler struct { - logger *logging.Logger - repository Repository -} +// handler serves the permission catalog. Permissions are defined in code +// (rbac/perm) - one per module - so there is nothing to create or edit here; +// roles pick from this list via POST/PUT /roles. +type handler struct{} -func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { - return &handler{logger: logger, repository: repository} +func NewHandler() handlers.Handler { + return &handler{} } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Roles)) group.GET("", h.list) - group.GET("/tree", h.tree) - group.GET("/:id", h.getByID) - group.POST("", h.create) - group.PUT("/:id", h.update) - group.DELETE("/:id", h.delete) } // list godoc // @Summary List permissions -// @Description Returns paginated permissions with optional filters +// @Description Returns the permission catalog: one code per module, in display order. Holding a code grants read and write in that module; the role's scope decides which records. // @Tags permission // @Produce json // @Security BearerAuth -// @Param permission_name query string false "Filter by name" -// @Param guard_name query string false "Filter by guard (web, operator, admin)" -// @Param module query string false "Filter by saha (cards, loans, …)" -// @Param page query int false "Page number" default(1) -// @Param limit query int false "Items per page" default(10) // @Success 200 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError // @Router /permissions [get] func (h *handler) list(c *gin.Context) { - filter, ok := parseListFilter(c) - if !ok { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - - result, err := h.repository.List(c.Request.Context(), filter) - if err != nil { - h.logger.Errorf("list permissions failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData(result)) -} - -// tree godoc -// @Summary Permission tree -// @Description Returns permissions grouped as guard → module (saha) → permissions -// @Tags permission -// @Produce json -// @Security BearerAuth -// @Param guard_name query string false "Filter by guard (web, operator, admin)" -// @Success 200 {object} appresult.AppSuccess -// @Failure 500 {object} appresult.AppError -// @Router /permissions/tree [get] -func (h *handler) tree(c *gin.Context) { - guardName := strings.TrimSpace(c.Query("guard_name")) - if guardName == "" { - guardName = strings.TrimSpace(c.Query("guardName")) - } - - result, err := h.repository.Tree(c.Request.Context(), guardName) - if err != nil { - h.logger.Errorf("permission tree failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData(result)) -} - -// getByID godoc -// @Summary Get permission by ID -// @Description Returns a single permission -// @Tags permission -// @Produce json -// @Security BearerAuth -// @Param id path int true "Permission ID" -// @Success 200 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 404 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /permissions/{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 permission failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData(item)) -} - -// create godoc -// @Summary Create permission -// @Description Creates a new permission -// @Tags permission -// @Accept json -// @Produce json -// @Security BearerAuth -// @Param body body CreatePermissionDTO true "Permission payload" -// @Success 201 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /permissions [post] -func (h *handler) create(c *gin.Context) { - var dto CreatePermissionDTO - 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 failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusCreated, appresult.SuccessWithData(item)) -} - -// update godoc -// @Summary Update permission -// @Description Updates an existing permission -// @Tags permission -// @Accept json -// @Produce json -// @Security BearerAuth -// @Param id path int true "Permission ID" -// @Param body body UpdatePermissionDTO true "Permission payload" -// @Success 200 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 404 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /permissions/{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 - } - - var dto UpdatePermissionDTO - if err := c.ShouldBindJSON(&dto); err != nil { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - - item, err := h.repository.Update(c.Request.Context(), id, dto) - if errors.Is(err, pgx.ErrNoRows) { - c.JSON(http.StatusNotFound, appresult.ErrNotFound) - return - } - if err != nil { - h.logger.Errorf("update permission failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData(item)) -} - -// delete godoc -// @Summary Delete permission -// @Description Deletes a permission -// @Tags permission -// @Produce json -// @Security BearerAuth -// @Param id path int true "Permission ID" -// @Success 200 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 404 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /permissions/{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 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 failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData("permission removed")) -} - -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("permission_name")); raw != "" { - filter.PermissionName = raw - } - if raw := firstQuery(c, "guard_name", "guardName"); raw != "" { - filter.GuardName = raw - } - if raw := firstQuery(c, "module"); raw != "" { - filter.Module = raw - } - - return filter, true -} - -func firstQuery(c *gin.Context, keys ...string) string { - for _, key := range keys { - if key == "" { - continue - } - if raw := strings.TrimSpace(c.Query(key)); raw != "" { - return raw - } - } - return "" + c.JSON(http.StatusOK, appresult.SuccessWithData(perm.All)) } diff --git a/internal/identity/permission/module.go b/internal/identity/permission/module.go deleted file mode 100644 index a4562d2..0000000 --- a/internal/identity/permission/module.go +++ /dev/null @@ -1,43 +0,0 @@ -package permission - -const ( - ModuleDashboard = "dashboard" - ModuleCards = "cards" - ModuleLoans = "loans" - ModuleUsers = "users" - ModuleRoles = "roles" - ModuleBranches = "branches" - ModuleProvinces = "provinces" - ModuleActivityLogs = "activity-logs" - ModuleBackups = "backups" - ModuleCurrencies = "currencies" - ModulePaymentSettings = "payment-settings" -) - -// moduleOrder is a display-order hint only, not a whitelist: the -// permissions.module field accepts any value (see permission.Repository. -// Modules, which lists what's actually in use). BuildTree/GroupProfileModules -// sort these first, then append any other module alphabetically, so a -// newly invented module still renders correctly without editing this file. -var moduleOrder = []string{ - ModuleDashboard, - ModuleCards, - ModuleLoans, - ModuleUsers, - ModuleRoles, - ModuleBranches, - ModuleProvinces, - ModuleActivityLogs, - ModuleBackups, - ModuleCurrencies, - ModulePaymentSettings, -} - -var guardOrder = []string{"operator", "admin", "web"} - -// ModuleOrder is the display order of sahalar in trees and profile. -func ModuleOrder() []string { - out := make([]string, len(moduleOrder)) - copy(out, moduleOrder) - return out -} diff --git a/internal/identity/permission/storage.go b/internal/identity/permission/storage.go deleted file mode 100644 index 4ebe8c9..0000000 --- a/internal/identity/permission/storage.go +++ /dev/null @@ -1,12 +0,0 @@ -package permission - -import "context" - -type Repository interface { - List(ctx context.Context, filter ListFilter) (ListPermissionDTO, error) - Tree(ctx context.Context, guardName string) (PermissionTreeDTO, error) - GetByID(ctx context.Context, id int64) (PermissionDTO, error) - Create(ctx context.Context, dto CreatePermissionDTO) (PermissionDTO, error) - Update(ctx context.Context, id int64, dto UpdatePermissionDTO) (PermissionDTO, error) - Delete(ctx context.Context, id int64) error -} diff --git a/internal/identity/permission/tree.go b/internal/identity/permission/tree.go deleted file mode 100644 index 68e8e5b..0000000 --- a/internal/identity/permission/tree.go +++ /dev/null @@ -1,67 +0,0 @@ -package permission - -import "sort" - -type treeKey struct { - guard string - module string -} - -// BuildTree groups a flat permission list into guard → module → permissions -// so the admin UI can render sahalar (cards, loans, …) as a tree. -func BuildTree(items []PermissionDTO) PermissionTreeDTO { - buckets := make(map[treeKey][]PermissionDTO) - guardsSeen := make(map[string]struct{}) - modulesByGuard := make(map[string]map[string]struct{}) - - for _, item := range items { - key := treeKey{guard: item.GuardName, module: item.Module} - buckets[key] = append(buckets[key], item) - guardsSeen[item.GuardName] = struct{}{} - if modulesByGuard[item.GuardName] == nil { - modulesByGuard[item.GuardName] = make(map[string]struct{}) - } - modulesByGuard[item.GuardName][item.Module] = struct{}{} - } - - guards := make([]GuardModulesDTO, 0, len(guardsSeen)) - for _, guard := range orderedKeys(guardOrder, guardsSeen) { - modulesSeen := modulesByGuard[guard] - modules := make([]ModulePermissionsDTO, 0, len(modulesSeen)) - for _, module := range orderedKeys(moduleOrder, modulesSeen) { - perms := buckets[treeKey{guard: guard, module: module}] - if perms == nil { - perms = []PermissionDTO{} - } - modules = append(modules, ModulePermissionsDTO{ - Module: module, - Permissions: perms, - }) - } - guards = append(guards, GuardModulesDTO{ - GuardName: guard, - Modules: modules, - }) - } - - return PermissionTreeDTO{Guards: guards} -} - -func orderedKeys(order []string, seen map[string]struct{}) []string { - keys := make([]string, 0, len(seen)) - used := make(map[string]struct{}, len(seen)) - for _, name := range order { - if _, ok := seen[name]; ok { - keys = append(keys, name) - used[name] = struct{}{} - } - } - var extra []string - for name := range seen { - if _, ok := used[name]; !ok { - extra = append(extra, name) - } - } - sort.Strings(extra) - return append(keys, extra...) -} diff --git a/internal/identity/permissionrole/db/postgresql.go b/internal/identity/permissionrole/db/postgresql.go deleted file mode 100644 index 8e114b0..0000000 --- a/internal/identity/permissionrole/db/postgresql.go +++ /dev/null @@ -1,101 +0,0 @@ -package db - -import ( - "context" - "errors" - - "online-back/internal/identity/permissionrole" - "online-back/pkg/client/postgresql" - "online-back/pkg/logging" - "online-back/pkg/repository/genericrepo" - - "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} -} - -// SetPermissions replaces dto.RoleId's whole permission set with -// dto.PermissionIds inside one transaction: pairs not in the list are -// soft-deleted, pairs in the list are upserted. Both statements run on the -// same tx so a role never ends up with permissions only half-updated. -func (r *repository) SetPermissions(ctx context.Context, dto permissionrole.SetRolePermissionsDTO) ([]permissionrole.PermissionRoleDTO, error) { - tx, err := r.client.Begin(ctx) - if err != nil { - return nil, err - } - defer tx.Rollback(ctx) - - _, err = tx.Exec(ctx, - `UPDATE permission_role SET deleted_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') - WHERE role_id = $1 AND deleted_at IS NULL AND NOT (permission_id = ANY($2::bigint[]))`, - dto.RoleId, dto.PermissionIds, - ) - if err != nil { - return nil, err - } - - var items []permissionrole.PermissionRoleDTO - if len(dto.PermissionIds) > 0 { - query := ` - WITH upserted AS ( - INSERT INTO permission_role (permission_id, role_id) - SELECT unnest($1::bigint[]), $2 - ON CONFLICT (permission_id, role_id) WHERE deleted_at IS NULL 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` - - rows, err := tx.Query(ctx, query, dto.PermissionIds, dto.RoleId) - if err != nil { - return nil, err - } - for rows.Next() { - item, err := scanPermissionRole(rows) - if err != nil { - rows.Close() - return nil, err - } - items = append(items, item) - } - rowsErr := rows.Err() - rows.Close() - if rowsErr != nil { - return nil, rowsErr - } - } - - if err := tx.Commit(ctx); err != nil { - return nil, err - } - return items, nil -} - -func (r *repository) Delete(ctx context.Context, id int64) error { - return genericrepo.Delete(ctx, r.client, "permission_role", id) -} - -func scanPermissionRole(row genericrepo.Scanner) (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 deleted file mode 100644 index e8a7e3c..0000000 --- a/internal/identity/permissionrole/dto.go +++ /dev/null @@ -1,24 +0,0 @@ -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"` -} - -// SetRolePermissionsDTO replaces a role's whole permission set: after the -// call, the role is assigned exactly PermissionIds - pairs not listed are -// removed, pairs listed but missing are added, and pairs already present -// are left as-is. An empty PermissionIds clears all permissions from the -// role. This is the only way to attach/update a role's permissions - there -// is no single-pair create endpoint. -type SetRolePermissionsDTO struct { - RoleId int64 `json:"roleId" binding:"required"` - PermissionIds []int64 `json:"permissionIds" binding:"required"` -} diff --git a/internal/identity/permissionrole/handler.go b/internal/identity/permissionrole/handler.go deleted file mode 100644 index e02225d..0000000 --- a/internal/identity/permissionrole/handler.go +++ /dev/null @@ -1,91 +0,0 @@ -package permissionrole - -import ( - "errors" - "net/http" - - "online-back/internal/appresult" - "online-back/internal/handlers" - "online-back/internal/shared" - "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("/bulk", h.setPermissions) - group.DELETE("/:id", h.delete) -} - -// setPermissions godoc -// @Summary Set a role's permissions -// @Description Replaces roleId's whole permission set with permissionIds - pairs not listed are removed, missing ones are added, an empty list clears all permissions from the role -// @Tags permission-roles -// @Accept json -// @Produce json -// @Security BearerAuth -// @Param body body SetRolePermissionsDTO true "Role + the permission IDs it should have" -// @Success 201 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /permission-roles/bulk [post] -func (h *handler) setPermissions(c *gin.Context) { - var dto SetRolePermissionsDTO - if err := c.ShouldBindJSON(&dto); err != nil { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - - items, err := h.repository.SetPermissions(c.Request.Context(), dto) - if err != nil { - h.logger.Errorf("set role permissions failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusCreated, appresult.SuccessWithData(items)) -} - -// 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 := shared.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")) -} diff --git a/internal/identity/permissionrole/storage.go b/internal/identity/permissionrole/storage.go deleted file mode 100644 index 6a001ca..0000000 --- a/internal/identity/permissionrole/storage.go +++ /dev/null @@ -1,10 +0,0 @@ -package permissionrole - -import "context" - -type Repository interface { - // SetPermissions replaces the role's permission set. See - // SetRolePermissionsDTO for the exact (add/remove/clear) semantics. - SetPermissions(ctx context.Context, dto SetRolePermissionsDTO) ([]PermissionRoleDTO, error) - Delete(ctx context.Context, id int64) error -} diff --git a/internal/identity/rbac/middleware.go b/internal/identity/rbac/middleware.go index 632f211..7b4cced 100644 --- a/internal/identity/rbac/middleware.go +++ b/internal/identity/rbac/middleware.go @@ -10,6 +10,7 @@ import ( "online-back/internal/appresult" "online-back/internal/config" + "online-back/internal/identity/rbac/perm" "online-back/pkg/logging" "github.com/gin-gonic/gin" @@ -18,291 +19,176 @@ import ( ) const ( - roleUser = "user" - roleOperator = "operator" - roleSuperadmin = "superadmin" - guardWeb = "web" - guardOperator = "operator" - guardAdmin = "admin" - adminPrefix = "/api/admin" - contextRole = "role" - contextGuard = "guard" + contextPrincipal = "rbacPrincipal" + contextService = "rbacService" ) -func RequirePermission(service Authorizer, code string) gin.HandlerFunc { - return func(c *gin.Context) { - rawID, exists := c.Get("id") - if !exists { - c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) - return - } +// Public: no token (login, register, payment callback). +func Public() Policy { + return Policy{name: "public", read: rule{kind: rulePublic}, write: rule{kind: rulePublic}} +} - userID, err := strconv.ParseInt(rawID.(string), 10, 64) - if err != nil { - c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) - return - } +// Authenticated: any logged-in user, clients included (profile, file). +func Authenticated() Policy { + return Policy{name: "authenticated", read: rule{kind: ruleAuthenticated}, write: rule{kind: ruleAuthenticated}} +} - granted, err := service.HasPermission(c.Request.Context(), userID, code) - if err != nil || !granted { - c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) - return - } +// Staff: any logged-in user whose role scope is not own. +func Staff() Policy { + return Policy{name: "staff", read: rule{kind: ruleStaff}, write: rule{kind: ruleStaff}} +} - c.Next() +// Require: code for every method. Own-scope callers are limited to their +// own records, branch-scope callers to their branches. +func Require(code perm.Code) Policy { + r := rule{kind: rulePermission, perm: string(code)} + return Policy{name: "require:" + string(code), read: r, write: r} +} + +// RequireStaff: Require, but never for own-scope callers. +func RequireStaff(code perm.Code) Policy { + r := rule{kind: rulePermission, perm: string(code), staffOnly: true} + return Policy{name: "require-staff:" + string(code), read: r, write: r} +} + +// Catalog: reference data every logged-in user reads (loan types, branches, +// currencies, ...); writes need code and a staff scope. +func Catalog(code perm.Code) Policy { + return Policy{ + name: "catalog:" + string(code), + read: rule{kind: ruleAuthenticated}, + write: rule{kind: rulePermission, perm: string(code), staffOnly: true}, } } +// StaffRead: any staff member reads, writes need code. +func StaffRead(code perm.Code) Policy { + return Policy{ + name: "staff-read:" + string(code), + read: rule{kind: ruleStaff}, + write: rule{kind: rulePermission, perm: string(code), staffOnly: true}, + } +} + +// Guard runs on every /api/admin request before the route's group +// middleware: it resolves the route's policy (deny if none), and for +// non-public routes loads the caller's principal into the context. func Guard(service Authorizer) gin.HandlerFunc { return func(c *gin.Context) { - if c.Request.Method == http.MethodOptions || isPublicAdminPath(c.Request.URL.Path) { + if c.Request.Method == http.MethodOptions || c.FullPath() == "" { + c.Next() + return + } + + policy, ok := routes.lookup(c.FullPath()) + if !ok { + abortForbidden(c, "route has no rbac policy", nil) + return + } + if policy.public() { c.Next() return } userID, ok := requestUserID(c) if !ok { + // The group's JwtTokenCheck answers with the proper 401/403. c.Next() return } - code, guardName, err := service.RoleLookup(c.Request.Context(), userID) + principal, err := service.Load(c.Request.Context(), userID) if err != nil { + logging.GetLogger().Errorf("rbac: load principal %d failed: %v", userID, err) c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } + if principal == nil { + abortForbidden(c, "user or role not found", logrus.Fields{"userId": userID}) + return + } - guard := effectiveGuard(code, guardName) c.Set("id", strconv.FormatInt(userID, 10)) - c.Set(contextRole, code) - c.Set(contextGuard, guard) + c.Set(contextPrincipal, principal) c.Set(contextService, service) - - switch guard { - case guardOperator: - enforceOperator(c, service, userID) - return - case guardWeb: - if code == "" { - c.Set(contextRole, roleUser) - } - if !userRoleAllows(c.Request.Method, c.Request.URL.Path) { - c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) - return - } - scopeOwnedLists(c, userID) - if !enforceOwnWrites(c, userID) { - return - } - c.Next() - return - default: - enforceAdmin(c, service, userID, code) - return - } - } -} - -// enforceAdmin gates the admin guard: only the superadmin role code is -// unconditionally trusted (kept as one deliberately unrestricted role by -// design). Every other admin-guard role (admin, manager, currency_maintainer, -// or any future role with guard_name=admin) is checked against its actual -// permission_role grants, mirroring enforceOperator's module/code checks — -// so who can do what is decided by role/permission assignment (managed by -// superadmin via the Role/Permission/Permission-Role APIs), not by role code. -func enforceAdmin(c *gin.Context, service Authorizer, userID int64, code string) { - if strings.EqualFold(strings.TrimSpace(code), roleSuperadmin) { c.Next() - return } - - if module := operatorPathModule(c.Request.Method, c.Request.URL.Path); module != "" { - granted, err := service.HasModuleAccess(c.Request.Context(), userID, module) - if err != nil { - c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - if !granted { - abortForbidden(c, "missing module access for admin path", logrus.Fields{"userId": userID, "module": module}) - return - } - } - - if perm := adminPathPermission(c.Request.Method, c.Request.URL.Path); perm != "" { - granted, err := service.HasPermission(c.Request.Context(), userID, perm) - if err != nil { - c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - if !granted { - abortForbidden(c, "missing permission for admin path", logrus.Fields{"userId": userID, "permission": perm}) - return - } - } - - c.Next() } -func enforceOperator(c *gin.Context, service Authorizer, 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) { - abortForbidden(c, "route not in operator allow-list", logrus.Fields{"userId": userID}) - return - } - - if !operatorProfileOrFile(c.Request.URL.Path) && !operatorClientsList(c.Request.URL.Path) && len(ids) == 0 { - abortForbidden(c, "operator has no assigned branches", logrus.Fields{"userId": userID}) - return - } - - if module := operatorPathModule(c.Request.Method, c.Request.URL.Path); module != "" { - granted, err := service.HasModuleAccess(c.Request.Context(), userID, module) - if err != nil { - c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) +func (p Policy) handler() gin.HandlerFunc { + return func(c *gin.Context) { + r := p.ruleFor(c.Request.Method) + principal := PrincipalFrom(c) + if principal == nil { + abortForbidden(c, "no principal", nil) return } - if !granted { - abortForbidden(c, "missing module access for operator path", logrus.Fields{"userId": userID, "module": module}) + + switch r.kind { + case ruleAuthenticated: + case ruleStaff: + if principal.Scope == ScopeOwn { + abortForbidden(c, "staff only", logrus.Fields{"userId": principal.UserID}) + return + } + case rulePermission: + if !principal.Can(perm.Code(r.perm)) { + abortForbidden(c, "missing permission", logrus.Fields{"userId": principal.UserID, "permission": r.perm}) + return + } + if r.staffOnly && principal.Scope == ScopeOwn { + abortForbidden(c, "staff only", logrus.Fields{"userId": principal.UserID, "permission": r.perm}) + return + } + if !enforceScope(c, principal) { + return + } + default: + abortForbidden(c, "unknown rule", nil) return } + c.Next() } - - if perm := operatorPathPermission(c.Request.Method, c.Request.URL.Path); perm != "" { - granted, err := service.HasPermission(c.Request.Context(), userID, perm) - if err != nil { - c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - if !granted { - abortForbidden(c, "missing permission for operator path", logrus.Fields{"userId": userID, "permission": perm}) - return - } - } - - if !operatorWriteAllowed(c, service, ids) { - return - } - - c.Next() } -// abortForbidden logs why a request was denied (method, path, and any extra -// fields the caller passes) before writing the 403, since appresult.ErrForbidden -// alone gives the client and the logs no way to tell which rbac check failed. -func abortForbidden(c *gin.Context, reason string, fields logrus.Fields) { - entry := logging.GetLogger().WithFields(logrus.Fields{ - "method": c.Request.Method, - "path": c.Request.URL.Path, - }) - for k, v := range fields { - entry = entry.WithField(k, v) - } - entry.Warn("rbac forbidden: " + reason) - c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) -} - -// EffectiveGuard resolves the guard a role with the given code/guard_name -// would run requests under - the same resolution Guard() applies to the -// caller on every request. Exposed so callers that grant a role (e.g. the -// user handler) can ask "would this reach guardAdmin?" against the role's -// real guard_name instead of matching against a hardcoded list of role -// names, which drifts the moment a new role is added. -func EffectiveGuard(code, guardName string) string { - return effectiveGuard(code, guardName) -} - -func effectiveGuard(code, guardName string) string { - code = strings.ToLower(strings.TrimSpace(code)) - guard := strings.ToLower(strings.TrimSpace(guardName)) - - switch code { - case "admin", "superadmin", "manager": - return guardAdmin - case roleOperator, "operatot": - return guardOperator - } - - switch guard { - case guardWeb, guardOperator, guardAdmin: - return guard - } - - if code == roleUser || code == "" { - return guardWeb - } - return guardAdmin -} - -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", - adminPrefix + "/visa-master-payment-orders/callback": +// enforceScope applies the role's data scope to a permission-gated request. +// own: list queries and write bodies are pinned to the caller's user id. +// branch: the caller must have branches, and write bodies may only name +// those branches (and, on update, users visible in them). +func enforceScope(c *gin.Context, p *Principal) bool { + switch p.Scope { + case ScopeAll: return true - default: - return false - } -} - -func userRoleAllows(method, path string) bool { - rest := adminREST(path) - if rest == "" { - return false - } - - if matchesPrefix(rest, userCatalogPrefixes) { - return method == http.MethodGet - } - if matchesPrefix(rest, userSelfPrefixes) { - if rest == "/profile" || strings.HasPrefix(rest, "/profile/") { - return method == http.MethodGet || method == http.MethodPut || method == http.MethodPatch - } - return method == http.MethodGet || method == http.MethodPost - } - if matchesPrefix(rest, userOwnedPrefixes) { - switch method { - case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete: - return true + case ScopeOwn: + pinOwnQuery(c, p.UserID) + return pinOwnBody(c, p.UserID) + case ScopeBranch: + if len(p.BranchIDs) == 0 { + abortForbidden(c, "branch scope without assigned branches", logrus.Fields{"userId": p.UserID}) + return false } + return branchWriteAllowed(c, p.BranchIDs) } + abortForbidden(c, "unknown scope", logrus.Fields{"userId": p.UserID, "scope": p.Scope}) return false } -func matchesPrefix(rest string, prefixes []string) bool { - for _, prefix := range prefixes { - if rest == prefix || strings.HasPrefix(rest, prefix+"/") { - return true - } - } - return false +func pinOwnQuery(c *gin.Context, userID int64) { + query := c.Request.URL.Query() + id := strconv.FormatInt(userID, 10) + query.Set("user_id", id) + query.Set("created_by", id) + c.Request.URL.RawQuery = query.Encode() } -func enforceOwnWrites(c *gin.Context, userID int64) bool { - if !matchesPrefix(adminREST(c.Request.URL.Path), userOwnedPrefixes) { +func pinOwnBody(c *gin.Context, userID int64) bool { + if !isWrite(c.Request.Method) || c.Request.Method == http.MethodDelete { return true } - switch c.Request.Method { - case http.MethodPost, http.MethodPut, http.MethodPatch: - default: - return true - } - - body, err := io.ReadAll(c.Request.Body) - if err != nil { - c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam) + body, ok := readBody(c) + if !ok { return false } - c.Request.Body = io.NopCloser(bytes.NewBuffer(body)) if len(bytes.TrimSpace(body)) == 0 { return true } @@ -324,30 +210,92 @@ func enforceOwnWrites(c *gin.Context, userID int64) bool { return true } -func scopeOwnedLists(c *gin.Context, userID int64) { - rest := strings.TrimSuffix(strings.TrimPrefix(c.Request.URL.Path, adminPrefix), "/") - if rest == "" { - return +func branchWriteAllowed(c *gin.Context, branchIDs []int64) bool { + switch c.Request.Method { + case http.MethodPost, http.MethodPut, http.MethodPatch: + default: + return true } - if !strings.HasPrefix(rest, "/") { - rest = "/" + rest + body, ok := readBody(c) + if !ok { + return false + } + if len(bytes.TrimSpace(body)) == 0 { + return true } - owned := false - for _, prefix := range userOwnedPrefixes { - if rest == prefix || strings.HasPrefix(rest, prefix+"/") { - owned = true - break - } + var payload struct { + BranchId *int64 `json:"branchId"` + UserId *int64 `json:"userId"` } - if !owned { - return + if err := json.Unmarshal(body, &payload); err != nil { + return true } - query := c.Request.URL.Query() - query.Set("user_id", strconv.FormatInt(userID, 10)) - query.Set("created_by", strconv.FormatInt(userID, 10)) - c.Request.URL.RawQuery = query.Encode() + if payload.BranchId != nil && *payload.BranchId > 0 && !containsInt64(branchIDs, *payload.BranchId) { + abortForbidden(c, "payload branchId not in caller's branches", logrus.Fields{ + "requestedBranchId": *payload.BranchId, + "allowedBranchIds": branchIDs, + }) + return false + } + + // A new order's customer has no record in the branch yet; the branchId + // check above already scopes the create, so only reassignment (PUT/PATCH) + // has to name a user visible in the caller's branches. + if c.Request.Method == http.MethodPost || payload.UserId == nil || *payload.UserId <= 0 { + return true + } + service := serviceFrom(c) + if service == nil { + abortForbidden(c, "no rbac service", nil) + return false + } + visible, err := service.UserVisibleInBranches(c.Request.Context(), *payload.UserId, branchIDs) + if err != nil { + c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return false + } + if !visible { + abortForbidden(c, "payload userId not visible in caller's branches", logrus.Fields{ + "requestedUserId": *payload.UserId, + "allowedBranchIds": branchIDs, + }) + return false + } + return true +} + +func readBody(c *gin.Context) ([]byte, bool) { + body, err := io.ReadAll(c.Request.Body) + if err != nil { + c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam) + return nil, false + } + c.Request.Body = io.NopCloser(bytes.NewBuffer(body)) + return body, true +} + +func isWrite(method string) bool { + switch method { + case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete: + return true + } + return false +} + +// abortForbidden logs which rbac check denied the request before writing the +// 403, since appresult.ErrForbidden alone doesn't say. +func abortForbidden(c *gin.Context, reason string, fields logrus.Fields) { + entry := logging.GetLogger().WithFields(logrus.Fields{ + "method": c.Request.Method, + "path": c.Request.URL.Path, + }) + for k, v := range fields { + entry = entry.WithField(k, v) + } + entry.Warn("rbac forbidden: " + reason) + c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) } func requestUserID(c *gin.Context) (int64, bool) { @@ -408,278 +356,3 @@ func bearerToken(header string) string { } return strings.TrimSpace(header) } - -var userCatalogPrefixes = []string{ - "/payment-cards", - "/reasons-cards", - "/loan-types", - "/loans-documents", - "/currencies", - "/branches", - "/provinces", - "/users/clients", -} - -var userSelfPrefixes = []string{ - "/profile", - "/file", -} - -var userOwnedPrefixes = []string{ - "/cards", - "/card-balances", - "/card-orders", - "/card-pin-orders", - "/card-rekwizit-orders", - "/visa-master-payment-orders", - "/loan-orders", - "/loans-repayment", - "/loan-paid-off-letters", -} - -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 operatorClientsList(path string) bool { - rest := adminREST(path) - return rest == "/users/clients" || strings.HasPrefix(rest, "/users/clients/") -} - -func operatorWriteAllowed(c *gin.Context, service Authorizer, 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) { - abortForbidden(c, "payload branchId not in operator's assigned branches", logrus.Fields{ - "requestedBranchId": *payload.BranchId, - "allowedBranchIds": branchIDs, - }) - return false - } - - // A new order's customer has no prior record in the branch to be - // "visible" through yet — the branchId check above already scopes the - // create to the operator's own branch, so only enforce user visibility - // when reassigning an existing record (PUT/PATCH). - if c.Request.Method == http.MethodPost { - return true - } - - 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 { - abortForbidden(c, "payload userId not visible in operator's branches", logrus.Fields{ - "requestedUserId": *payload.UserId, - "allowedBranchIds": branchIDs, - }) - 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 -} - -// operatorPathModule returns the permission module ("cards" or "loans") that -// guards a saha endpoint. Matching by module rather than a fixed code lets an -// admin grant access under a new permission code created in that module -// (via the existing Permission/Permission-Role APIs) without a code change -// here. Shared by both enforceOperator and enforceAdmin — the cards/loans -// grouping is the same regardless of which guard is calling. -func operatorPathModule(_, path string) string { - rest := adminREST(path) - - switch { - case matchesPrefix(rest, []string{ - "/cards", - "/card-balances", - "/card-orders", - "/card-pin-orders", - "/card-rekwizit-orders", - "/visa-master-payment-orders", - "/payment-history", - "/payment-cards", - "/reasons-cards", - }): - return "cards" - - case matchesPrefix(rest, []string{ - "/loan-orders", - "/loans-repayment", - "/loan-paid-off-letters", - "/loan-types", - "/loans-documents", - }): - return "loans" - } - - return "" -} - -// operatorPathPermission returns the exact permission code required for -// endpoints that distinguish view vs. manage access. Empty string: shared -// catalog (profile, file, dashboard, branches, provinces, users/clients, -// currencies read) — any operator may call it. -func operatorPathPermission(method, path string) string { - rest := adminREST(path) - - switch { - case matchesPrefix(rest, []string{"/users/clients"}): - return "" - - case matchesPrefix(rest, []string{"/users", "/branch-users"}): - if method == http.MethodGet { - return "users.view" - } - return "users.manage" - } - - return "" -} - -// adminPathPermission returns the ".view"/".manage" code -// required for admin-guard saha that split read vs. write access (unlike -// cards/loans, which stay module-based via operatorPathModule). Empty -// string: no permission required (dashboard, profile, file, public routes). -func adminPathPermission(method, path string) string { - rest := adminREST(path) - - switch { - case matchesPrefix(rest, []string{"/users", "/branch-users"}): - return viewOrManage(method, "users") - - case matchesPrefix(rest, []string{"/roles", "/permissions", "/permission-roles", "/role-users"}): - return viewOrManage(method, "roles") - - case matchesPrefix(rest, []string{"/branches"}): - return viewOrManage(method, "branches") - - case matchesPrefix(rest, []string{"/provinces"}): - return viewOrManage(method, "provinces") - - case matchesPrefix(rest, []string{"/activity-logs"}): - return "activity-logs.view" - - case matchesPrefix(rest, []string{"/backups"}): - return viewOrManage(method, "backups") - - case matchesPrefix(rest, []string{"/currencies"}): - return viewOrManage(method, "currencies") - - case matchesPrefix(rest, []string{"/payment-settings"}): - return viewOrManage(method, "payment-settings") - } - - return "" -} - -func viewOrManage(method, module string) string { - if method == http.MethodGet { - return module + ".view" - } - return module + ".manage" -} - -var operatorWritePrefixes = []string{ - "/profile", - "/file", - "/users", - "/branch-users", - "/cards", - "/card-balances", - "/card-orders", - "/card-pin-orders", - "/card-rekwizit-orders", - "/visa-master-payment-orders", - "/payment-cards", - "/reasons-cards", - "/loan-orders", - "/loans-repayment", - "/loan-paid-off-letters", - "/loan-types", - "/loans-documents", -} - -var operatorGetPrefixes = []string{ - "/profile", - "/file", - "/dashboard", - "/users", - "/cards", - "/card-balances", - "/card-orders", - "/card-pin-orders", - "/card-rekwizit-orders", - "/payment-cards", - "/reasons-cards", - "/visa-master-payment-orders", - "/payment-history", - "/loan-orders", - "/loan-types", - "/loans-documents", - "/loans-repayment", - "/loan-paid-off-letters", - "/provinces", - "/branches", - "/currencies", - "/payment-settings", -} diff --git a/internal/identity/rbac/middleware_test.go b/internal/identity/rbac/middleware_test.go deleted file mode 100644 index b6d3aa2..0000000 --- a/internal/identity/rbac/middleware_test.go +++ /dev/null @@ -1,895 +0,0 @@ -package rbac - -import ( - "bytes" - "context" - "errors" - "io" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/gin-gonic/gin" - "github.com/golang-jwt/jwt" -) - -func TestUserRoleAllows(t *testing.T) { - tests := []struct { - method, path string - want bool - }{ - {http.MethodGet, "/api/admin/currencies", true}, - {http.MethodGet, "/api/admin/currencies/3", true}, - {http.MethodPost, "/api/admin/currencies", false}, - {http.MethodPut, "/api/admin/currencies/3", false}, - {http.MethodDelete, "/api/admin/currencies/3", false}, - {http.MethodGet, "/api/admin/backups", false}, - {http.MethodGet, "/api/admin/backups/1", false}, - {http.MethodPost, "/api/admin/backups", false}, - {http.MethodGet, "/api/admin/cards", true}, - {http.MethodPost, "/api/admin/cards", true}, - {http.MethodPut, "/api/admin/cards/9", true}, - {http.MethodDelete, "/api/admin/cards/9", true}, - {http.MethodGet, "/api/admin/card-orders/9", true}, - {http.MethodPost, "/api/admin/card-orders", true}, - {http.MethodPut, "/api/admin/loan-orders/2", true}, - {http.MethodDelete, "/api/admin/loan-orders/2", true}, - {http.MethodGet, "/api/admin/card-balances", true}, - {http.MethodPost, "/api/admin/card-balances", true}, - {http.MethodPut, "/api/admin/card-balances/9", true}, - {http.MethodDelete, "/api/admin/card-balances/9", true}, - {http.MethodGet, "/api/admin/profile", true}, - {http.MethodPut, "/api/admin/profile", true}, - {http.MethodPost, "/api/admin/file", true}, - {http.MethodDelete, "/api/admin/profile", false}, - {http.MethodGet, "/api/admin/users", false}, - {http.MethodGet, "/api/admin/activity-logs", false}, - {http.MethodGet, "/api/admin/provinces", true}, - {http.MethodPost, "/api/admin/provinces", false}, - {http.MethodGet, "/api/admin/branches", true}, - {http.MethodPost, "/api/admin/branches", false}, - {http.MethodGet, "/api/admin/users/clients", true}, - {http.MethodPost, "/api/admin/users", false}, - {http.MethodGet, "/api/admin/loan-types", true}, - {http.MethodPost, "/api/admin/loan-types", false}, - {http.MethodPost, "/api/admin/loan-orders", true}, - {http.MethodGet, "/api/admin/loans-repayment", true}, - {http.MethodPost, "/api/admin/loans-repayment", true}, - {http.MethodDelete, "/api/admin/loan-paid-off-letters/4", true}, - {http.MethodPatch, "/api/admin/cards/9", true}, - } - for _, tt := range tests { - if got := userRoleAllows(tt.method, tt.path); got != tt.want { - t.Errorf("userRoleAllows(%s %s) = %v, want %v", tt.method, tt.path, got, tt.want) - } - } -} - -func TestOperatorRoleAllows(t *testing.T) { - tests := []struct { - method, path string - want bool - }{ - {http.MethodGet, "/api/admin/currencies", true}, - {http.MethodGet, "/api/admin/currencies/1", true}, - {http.MethodPost, "/api/admin/currencies", false}, - {http.MethodPut, "/api/admin/currencies/1", false}, - {http.MethodDelete, "/api/admin/currencies/1", false}, - {http.MethodGet, "/api/admin/backups", false}, - {http.MethodPost, "/api/admin/backups", false}, - {http.MethodGet, "/api/admin/card-orders", true}, - {http.MethodPost, "/api/admin/card-orders", true}, - {http.MethodDelete, "/api/admin/card-orders/2", true}, - {http.MethodGet, "/api/admin/dashboard", true}, - {http.MethodGet, "/api/admin/users", true}, - {http.MethodGet, "/api/admin/users/clients", true}, - {http.MethodPost, "/api/admin/users", true}, - {http.MethodGet, "/api/admin/activity-logs", false}, - {http.MethodGet, "/api/admin/provinces", true}, - {http.MethodPost, "/api/admin/provinces", false}, - {http.MethodGet, "/api/admin/card-balances", true}, - {http.MethodPost, "/api/admin/card-balances", true}, - } - for _, tt := range tests { - if got := operatorRoleAllows(tt.method, tt.path); got != tt.want { - t.Errorf("operatorRoleAllows(%s %s) = %v, want %v", tt.method, tt.path, got, tt.want) - } - } -} - -func TestOperatorClientsListNeedsNoPermission(t *testing.T) { - if got := operatorPathPermission(http.MethodGet, "/api/admin/users/clients"); got != "" { - t.Fatalf("clients GET perm=%q, want none", got) - } - if got := operatorPathPermission(http.MethodGet, "/api/admin/users"); got != "users.view" { - t.Fatalf("users GET perm=%q, want users.view", got) - } - - auth := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{}} - if status := serveGuard(auth, http.MethodGet, "/api/admin/users/clients", "7", nil); status != http.StatusOK { - t.Fatalf("clients status=%d", status) - } - if status := serveGuard(auth, http.MethodGet, "/api/admin/users", "7", nil); status != http.StatusForbidden { - t.Fatalf("users list status=%d", status) - } - noBranch := &stubAuth{role: roleOperator, perms: map[string]bool{}} - if status := serveGuard(noBranch, http.MethodGet, "/api/admin/users/clients", "7", nil); status != http.StatusOK { - t.Fatalf("no-branch clients status=%d", status) - } -} - -func TestOperatorCardsAndLoansSahalar(t *testing.T) { - cardsOnly := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{"cards": true}} - loansOnly := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{"loans": true}} - both := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{"cards": true, "loans": true}} - - if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusOK { - t.Fatalf("cards GET orders=%d", status) - } - if status := serveGuard(cardsOnly, http.MethodPost, "/api/admin/card-pin-orders", "7", nil); status != http.StatusOK { - t.Fatalf("cards POST pin=%d", status) - } - if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/visa-master-payment-orders", "7", nil); status != http.StatusOK { - t.Fatalf("cards GET visa=%d", status) - } - if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/loan-orders", "7", nil); status != http.StatusForbidden { - t.Fatalf("cards GET loans=%d", status) - } - - if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/loan-orders", "7", nil); status != http.StatusOK { - t.Fatalf("loans GET orders=%d", status) - } - if status := serveGuard(loansOnly, http.MethodPut, "/api/admin/loan-paid-off-letters/1", "7", nil); status != http.StatusOK { - t.Fatalf("loans PUT letter=%d", status) - } - if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusForbidden { - t.Fatalf("loans GET cards=%d", status) - } - - if status := serveGuard(both, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusOK { - t.Fatalf("both GET cards=%d", status) - } - if status := serveGuard(both, http.MethodGet, "/api/admin/loan-orders", "7", nil); status != http.StatusOK { - t.Fatalf("both GET loans=%d", status) - } - - if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/card-balances", "7", nil); status != http.StatusOK { - t.Fatalf("cards GET balances=%d", status) - } - if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/card-balances", "7", nil); status != http.StatusForbidden { - t.Fatalf("loans GET balances=%d", status) - } - if got := operatorPathModule(http.MethodGet, "/api/admin/card-balances"); got != "cards" { - t.Fatalf("card-balances path=%q", got) - } - if got := operatorPathModule(http.MethodPost, "/api/admin/card-orders"); got != "cards" { - t.Fatalf("card-orders path=%q", got) - } -} - -func TestAllCardAndLoanRoutesMapped(t *testing.T) { - cardPaths := []string{ - "/api/admin/cards", - "/api/admin/card-balances", - "/api/admin/card-orders", - "/api/admin/card-pin-orders", - "/api/admin/card-rekwizit-orders", - "/api/admin/visa-master-payment-orders", - "/api/admin/payment-cards", - "/api/admin/reasons-cards", - } - loanPaths := []string{ - "/api/admin/loan-orders", - "/api/admin/loans-repayment", - "/api/admin/loan-paid-off-letters", - "/api/admin/loan-types", - "/api/admin/loans-documents", - } - for _, path := range cardPaths { - if got := operatorPathModule(http.MethodGet, path); got != "cards" { - t.Errorf("GET %s module=%q, want cards", path, got) - } - if got := operatorPathModule(http.MethodPost, path); got != "cards" { - t.Errorf("POST %s module=%q, want cards", path, got) - } - if !operatorRoleAllows(http.MethodGet, path) || !operatorRoleAllows(http.MethodPost, path) { - t.Errorf("%s not on operator allowlist", path) - } - } - for _, path := range loanPaths { - if got := operatorPathModule(http.MethodGet, path); got != "loans" { - t.Errorf("GET %s module=%q, want loans", path, got) - } - if got := operatorPathModule(http.MethodPost, path); got != "loans" { - t.Errorf("POST %s module=%q, want loans", path, got) - } - if !operatorRoleAllows(http.MethodGet, path) || !operatorRoleAllows(http.MethodPost, path) { - t.Errorf("%s not on operator allowlist", path) - } - } -} - -func TestUserPrefixDoesNotBleedIntoOtherModules(t *testing.T) { - if matchesPrefix("/card-balances", []string{"/cards"}) { - t.Fatal("/cards prefix must not match /card-balances") - } - if !matchesPrefix("/card-balances", userOwnedPrefixes) { - t.Fatal("/card-balances must be granted via its own entry in userOwnedPrefixes") - } -} - -func TestIsPublicAdminPath(t *testing.T) { - public := []string{ - "/api/admin/login", - "/api/admin/token", - "/api/admin/register", - "/api/admin/register/verify", - "/api/admin/forgot-password", - "/api/admin/forgot-password/verify", - "/api/admin/login/", - } - for _, path := range public { - if !isPublicAdminPath(path) { - t.Errorf("expected public %s", path) - } - } - private := []string{"/api/admin/currencies", "/api/admin/backups", "/api/admin/users"} - for _, path := range private { - if isPublicAdminPath(path) { - t.Errorf("expected private %s", path) - } - } -} - -func TestAdminREST(t *testing.T) { - if got := adminREST("/api/admin/currencies/4"); got != "/currencies/4" { - t.Fatalf("got %q", got) - } - if got := adminREST("/api/admin/currencies/"); got != "/currencies" { - t.Fatalf("got %q", got) - } - if got := adminREST("/api/admin"); got != "" { - t.Fatalf("got %q", got) - } -} - -func TestScopeOwnedListsInjectsUserID(t *testing.T) { - gin.SetMode(gin.TestMode) - paths := []string{ - "/api/admin/cards?page=1", - "/api/admin/loan-orders", - "/api/admin/loans-repayment", - "/api/admin/loan-paid-off-letters", - "/api/admin/card-balances", - } - for _, path := range paths { - w := httptest.NewRecorder() - c, _ := gin.CreateTestContext(w) - c.Request = httptest.NewRequest(http.MethodGet, path, nil) - scopeOwnedLists(c, 42) - if got := c.Request.URL.Query().Get("user_id"); got != "42" { - t.Errorf("%s user_id=%q", path, got) - } - } -} - -func TestScopeOwnedListsInjectsCreatedByForCardBalances(t *testing.T) { - gin.SetMode(gin.TestMode) - w := httptest.NewRecorder() - c, _ := gin.CreateTestContext(w) - c.Request = httptest.NewRequest(http.MethodGet, "/api/admin/card-balances?status=pending", nil) - - scopeOwnedLists(c, 42) - if got := c.Request.URL.Query().Get("created_by"); got != "42" { - t.Fatalf("card-balances created_by=%q, want 42", got) - } - if got := c.Request.URL.Query().Get("status"); got != "pending" { - t.Fatalf("existing query params must be preserved, status=%q", got) - } -} - -func TestScopeOwnedListsSkipsReferenceData(t *testing.T) { - gin.SetMode(gin.TestMode) - w := httptest.NewRecorder() - c, _ := gin.CreateTestContext(w) - c.Request = httptest.NewRequest(http.MethodGet, "/api/admin/currencies", nil) - - scopeOwnedLists(c, 42) - if got := c.Request.URL.Query().Get("user_id"); got != "" { - t.Fatalf("currencies must not be scoped by user_id, got %q", got) - } -} - -func TestGuardMatrix(t *testing.T) { - gin.SetMode(gin.TestMode) - - tests := []struct { - name string - role string - branches []int64 - method string - path string - want int - }{ - {"user GET currencies", roleUser, nil, http.MethodGet, "/api/admin/currencies", http.StatusOK}, - {"user POST currencies", roleUser, nil, http.MethodPost, "/api/admin/currencies", http.StatusForbidden}, - {"user GET backups", roleUser, nil, http.MethodGet, "/api/admin/backups", http.StatusForbidden}, - {"user GET cards", roleUser, nil, http.MethodGet, "/api/admin/cards", http.StatusOK}, - {"user POST cards", roleUser, nil, http.MethodPost, "/api/admin/cards", http.StatusOK}, - {"user PUT card-orders", roleUser, nil, http.MethodPut, "/api/admin/card-orders/3", http.StatusOK}, - {"user DELETE loan-orders", roleUser, nil, http.MethodDelete, "/api/admin/loan-orders/3", http.StatusOK}, - {"user PATCH cards", roleUser, nil, http.MethodPatch, "/api/admin/cards/3", http.StatusOK}, - {"user GET card-balances", roleUser, nil, http.MethodGet, "/api/admin/card-balances", http.StatusOK}, - {"user POST card-balances", roleUser, nil, http.MethodPost, "/api/admin/card-balances", http.StatusOK}, - {"user DELETE card-balances", roleUser, nil, http.MethodDelete, "/api/admin/card-balances/3", http.StatusOK}, - {"user POST loans-repayment", roleUser, nil, http.MethodPost, "/api/admin/loans-repayment", http.StatusOK}, - {"user PUT profile", roleUser, nil, http.MethodPut, "/api/admin/profile", http.StatusOK}, - {"user POST file", roleUser, nil, http.MethodPost, "/api/admin/file", http.StatusOK}, - {"user GET users", roleUser, nil, http.MethodGet, "/api/admin/users", http.StatusForbidden}, - {"user GET users/clients", roleUser, nil, http.MethodGet, "/api/admin/users/clients", http.StatusOK}, - {"user GET branches", roleUser, nil, http.MethodGet, "/api/admin/branches", http.StatusOK}, - {"user GET provinces", roleUser, nil, http.MethodGet, "/api/admin/provinces", http.StatusOK}, - {"user POST branches", roleUser, nil, http.MethodPost, "/api/admin/branches", http.StatusForbidden}, - {"no-role GET currencies", "", nil, http.MethodGet, "/api/admin/currencies", http.StatusOK}, - {"no-role GET backups", "", nil, http.MethodGet, "/api/admin/backups", http.StatusForbidden}, - - {"operator GET currencies", roleOperator, []int64{1}, http.MethodGet, "/api/admin/currencies", http.StatusOK}, - {"operator POST currencies", roleOperator, []int64{1}, http.MethodPost, "/api/admin/currencies", http.StatusForbidden}, - {"operator GET backups", roleOperator, []int64{1}, http.MethodGet, "/api/admin/backups", http.StatusForbidden}, - {"operator GET card-orders", roleOperator, []int64{1}, http.MethodGet, "/api/admin/card-orders", http.StatusOK}, - {"operator POST card-orders", roleOperator, []int64{1}, http.MethodPost, "/api/admin/card-orders", http.StatusOK}, - {"operator no branch GET currencies", roleOperator, nil, http.MethodGet, "/api/admin/currencies", http.StatusForbidden}, - {"operator no branch GET profile", roleOperator, nil, http.MethodGet, "/api/admin/profile", http.StatusOK}, - {"operator no branch GET users/clients", roleOperator, nil, http.MethodGet, "/api/admin/users/clients", http.StatusOK}, - - {"admin GET backups", "admin", nil, http.MethodGet, "/api/admin/backups", http.StatusOK}, - {"admin POST currencies", "admin", nil, http.MethodPost, "/api/admin/currencies", http.StatusOK}, - {"superadmin DELETE backups", "superadmin", nil, http.MethodDelete, "/api/admin/backups/1", http.StatusOK}, - {"manager GET backups", "manager", nil, http.MethodGet, "/api/admin/backups", http.StatusOK}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - status := serveGuard(&stubAuth{role: tt.role, branches: tt.branches}, tt.method, tt.path, "7", nil) - if status != tt.want { - t.Fatalf("status=%d want=%d", status, tt.want) - } - }) - } - - if status := serveGuard(&stubAuth{role: "customer", guard: guardWeb}, http.MethodPost, "/api/admin/cards", "7", nil); status != http.StatusOK { - t.Fatalf("web guard custom role status=%d", status) - } - if status := serveGuard(&stubAuth{role: "customer", guard: guardWeb}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusForbidden { - t.Fatalf("web guard backups status=%d", status) - } - if status := serveGuard(&stubAuth{role: "teller", guard: guardOperator, branches: []int64{1}}, http.MethodPost, "/api/admin/card-orders", "7", nil); status != http.StatusOK { - t.Fatalf("operator guard custom role status=%d", status) - } - if status := serveGuard(&stubAuth{role: "auditor", guard: guardAdmin}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusOK { - t.Fatalf("admin guard custom role status=%d", status) - } - if status := serveGuard(&stubAuth{role: roleOperator, guard: guardAdmin, branches: []int64{1}}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusForbidden { - t.Fatalf("legacy operator+admin guard must stay operator, status=%d", status) - } - if status := serveGuard(&stubAuth{role: "superadmin", guard: guardWeb}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusOK { - t.Fatalf("superadmin code must stay admin even if guard is web, status=%d", status) - } -} - -func TestAdminPathPermission(t *testing.T) { - tests := []struct { - method, path string - want string - }{ - {http.MethodGet, "/api/admin/users", "users.view"}, - {http.MethodPost, "/api/admin/users", "users.manage"}, - {http.MethodGet, "/api/admin/branch-users", "users.view"}, - {http.MethodGet, "/api/admin/roles", "roles.view"}, - {http.MethodPost, "/api/admin/roles", "roles.manage"}, - {http.MethodGet, "/api/admin/permissions", "roles.view"}, - {http.MethodPost, "/api/admin/permission-roles", "roles.manage"}, - {http.MethodDelete, "/api/admin/role-users/1", "roles.manage"}, - {http.MethodGet, "/api/admin/branches", "branches.view"}, - {http.MethodPost, "/api/admin/branches", "branches.manage"}, - {http.MethodGet, "/api/admin/provinces", "provinces.view"}, - {http.MethodPost, "/api/admin/provinces", "provinces.manage"}, - {http.MethodGet, "/api/admin/activity-logs", "activity-logs.view"}, - {http.MethodGet, "/api/admin/backups", "backups.view"}, - {http.MethodPost, "/api/admin/backups", "backups.manage"}, - {http.MethodGet, "/api/admin/currencies", "currencies.view"}, - {http.MethodPost, "/api/admin/currencies", "currencies.manage"}, - {http.MethodGet, "/api/admin/payment-settings", "payment-settings.view"}, - {http.MethodPut, "/api/admin/payment-settings", "payment-settings.manage"}, - {http.MethodGet, "/api/admin/dashboard", ""}, - {http.MethodGet, "/api/admin/profile", ""}, - {http.MethodPost, "/api/admin/file", ""}, - } - for _, tt := range tests { - if got := adminPathPermission(tt.method, tt.path); got != tt.want { - t.Errorf("adminPathPermission(%s %s)=%q want %q", tt.method, tt.path, got, tt.want) - } - } -} - -func TestEnforceAdminSuperadminBypassesEverything(t *testing.T) { - // perms is a non-nil empty map, so every HasPermission/HasModuleAccess - // lookup would deny — superadmin must still pass without ever checking. - auth := &stubAuth{role: roleSuperadmin, perms: map[string]bool{}} - - if status := serveGuard(auth, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusOK { - t.Fatalf("superadmin GET backups=%d", status) - } - if status := serveGuard(auth, http.MethodDelete, "/api/admin/users/1", "7", nil); status != http.StatusOK { - t.Fatalf("superadmin DELETE users=%d", status) - } -} - -func TestEnforceAdminChecksPermission(t *testing.T) { - admin := &stubAuth{role: "admin", perms: map[string]bool{}} - if status := serveGuard(admin, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusForbidden { - t.Fatalf("admin without grant GET backups=%d", status) - } - - adminWithGrant := &stubAuth{role: "admin", perms: map[string]bool{"backups.view": true}} - if status := serveGuard(adminWithGrant, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusOK { - t.Fatalf("admin with grant GET backups=%d", status) - } - - manager := &stubAuth{role: "manager", perms: map[string]bool{"cards": true}} - if status := serveGuard(manager, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusOK { - t.Fatalf("manager GET card-orders=%d", status) - } - if status := serveGuard(manager, http.MethodGet, "/api/admin/currencies", "7", nil); status != http.StatusForbidden { - t.Fatalf("manager without currencies grant GET currencies=%d", status) - } -} - -func TestGuardOptionsAndPublicSkipAuthz(t *testing.T) { - gin.SetMode(gin.TestMode) - auth := &stubAuth{role: roleUser} - - if status := serveGuard(auth, http.MethodOptions, "/api/admin/backups", "7", nil); status != http.StatusOK { - t.Fatalf("OPTIONS status=%d", status) - } - if status := serveGuard(auth, http.MethodGet, "/api/admin/login", "7", nil); status != http.StatusOK { - t.Fatalf("public login status=%d", status) - } -} - -func TestGuardWithoutUserPassesThrough(t *testing.T) { - gin.SetMode(gin.TestMode) - r := gin.New() - r.Use(Guard(&stubAuth{role: roleUser})) - r.GET("/api/admin/backups", func(c *gin.Context) { c.Status(http.StatusOK) }) - - w := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/admin/backups", nil) - r.ServeHTTP(w, req) - if w.Code != http.StatusOK { - t.Fatalf("status=%d", w.Code) - } -} - -func TestGuardRoleLookupError(t *testing.T) { - gin.SetMode(gin.TestMode) - status := serveGuard(&stubAuth{roleErr: errors.New("db down")}, http.MethodGet, "/api/admin/currencies", "7", nil) - if status != http.StatusInternalServerError { - t.Fatalf("status=%d", status) - } -} - -func TestOperatorWriteAllowedBranchScope(t *testing.T) { - gin.SetMode(gin.TestMode) - auth := &stubAuth{role: roleOperator, branches: []int64{1, 2}, visible: true} - - allowed := serveGuard(auth, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"branchId":1}`)) - if allowed != http.StatusOK { - t.Fatalf("own branch status=%d", allowed) - } - - denied := serveGuard(auth, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"branchId":99}`)) - if denied != http.StatusForbidden { - t.Fatalf("foreign branch status=%d", denied) - } -} - -func TestOperatorWriteAllowedUserVisibility(t *testing.T) { - gin.SetMode(gin.TestMode) - - okAuth := &stubAuth{role: roleOperator, branches: []int64{1}, visible: true} - if status := serveGuard(okAuth, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"userId":15}`)); status != http.StatusOK { - t.Fatalf("visible user status=%d", status) - } - - // Creating a brand-new order for a customer who has no prior record in - // the branch must still succeed — the branchId check alone scopes a - // create to the operator's own branch. - hidden := &stubAuth{role: roleOperator, branches: []int64{1}, visible: false} - if status := serveGuard(hidden, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"userId":15}`)); status != http.StatusOK { - t.Fatalf("new customer create status=%d", status) - } - - // Reassigning an existing order's customer still enforces visibility. - if status := serveGuard(hidden, http.MethodPut, "/api/admin/card-orders/1", "7", []byte(`{"userId":15}`)); status != http.StatusForbidden { - t.Fatalf("update hidden user status=%d", status) - } -} - -func TestRequirePermission(t *testing.T) { - gin.SetMode(gin.TestMode) - r := gin.New() - r.Use(func(c *gin.Context) { - c.Set("id", "3") - c.Next() - }) - r.GET("/x", RequirePermission(&stubAuth{perms: map[string]bool{"currencies.view": true}}, "currencies.view"), okHandler) - r.POST("/x", RequirePermission(&stubAuth{perms: map[string]bool{}}, "currencies.manage"), okHandler) - - w := httptest.NewRecorder() - r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/x", nil)) - if w.Code != http.StatusOK { - t.Fatalf("granted status=%d", w.Code) - } - - w = httptest.NewRecorder() - r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/x", nil)) - if w.Code != http.StatusForbidden { - t.Fatalf("denied status=%d", w.Code) - } -} - -func TestAllowsBranchAndGuardUser(t *testing.T) { - gin.SetMode(gin.TestMode) - - w := httptest.NewRecorder() - c, _ := gin.CreateTestContext(w) - c.Request = httptest.NewRequest(http.MethodGet, "/", nil) - if !AllowsBranch(c, 1) { - t.Fatal("no scope should allow any branch") - } - if !GuardUser(c, 9) { - t.Fatal("no scope should allow any user") - } - - c.Set(contextBranchIDs, []int64{1, 2}) - if !AllowsBranch(c, 2) { - t.Fatal("expected branch 2 allowed") - } - if AllowsBranch(c, 9) { - t.Fatal("expected branch 9 denied") - } - - c.Set(contextService, &stubAuth{visible: true}) - if !GuardUser(c, 15) { - t.Fatal("expected visible user allowed") - } - c.Set(contextService, &stubAuth{visible: false}) - if GuardUser(c, 15) { - t.Fatal("expected hidden user denied") - } -} - -func TestGuardNewBranchAssignment(t *testing.T) { - gin.SetMode(gin.TestMode) - - w := httptest.NewRecorder() - c, _ := gin.CreateTestContext(w) - c.Request = httptest.NewRequest(http.MethodPost, "/", nil) - - // No branch scope (admin caller): always allowed. - if !GuardNewBranchAssignment(c, 42) { - t.Fatal("admin caller should be able to assign any user") - } - - // Operator scoped to branch 1. - c.Set(contextBranchIDs, []int64{1}) - - // Target has no existing branch: first-time assignment is allowed. - c.Set(contextService, &stubAuth{branches: nil}) - if !GuardNewBranchAssignment(c, 42) { - t.Fatal("unbranched target should be assignable") - } - - // Target already belongs to the operator's own branch: no-op re-assignment is allowed. - c.Set(contextService, &stubAuth{branches: []int64{1}}) - if !GuardNewBranchAssignment(c, 42) { - t.Fatal("target already in caller's branch should be assignable") - } - - // Target belongs to a different branch: reject cross-branch poaching. - c.Set(contextService, &stubAuth{branches: []int64{2}}) - if GuardNewBranchAssignment(c, 42) { - t.Fatal("target from a foreign branch must not be assignable") - } -} - -func TestBindBranchIDs(t *testing.T) { - gin.SetMode(gin.TestMode) - w := httptest.NewRecorder() - c, _ := gin.CreateTestContext(w) - c.Request = httptest.NewRequest(http.MethodGet, "/", nil) - - var dest []int64 - BindBranchIDs(c, &dest) - if dest != nil { - t.Fatalf("expected empty dest, got %v", dest) - } - - c.Set(contextBranchIDs, []int64{4, 5}) - BindBranchIDs(c, &dest) - if len(dest) != 2 || dest[0] != 4 { - t.Fatalf("dest=%v", dest) - } -} - -func TestClaimAndContextUserID(t *testing.T) { - if id, ok := claimUserID(jwt.MapClaims{"id": float64(12)}); !ok || id != 12 { - t.Fatalf("float id=%d ok=%v", id, ok) - } - if id, ok := claimUserID(jwt.MapClaims{"id": "8"}); !ok || id != 8 { - t.Fatalf("string id=%d ok=%v", id, ok) - } - if _, ok := claimUserID(jwt.MapClaims{"id": 0}); ok { - t.Fatal("zero id should fail") - } - - gin.SetMode(gin.TestMode) - w := httptest.NewRecorder() - c, _ := gin.CreateTestContext(w) - c.Set("id", "21") - if id, ok := parseContextUserID(c); !ok || id != 21 { - t.Fatalf("context id=%d ok=%v", id, ok) - } -} - -func TestBearerToken(t *testing.T) { - if got := bearerToken("Bearer abc"); got != "abc" { - t.Fatalf("got %q", got) - } - if got := bearerToken("abc"); got != "abc" { - t.Fatalf("got %q", got) - } -} - -func TestUserInBranchSQLIncludesNewOrderTables(t *testing.T) { - sql := UserInBranchSQL("c.user_id", 3) - for _, table := range []string{ - "branch_user", "card_orders", "loan_orders", "card_pin_orders", - "card_rekwizit_orders", "visa_master_payment_orders", "loan_paid_off_letters", - "card_balances", - } { - if !strings.Contains(sql, table) { - t.Errorf("missing %s", table) - } - } - if strings.Count(sql, "$3") != 8 { - t.Fatalf("$3 count=%d", strings.Count(sql, "$3")) - } -} - -func serveGuard(auth Authorizer, method, path, userID string, body []byte) int { - r := gin.New() - r.Use(func(c *gin.Context) { - c.Set("id", userID) - c.Next() - }) - r.Use(Guard(auth)) - handler := func(c *gin.Context) { c.Status(http.StatusOK) } - r.GET("/api/admin/*rest", handler) - r.POST("/api/admin/*rest", handler) - r.PUT("/api/admin/*rest", handler) - r.PATCH("/api/admin/*rest", handler) - r.DELETE("/api/admin/*rest", handler) - r.OPTIONS("/api/admin/*rest", handler) - - var req *http.Request - if body != nil { - req = httptest.NewRequest(method, path, bytes.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - } else { - req = httptest.NewRequest(method, path, nil) - } - w := httptest.NewRecorder() - r.ServeHTTP(w, req) - return w.Code -} - -func okHandler(c *gin.Context) { c.Status(http.StatusOK) } - -type stubAuth struct { - role string - guard string - roleErr error - branches []int64 - visible bool - visibleErr error - perms map[string]bool -} - -func (s *stubAuth) RoleLookup(context.Context, int64) (string, string, error) { - return s.role, s.guard, s.roleErr -} - -func (s *stubAuth) BranchIDs(context.Context, int64) ([]int64, error) { - return s.branches, nil -} - -func (s *stubAuth) HasPermission(_ context.Context, _ int64, code string) (bool, error) { - if s.perms == nil { - return true, nil - } - return s.perms[code], nil -} - -func (s *stubAuth) HasModuleAccess(_ context.Context, _ int64, module string) (bool, error) { - if s.perms == nil { - return true, nil - } - return s.perms[module], nil -} - -func (s *stubAuth) UserVisibleInBranches(context.Context, int64, []int64) (bool, error) { - return s.visible, s.visibleErr -} - -var _ Authorizer = (*stubAuth)(nil) -var _ Authorizer = (*Service)(nil) - -func TestEffectiveGuard(t *testing.T) { - tests := []struct { - code, guard, want string - }{ - {roleUser, guardWeb, guardWeb}, - {roleOperator, guardOperator, guardOperator}, - {"admin", guardAdmin, guardAdmin}, - {"customer", guardWeb, guardWeb}, - {"teller", guardOperator, guardOperator}, - {"auditor", guardAdmin, guardAdmin}, - {roleUser, "", guardWeb}, - {roleOperator, "", guardOperator}, - {"admin", "", guardAdmin}, - {"", "", guardWeb}, - {roleOperator, guardAdmin, guardOperator}, - {roleOperator, guardWeb, guardOperator}, - {"operatot", guardWeb, guardOperator}, - {"superadmin", guardWeb, guardAdmin}, - {"admin", guardWeb, guardAdmin}, - {"manager", guardOperator, guardAdmin}, - } - for _, tt := range tests { - if got := effectiveGuard(tt.code, tt.guard); got != tt.want { - t.Errorf("effectiveGuard(%q, %q)=%q want %q", tt.code, tt.guard, got, tt.want) - } - } -} - -func TestContainsInt64(t *testing.T) { - if !containsInt64([]int64{1, 2, 3}, 2) { - t.Fatal("expected 2") - } - if containsInt64([]int64{1, 2, 3}, 9) { - t.Fatal("did not expect 9") - } -} - -func TestHasBranchScope(t *testing.T) { - gin.SetMode(gin.TestMode) - w := httptest.NewRecorder() - c, _ := gin.CreateTestContext(w) - c.Request = httptest.NewRequest(http.MethodGet, "/", nil) - if HasBranchScope(c) { - t.Fatal("expected no scope") - } - c.Set(contextBranchIDs, []int64{1}) - if !HasBranchScope(c) { - t.Fatal("expected scope") - } -} - -func TestEnforceOwnWritesRewritesUserID(t *testing.T) { - gin.SetMode(gin.TestMode) - r := gin.New() - r.Use(func(c *gin.Context) { - c.Set("id", "7") - c.Next() - }) - r.Use(Guard(&stubAuth{role: roleUser})) - r.POST("/api/admin/cards", func(c *gin.Context) { - body, _ := io.ReadAll(c.Request.Body) - c.String(http.StatusOK, string(body)) - }) - - w := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/admin/cards", bytes.NewReader([]byte(`{"userId":99,"number":"1"}`))) - req.Header.Set("Content-Type", "application/json") - r.ServeHTTP(w, req) - if w.Code != http.StatusOK { - t.Fatalf("status=%d", w.Code) - } - if !strings.Contains(w.Body.String(), `"userId":7`) { - t.Fatalf("userId not rewritten: %s", w.Body.String()) - } - if !strings.Contains(w.Body.String(), `"user_id":7`) { - t.Fatalf("user_id not rewritten: %s", w.Body.String()) - } -} - -func TestEnforceOwnWritesRewritesCreatedByForCardBalances(t *testing.T) { - gin.SetMode(gin.TestMode) - r := gin.New() - r.Use(func(c *gin.Context) { - c.Set("id", "7") - c.Next() - }) - r.Use(Guard(&stubAuth{role: roleUser})) - r.POST("/api/admin/card-balances", func(c *gin.Context) { - body, _ := io.ReadAll(c.Request.Body) - c.String(http.StatusOK, string(body)) - }) - - w := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/admin/card-balances", bytes.NewReader([]byte(`{"createdBy":99,"cardNumber":"4111111111111111"}`))) - req.Header.Set("Content-Type", "application/json") - r.ServeHTTP(w, req) - if w.Code != http.StatusOK { - t.Fatalf("status=%d", w.Code) - } - if !strings.Contains(w.Body.String(), `"createdBy":7`) { - t.Fatalf("createdBy not rewritten: %s", w.Body.String()) - } - if !strings.Contains(w.Body.String(), `"created_by":7`) { - t.Fatalf("created_by not rewritten: %s", w.Body.String()) - } -} - -func TestGuardOwnedOwnScope(t *testing.T) { - gin.SetMode(gin.TestMode) - w := httptest.NewRecorder() - c, _ := gin.CreateTestContext(w) - c.Request = httptest.NewRequest(http.MethodGet, "/", nil) - c.Set(contextRole, roleUser) - c.Set(contextGuard, guardWeb) - c.Set("id", "7") - - own := int64(7) - if !GuardOwned(c, &own) { - t.Fatal("own record should pass") - } - other := int64(9) - if GuardOwned(c, &other) { - t.Fatal("foreign record should fail") - } - if GuardOwned(c, nil) { - t.Fatal("nil owner should fail") - } - if GuardUser(c, 9) { - t.Fatal("GuardUser should deny other users") - } - if !GuardUser(c, 7) { - t.Fatal("GuardUser should allow current user") - } -} - -func TestSkipRecordGuard(t *testing.T) { - gin.SetMode(gin.TestMode) - w := httptest.NewRecorder() - c, _ := gin.CreateTestContext(w) - c.Request = httptest.NewRequest(http.MethodGet, "/", nil) - - if !SkipRecordGuard(c) { - t.Fatal("admin with no role/branches should skip") - } - c.Set(contextRole, roleUser) - c.Set(contextGuard, guardWeb) - if SkipRecordGuard(c) { - t.Fatal("user must not skip record guard") - } - c.Set(contextRole, roleOperator) - c.Set(contextGuard, guardOperator) - c.Set(contextBranchIDs, []int64{1}) - if SkipRecordGuard(c) { - t.Fatal("operator with branches must not skip") - } -} diff --git a/internal/identity/rbac/perm/perm.go b/internal/identity/rbac/perm/perm.go new file mode 100644 index 0000000..36563e6 --- /dev/null +++ b/internal/identity/rbac/perm/perm.go @@ -0,0 +1,99 @@ +// Package perm is the single source of truth for permission codes. One code +// per module: holding it grants every action (read and write) in that module; +// which records the caller sees is decided by the role's scope, not here. +// +// The admin UI can only assign these codes to roles - it cannot create, +// rename or delete them. Sync writes this list into the permissions table on +// startup so role_permissions' foreign key always matches the code. +package perm + +import ( + "context" + + "online-back/pkg/client/postgresql" +) + +type Code string + +const ( + Dashboard Code = "dashboard" + Cards Code = "cards" + Loans Code = "loans" + Users Code = "users" + Roles Code = "roles" + Branches Code = "branches" + Provinces Code = "provinces" + Currencies Code = "currencies" + PaymentSettings Code = "payment-settings" + Backups Code = "backups" + ActivityLogs Code = "activity-logs" +) + +type Def struct { + Code Code `json:"code"` + Name string `json:"name"` +} + +// All is also the display order for the admin UI and the profile. +var All = []Def{ + {Dashboard, "Dashboard"}, + {Cards, "Cards"}, + {Loans, "Loans"}, + {Users, "Users"}, + {Roles, "Roles"}, + {Branches, "Branches"}, + {Provinces, "Provinces"}, + {Currencies, "Currencies"}, + {PaymentSettings, "Payment settings"}, + {Backups, "Backups"}, + {ActivityLogs, "Activity logs"}, +} + +var known = func() map[Code]struct{} { + m := make(map[Code]struct{}, len(All)) + for _, d := range All { + m[d.Code] = struct{}{} + } + return m +}() + +func Valid(code Code) bool { + _, ok := known[code] + return ok +} + +func Codes() []Code { + out := make([]Code, len(All)) + for i, d := range All { + out[i] = d.Code + } + return out +} + +// Sync upserts All into the permissions table and removes codes no longer +// in the catalog (role_permissions rows go with them via ON DELETE CASCADE). +func Sync(ctx context.Context, client postgresql.Client) error { + tx, err := client.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + + codes := make([]string, len(All)) + names := make([]string, len(All)) + for i, d := range All { + codes[i] = string(d.Code) + names[i] = d.Name + } + + if _, err := tx.Exec(ctx, ` + INSERT INTO permissions (code, name) + SELECT * FROM unnest($1::varchar[], $2::varchar[]) + ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name`, codes, names); err != nil { + return err + } + if _, err := tx.Exec(ctx, `DELETE FROM permissions WHERE NOT (code = ANY($1::varchar[]))`, codes); err != nil { + return err + } + return tx.Commit(ctx) +} diff --git a/internal/identity/rbac/principal.go b/internal/identity/rbac/principal.go new file mode 100644 index 0000000..297a8fb --- /dev/null +++ b/internal/identity/rbac/principal.go @@ -0,0 +1,141 @@ +package rbac + +import ( + "errors" + + "online-back/internal/identity/rbac/perm" +) + +// Scope decides which records a role's permissions apply to. It is the only +// data-visibility knob: "what can I do" is the permission list, "on whose +// records" is the scope. +type Scope string + +const ( + ScopeOwn Scope = "own" // only records the caller owns (clients) + ScopeBranch Scope = "branch" // records of the caller's branch_user branches + ScopeAll Scope = "all" // every branch +) + +func (s Scope) Valid() bool { + return s == ScopeOwn || s == ScopeBranch || s == ScopeAll +} + +func (s Scope) rank() int { + switch s { + case ScopeBranch: + return 1 + case ScopeAll: + return 2 + default: + return 0 + } +} + +// Principal is the caller as rbac sees it, loaded once per request (cached +// across requests, see Service.Load). Treat it as read-only. +type Principal struct { + UserID int64 + RoleID int64 + RoleCode string + Scope Scope + IsSuper bool + Perms map[perm.Code]struct{} + BranchIDs []int64 +} + +func (p *Principal) Can(code perm.Code) bool { + if p == nil { + return false + } + if p.IsSuper { + return true + } + _, ok := p.Perms[code] + return ok +} + +// PermCodes lists the caller's effective permissions in catalog order. +func (p *Principal) PermCodes() []perm.Code { + out := []perm.Code{} + for _, code := range perm.Codes() { + if p.Can(code) { + out = append(out, code) + } + } + return out +} + +// RoleInfo is what the grant/edit rules need to know about a role. +type RoleInfo struct { + ID int64 + Code string + Scope Scope + IsSuper bool + IsSystem bool + Perms []perm.Code +} + +var ( + ErrSuperOnly = errors.New("only a superadmin can grant or change a superadmin role") + ErrScopeTooWide = errors.New("role scope is wider than the caller's own scope") + ErrPermissionHeld = errors.New("role holds a permission the caller does not have") + ErrSystemRole = errors.New("system role scope cannot be changed") + ErrUnknownPerm = errors.New("unknown permission code") + ErrInvalidScope = errors.New("invalid scope") +) + +// CanGrant reports whether the caller may give target to a user - or, the +// same question, manage a user who already holds target. A caller can only +// hand out what they themselves hold: no wider scope, no permission they +// lack, and superadmin only from a superadmin. Own-scope roles (clients) +// skip the permission check: they only ever reach the holder's own records, +// so a cards-only operator can still register a cards+loans client. +func (p *Principal) CanGrant(target RoleInfo) error { + if p == nil { + return ErrSuperOnly + } + if p.IsSuper { + return nil + } + if target.IsSuper { + return ErrSuperOnly + } + if target.Scope.rank() > p.Scope.rank() { + return ErrScopeTooWide + } + if target.Scope == ScopeOwn { + return nil + } + for _, code := range target.Perms { + if !p.Can(code) { + return ErrPermissionHeld + } + } + return nil +} + +// CanSaveRole checks a role create (existing == nil) or update. The caller +// must be able to grant both the role as it is now and as it will be, so +// they can neither widen a role past their own rights nor strip one that is +// already out of their reach. +func (p *Principal) CanSaveRole(existing *RoleInfo, next RoleInfo) error { + if !next.Scope.Valid() { + return ErrInvalidScope + } + for _, code := range next.Perms { + if !perm.Valid(code) { + return ErrUnknownPerm + } + } + if existing != nil { + if existing.IsSystem && next.Scope != existing.Scope { + return ErrSystemRole + } + if err := p.CanGrant(*existing); err != nil { + return err + } + next.IsSuper = existing.IsSuper + } + return p.CanGrant(next) +} diff --git a/internal/identity/rbac/rbac_test.go b/internal/identity/rbac/rbac_test.go new file mode 100644 index 0000000..159a90f --- /dev/null +++ b/internal/identity/rbac/rbac_test.go @@ -0,0 +1,373 @@ +package rbac + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "online-back/internal/identity/rbac/perm" + + "github.com/gin-gonic/gin" +) + +func principal(scope Scope, codes ...perm.Code) *Principal { + p := &Principal{UserID: 7, RoleID: 70, Scope: scope, Perms: map[perm.Code]struct{}{}} + for _, code := range codes { + p.Perms[code] = struct{}{} + } + if scope == ScopeBranch { + p.BranchIDs = []int64{3} + } + return p +} + +type fakeAuthorizer struct { + principals map[int64]*Principal + visible bool + loadErr error +} + +func (f *fakeAuthorizer) Load(_ context.Context, id int64) (*Principal, error) { + return f.principals[id], f.loadErr +} +func (f *fakeAuthorizer) BranchIDs(context.Context, int64) ([]int64, error) { return nil, nil } +func (f *fakeAuthorizer) UserVisibleInBranches(context.Context, int64, []int64) (bool, error) { + return f.visible, nil +} + +// runPolicy sends one request through p's group middleware with caller +// already in the context (as Guard would leave it). +func runPolicy(t *testing.T, p Policy, caller *Principal, method, target, body string) (int, *http.Request) { + t.Helper() + gin.SetMode(gin.TestMode) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(method, target, strings.NewReader(body)) + if caller != nil { + c.Set(contextPrincipal, caller) + } + c.Set(contextService, &fakeAuthorizer{visible: false}) + p.handler()(c) + if c.IsAborted() { + return w.Code, c.Request + } + return http.StatusOK, c.Request +} + +func TestCan(t *testing.T) { + p := principal(ScopeAll, perm.Loans) + if !p.Can(perm.Loans) || p.Can(perm.Cards) { + t.Fatal("Can should follow the permission set") + } + if !(&Principal{IsSuper: true}).Can(perm.Backups) { + t.Fatal("superadmin holds every permission") + } + if (*Principal)(nil).Can(perm.Loans) { + t.Fatal("nil principal holds nothing") + } +} + +func TestPermCodesFollowCatalogOrder(t *testing.T) { + p := principal(ScopeAll, perm.Loans, perm.Dashboard, perm.Cards) + got := p.PermCodes() + want := []perm.Code{perm.Dashboard, perm.Cards, perm.Loans} + if len(got) != len(want) { + t.Fatalf("got %v", got) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("got %v, want %v", got, want) + } + } +} + +func TestCanGrant(t *testing.T) { + admin := principal(ScopeAll, perm.Cards, perm.Loans, perm.Users) + manager := principal(ScopeBranch, perm.Cards, perm.Users) + + cases := []struct { + name string + caller *Principal + target RoleInfo + want error + }{ + {"super grants anything", &Principal{IsSuper: true, Scope: ScopeAll}, RoleInfo{IsSuper: true, Scope: ScopeAll}, nil}, + {"admin cannot grant superadmin", admin, RoleInfo{IsSuper: true, Scope: ScopeAll}, ErrSuperOnly}, + {"admin grants loan head", admin, RoleInfo{Scope: ScopeAll, Perms: []perm.Code{perm.Loans}}, nil}, + {"admin lacks backups", admin, RoleInfo{Scope: ScopeAll, Perms: []perm.Code{perm.Backups}}, ErrPermissionHeld}, + {"manager cannot grant all scope", manager, RoleInfo{Scope: ScopeAll, Perms: []perm.Code{perm.Cards}}, ErrScopeTooWide}, + {"manager grants card operator", manager, RoleInfo{Scope: ScopeBranch, Perms: []perm.Code{perm.Cards}}, nil}, + {"manager lacks loans", manager, RoleInfo{Scope: ScopeBranch, Perms: []perm.Code{perm.Loans}}, ErrPermissionHeld}, + {"own-scope role skips the permission check", manager, RoleInfo{Scope: ScopeOwn, Perms: []perm.Code{perm.Cards, perm.Loans}}, nil}, + {"nil caller", nil, RoleInfo{Scope: ScopeOwn}, ErrSuperOnly}, + } + for _, tc := range cases { + if got := tc.caller.CanGrant(tc.target); !errors.Is(got, tc.want) { + t.Errorf("%s: got %v, want %v", tc.name, got, tc.want) + } + } +} + +func TestCanSaveRole(t *testing.T) { + admin := principal(ScopeAll, perm.Cards, perm.Loans, perm.Roles) + super := &Principal{IsSuper: true, Scope: ScopeAll} + + if err := admin.CanSaveRole(nil, RoleInfo{Scope: "global"}); !errors.Is(err, ErrInvalidScope) { + t.Errorf("invalid scope: got %v", err) + } + if err := admin.CanSaveRole(nil, RoleInfo{Scope: ScopeAll, Perms: []perm.Code{"nope"}}); !errors.Is(err, ErrUnknownPerm) { + t.Errorf("unknown perm: got %v", err) + } + system := &RoleInfo{Scope: ScopeOwn, IsSystem: true} + if err := super.CanSaveRole(system, RoleInfo{Scope: ScopeBranch}); !errors.Is(err, ErrSystemRole) { + t.Errorf("system role scope change: got %v", err) + } + if err := super.CanSaveRole(system, RoleInfo{Scope: ScopeOwn, Perms: []perm.Code{perm.Cards}}); err != nil { + t.Errorf("system role perms may change: got %v", err) + } + superRole := &RoleInfo{Scope: ScopeAll, IsSuper: true, IsSystem: true} + if err := admin.CanSaveRole(superRole, RoleInfo{Scope: ScopeAll}); !errors.Is(err, ErrSuperOnly) { + t.Errorf("admin editing superadmin role: got %v", err) + } + // A role already out of reach cannot be stripped either. + backups := &RoleInfo{Scope: ScopeAll, Perms: []perm.Code{perm.Backups}} + if err := admin.CanSaveRole(backups, RoleInfo{Scope: ScopeAll}); !errors.Is(err, ErrPermissionHeld) { + t.Errorf("admin editing role with backups: got %v", err) + } +} + +func TestPolicyMatrix(t *testing.T) { + client := principal(ScopeOwn, perm.Cards, perm.Loans) + operator := principal(ScopeBranch, perm.Cards) + loanHead := principal(ScopeAll, perm.Loans) + + cases := []struct { + name string + policy Policy + caller *Principal + method string + want int + }{ + {"client reads own cards", Require(perm.Cards), client, http.MethodGet, 200}, + {"operator lacks loans", Require(perm.Loans), operator, http.MethodGet, 403}, + {"loan head reads loans", Require(perm.Loans), loanHead, http.MethodGet, 200}, + {"loan head has no cards", Require(perm.Cards), loanHead, http.MethodGet, 403}, + {"client blocked from staff module", RequireStaff(perm.Cards), client, http.MethodGet, 403}, + {"operator on staff module", RequireStaff(perm.Cards), operator, http.MethodGet, 200}, + {"client reads catalog", Catalog(perm.Loans), client, http.MethodGet, 200}, + {"client cannot write catalog", Catalog(perm.Loans), client, http.MethodPost, 403}, + {"operator cannot write loans catalog", Catalog(perm.Loans), operator, http.MethodPost, 403}, + {"loan head writes loans catalog", Catalog(perm.Loans), loanHead, http.MethodPost, 200}, + {"staff read for operator", StaffRead(perm.PaymentSettings), operator, http.MethodGet, 200}, + {"staff read blocks client", StaffRead(perm.PaymentSettings), client, http.MethodGet, 403}, + {"staff write needs perm", StaffRead(perm.PaymentSettings), operator, http.MethodPut, 403}, + {"staff blocks client", Staff(), client, http.MethodGet, 403}, + {"authenticated lets client in", Authenticated(), client, http.MethodPut, 200}, + {"no principal", Authenticated(), nil, http.MethodGet, 403}, + } + for _, tc := range cases { + if got, _ := runPolicy(t, tc.policy, tc.caller, tc.method, "/api/admin/x", ""); got != tc.want { + t.Errorf("%s: got %d, want %d", tc.name, got, tc.want) + } + } +} + +func TestBranchScopeWithoutBranchesIsDenied(t *testing.T) { + p := principal(ScopeBranch, perm.Cards) + p.BranchIDs = nil + if got, _ := runPolicy(t, Require(perm.Cards), p, http.MethodGet, "/api/admin/cards", ""); got != 403 { + t.Fatalf("got %d, want 403", got) + } +} + +func TestOwnScopePinsQueryAndBody(t *testing.T) { + client := principal(ScopeOwn, perm.Cards) + + _, req := runPolicy(t, Require(perm.Cards), client, http.MethodGet, "/api/admin/card-orders?user_id=99", "") + if req.URL.Query().Get("user_id") != "7" || req.URL.Query().Get("created_by") != "7" { + t.Fatalf("list not pinned to caller: %s", req.URL.RawQuery) + } + + _, req = runPolicy(t, Require(perm.Cards), client, http.MethodPost, "/api/admin/card-orders", `{"userId":99,"branchId":1}`) + body, _ := io.ReadAll(req.Body) + var payload map[string]interface{} + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + for _, key := range []string{"userId", "user_id", "createdBy", "created_by"} { + if payload[key] != float64(7) { + t.Fatalf("%s = %v, want 7", key, payload[key]) + } + } + if payload["branchId"] != float64(1) { + t.Fatal("other fields must survive the rewrite") + } +} + +func TestBranchScopeWrites(t *testing.T) { + operator := principal(ScopeBranch, perm.Cards) + cases := []struct { + name string + method string + body string + want int + }{ + {"own branch", http.MethodPost, `{"branchId":3}`, 200}, + {"other branch", http.MethodPost, `{"branchId":4}`, 403}, + {"create for new customer", http.MethodPost, `{"branchId":3,"userId":50}`, 200}, + {"reassign to invisible user", http.MethodPut, `{"branchId":3,"userId":50}`, 403}, + {"no body", http.MethodPut, ``, 200}, + } + for _, tc := range cases { + if got, _ := runPolicy(t, Require(perm.Cards), operator, tc.method, "/api/admin/card-orders/1", tc.body); got != tc.want { + t.Errorf("%s: got %d, want %d", tc.name, got, tc.want) + } + } +} + +func TestRegistryLookupAndVerify(t *testing.T) { + routes.reset() + defer routes.reset() + gin.SetMode(gin.TestMode) + + engine := gin.New() + admin := engine.Group("/api/admin") + Group(admin, "/users", RequireStaff(perm.Users)).GET("/:id", func(*gin.Context) {}) + Group(admin, "/users/clients", Staff()).GET("", func(*gin.Context) {}) + Group(admin, "/login", Public()).POST("", func(*gin.Context) {}) + + if p, _ := routes.lookup("/api/admin/users/clients"); p.name != "staff" { + t.Fatalf("longest prefix should win, got %s", p.name) + } + if p, _ := routes.lookup("/api/admin/users/:id"); p.name != "require-staff:users" { + t.Fatalf("got %s", p.name) + } + if _, ok := routes.lookup("/api/admin/usersx"); ok { + t.Fatal("prefix must match whole path segments") + } + if err := VerifyRoutes(engine.Routes(), "/api/admin"); err != nil { + t.Fatalf("all routes declared: %v", err) + } + + admin.GET("/forgotten", func(*gin.Context) {}) + err := VerifyRoutes(engine.Routes(), "/api/admin") + if err == nil || !strings.Contains(err.Error(), "GET /api/admin/forgotten") { + t.Fatalf("undeclared route must be reported, got %v", err) + } +} + +func TestRegistryRejectsConflictingPolicies(t *testing.T) { + routes.reset() + defer routes.reset() + engine := gin.New() + Group(engine.Group("/api/admin"), "/cards", Require(perm.Cards)) + Group(engine.Group("/api/admin"), "/cards", Require(perm.Cards)) // same policy twice is fine + defer func() { + if recover() == nil { + t.Fatal("expected panic for conflicting policy") + } + }() + Group(engine.Group("/api/admin"), "/cards", Catalog(perm.Cards)) +} + +func TestGuardEndToEnd(t *testing.T) { + routes.reset() + defer routes.reset() + gin.SetMode(gin.TestMode) + + auth := &fakeAuthorizer{principals: map[int64]*Principal{7: principal(ScopeAll, perm.Loans)}} + engine := gin.New() + admin := engine.Group("/api/admin") + // Stand-in for JwtTokenCheck: Guard reads the id from the context first. + admin.Use(func(c *gin.Context) { + if id := c.GetHeader("X-User"); id != "" { + c.Set("id", id) + } + }, Guard(auth)) + ok := func(c *gin.Context) { c.Status(http.StatusOK) } + admin.Group("/loan-orders", Require(perm.Loans).handler()).GET("", ok) + routes.add("/api/admin/loan-orders", Require(perm.Loans)) + admin.Group("/cards", Require(perm.Cards).handler()).GET("", ok) + routes.add("/api/admin/cards", Require(perm.Cards)) + admin.GET("/undeclared", ok) + + do := func(path, user string) int { + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, path, &bytes.Buffer{}) + if user != "" { + req.Header.Set("X-User", user) + } + engine.ServeHTTP(w, req) + return w.Code + } + if got := do("/api/admin/loan-orders", "7"); got != 200 { + t.Errorf("loan head on loans: %d", got) + } + if got := do("/api/admin/cards", "7"); got != 403 { + t.Errorf("loan head on cards: %d", got) + } + if got := do("/api/admin/loan-orders", "8"); got != 403 { + t.Errorf("unknown user: %d", got) + } + if got := do("/api/admin/undeclared", "7"); got != 403 { + t.Errorf("undeclared route must be denied: %d", got) + } + + auth.loadErr = errors.New("db down") + if got := do("/api/admin/loan-orders", "7"); got != 500 { + t.Errorf("load error: %d", got) + } +} + +func TestScopeHelpers(t *testing.T) { + gin.SetMode(gin.TestMode) + ctx := func(p *Principal) *gin.Context { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodGet, "/", nil) + c.Set(contextPrincipal, p) + c.Set(contextService, &fakeAuthorizer{visible: true}) + return c + } + + all := ctx(principal(ScopeAll)) + if !HasAllScope(all) || !SkipRecordGuard(all) || BranchIDsFrom(all) != nil || !AllowsBranch(all, 99) { + t.Error("all scope sees everything") + } + + branch := ctx(principal(ScopeBranch)) + if !HasBranchScope(branch) || SkipRecordGuard(branch) || AllowsBranch(branch, 99) || !AllowsBranch(branch, 3) { + t.Error("branch scope is limited to its branches") + } + var ids []int64 + BindBranchIDs(branch, &ids) + if len(ids) != 1 || ids[0] != 3 { + t.Errorf("BindBranchIDs = %v", ids) + } + + own := ctx(principal(ScopeOwn)) + if !IsOwnScope(own) || SkipRecordGuard(own) { + t.Error("own scope must be guarded") + } + mine, other := int64(7), int64(8) + if !GuardOwned(own, &mine) || GuardOwned(ctx(principal(ScopeOwn)), &other) { + t.Error("GuardOwned follows the owner id") + } + if id, ok := CurrentUserID(own); !ok || id != 7 { + t.Errorf("CurrentUserID = %d, %v", id, ok) + } +} + +func TestUserInBranchSQLIncludesOrderTables(t *testing.T) { + sql := UserInBranchSQL("u.id", 2) + for _, table := range []string{"branch_user", "card_orders", "loan_orders", "card_pin_orders", "card_rekwizit_orders", "visa_master_payment_orders", "loan_paid_off_letters", "card_balances"} { + if !strings.Contains(sql, table) { + t.Errorf("UserInBranchSQL missing %s", table) + } + } +} diff --git a/internal/identity/rbac/registry.go b/internal/identity/rbac/registry.go new file mode 100644 index 0000000..91f4f97 --- /dev/null +++ b/internal/identity/rbac/registry.go @@ -0,0 +1,126 @@ +package rbac + +import ( + "fmt" + "net/http" + "path" + "sort" + "strings" + "sync" + + "online-back/internal/appresult" + + "github.com/gin-gonic/gin" +) + +type ruleKind int + +const ( + rulePublic ruleKind = iota // no token needed + ruleAuthenticated // any logged-in user + ruleStaff // any logged-in user whose scope is not own + rulePermission // perm required (+ scope enforcement) +) + +type rule struct { + kind ruleKind + perm string + staffOnly bool +} + +// Policy is the access rule of a route group: one rule for reads (GET/HEAD) +// and one for writes. Build it with Public, Authenticated, Staff, Require, +// RequireStaff, Catalog or StaffRead. +type Policy struct { + name string + read rule + write rule +} + +func (p Policy) String() string { return p.name } + +func (p Policy) public() bool { return p.read.kind == rulePublic && p.write.kind == rulePublic } + +func (p Policy) ruleFor(method string) rule { + if method == http.MethodGet || method == http.MethodHead { + return p.read + } + return p.write +} + +// registry maps full route prefixes (e.g. "/api/admin/card-orders") to the +// policy declared for them. Guard resolves a request's policy from it by +// longest prefix, and VerifyRoutes fails startup for any route with none. +type registry struct { + mu sync.RWMutex + policies map[string]Policy +} + +var routes = ®istry{policies: make(map[string]Policy)} + +func (r *registry) add(prefix string, p Policy) { + r.mu.Lock() + defer r.mu.Unlock() + if existing, ok := r.policies[prefix]; ok && existing.name != p.name { + panic(fmt.Sprintf("rbac: %s registered with policy %s and %s", prefix, existing.name, p.name)) + } + r.policies[prefix] = p +} + +func (r *registry) lookup(fullPath string) (Policy, bool) { + r.mu.RLock() + defer r.mu.RUnlock() + best := "" + var found Policy + ok := false + for prefix, p := range r.policies { + if (fullPath == prefix || strings.HasPrefix(fullPath, prefix+"/")) && len(prefix) >= len(best) { + best, found, ok = prefix, p, true + } + } + return found, ok +} + +func (r *registry) reset() { + r.mu.Lock() + r.policies = make(map[string]Policy) + r.mu.Unlock() +} + +// Group creates a route group under parent at relativePath and declares its +// policy. Every /api/admin route must be registered through Group - see +// VerifyRoutes. +func Group(parent *gin.RouterGroup, relativePath string, p Policy) *gin.RouterGroup { + full := joinPath(parent.BasePath(), relativePath) + routes.add(full, p) + if p.public() { + return parent.Group(relativePath) + } + return parent.Group(relativePath, appresult.JwtTokenCheck(), p.handler()) +} + +// VerifyRoutes returns an error naming every route under prefix that has no +// policy. Call it after all handlers are registered. +func VerifyRoutes(all gin.RoutesInfo, prefix string) error { + var missing []string + for _, route := range all { + if route.Path != prefix && !strings.HasPrefix(route.Path, prefix+"/") { + continue + } + if _, ok := routes.lookup(route.Path); !ok { + missing = append(missing, route.Method+" "+route.Path) + } + } + if len(missing) == 0 { + return nil + } + sort.Strings(missing) + return fmt.Errorf("rbac: routes without a policy (use rbac.Group): %s", strings.Join(missing, ", ")) +} + +func joinPath(base, rel string) string { + if rel == "" { + return strings.TrimSuffix(base, "/") + } + return strings.TrimSuffix(path.Join(base, rel), "/") +} diff --git a/internal/identity/rbac/roleinfo.go b/internal/identity/rbac/roleinfo.go new file mode 100644 index 0000000..401749c --- /dev/null +++ b/internal/identity/rbac/roleinfo.go @@ -0,0 +1,36 @@ +package rbac + +import ( + "errors" + + "online-back/internal/identity/rbac/perm" + "online-back/pkg/repository/genericrepo" + + "github.com/jackc/pgx/v4" +) + +// RoleInfoSelect selects the columns ScanRoleInfo reads from roles r; append +// the WHERE clause (it must keep r.deleted_at IS NULL). +const RoleInfoSelect = `SELECT r.id, r.code, r.scope, r.is_super, r.is_system, + ARRAY(SELECT rp.permission_code::text FROM role_permissions rp WHERE rp.role_id = r.id ORDER BY 1) + FROM roles r ` + +// ScanRoleInfo scans one RoleInfoSelect row; a missing row is (nil, nil). +func ScanRoleInfo(row genericrepo.Scanner) (*RoleInfo, error) { + var info RoleInfo + var scope string + var codes []string + err := row.Scan(&info.ID, &info.Code, &scope, &info.IsSuper, &info.IsSystem, &codes) + if errors.Is(err, pgx.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + info.Scope = Scope(scope) + info.Perms = make([]perm.Code, len(codes)) + for i, code := range codes { + info.Perms[i] = perm.Code(code) + } + return &info, nil +} diff --git a/internal/identity/rbac/scope.go b/internal/identity/rbac/scope.go index 1073fd5..54c1e37 100644 --- a/internal/identity/rbac/scope.go +++ b/internal/identity/rbac/scope.go @@ -5,61 +5,69 @@ import ( "net/http" "online-back/internal/appresult" + "online-back/internal/identity/rbac/perm" "github.com/gin-gonic/gin" ) -// The three valid guard names. Use these constants when validating -// the guardName field in role/permission DTOs. -const ( - GuardWeb = guardWeb - GuardOperator = guardOperator - GuardAdmin = guardAdmin -) - -const ( - contextBranchIDs = "branchIds" - contextService = "rbacService" -) - -func BranchIDsFrom(c *gin.Context) []int64 { - raw, ok := c.Get(contextBranchIDs) +// PrincipalFrom returns the caller loaded by Guard, or nil on public routes. +func PrincipalFrom(c *gin.Context) *Principal { + raw, ok := c.Get(contextPrincipal) if !ok { return nil } - ids, _ := raw.([]int64) - return ids + p, _ := raw.(*Principal) + return p +} + +func serviceFrom(c *gin.Context) Authorizer { + raw, ok := c.Get(contextService) + if !ok { + return nil + } + service, _ := raw.(Authorizer) + return service +} + +// Can reports whether the caller holds code (always true for superadmin). +func Can(c *gin.Context, code perm.Code) bool { + return PrincipalFrom(c).Can(code) +} + +// BranchIDsFrom returns the caller's branches when their scope is branch, +// nil otherwise (all and own scopes are not narrowed by branch). +func BranchIDsFrom(c *gin.Context) []int64 { + p := PrincipalFrom(c) + if p == nil || p.Scope != ScopeBranch { + return nil + } + return p.BranchIDs } func HasBranchScope(c *gin.Context) bool { return len(BranchIDsFrom(c)) > 0 } -func RoleFrom(c *gin.Context) string { - raw, _ := c.Get(contextRole) - role, _ := raw.(string) - return role -} - -func GuardFrom(c *gin.Context) string { - raw, _ := c.Get(contextGuard) - guard, _ := raw.(string) - return guard -} - func IsOwnScope(c *gin.Context) bool { - return GuardFrom(c) == guardWeb + p := PrincipalFrom(c) + return p != nil && p.Scope == ScopeOwn } -func IsAdminGuard(c *gin.Context) bool { - return GuardFrom(c) == guardAdmin +func HasAllScope(c *gin.Context) bool { + p := PrincipalFrom(c) + return p != nil && p.Scope == ScopeAll } +// SkipRecordGuard: all-scope callers see every record, so handlers can skip +// the extra owner/branch lookup. func SkipRecordGuard(c *gin.Context) bool { - return !HasBranchScope(c) && !IsOwnScope(c) + return HasAllScope(c) } func CurrentUserID(c *gin.Context) (int64, bool) { + if p := PrincipalFrom(c); p != nil { + return p.UserID, true + } return parseContextUserID(c) } @@ -116,12 +124,7 @@ func GuardNewBranchAssignment(c *gin.Context, targetUserID int64) bool { if !HasBranchScope(c) { return true } - raw, ok := c.Get(contextService) - if !ok { - c.JSON(http.StatusForbidden, appresult.ErrForbidden) - return false - } - service, _ := raw.(Authorizer) + service := serviceFrom(c) if service == nil { c.JSON(http.StatusForbidden, appresult.ErrForbidden) return false @@ -149,12 +152,7 @@ func GuardUser(c *gin.Context, userID int64) bool { if len(ids) == 0 { return true } - raw, ok := c.Get(contextService) - if !ok { - c.JSON(http.StatusForbidden, appresult.ErrForbidden) - return false - } - service, _ := raw.(Authorizer) + service := serviceFrom(c) if service == nil { c.JSON(http.StatusForbidden, appresult.ErrForbidden) return false diff --git a/internal/identity/rbac/service.go b/internal/identity/rbac/service.go index d86b108..9df43f2 100644 --- a/internal/identity/rbac/service.go +++ b/internal/identity/rbac/service.go @@ -3,82 +3,137 @@ package rbac import ( "context" "errors" + "sync" + "time" + "online-back/internal/identity/rbac/perm" "online-back/pkg/client/postgresql" "github.com/jackc/pgx/v4" ) -type Service struct { - client postgresql.Client -} - -func NewService(client postgresql.Client) *Service { - return &Service{client: client} -} - -// Authorizer is the lookup Guard, RequirePermission and GuardUser need. +// Authorizer is what the middleware and the scope helpers need. type Authorizer interface { - RoleLookup(ctx context.Context, userID int64) (code, guardName string, err error) + // Load returns the caller's principal, or nil when the user or their + // role no longer exists. + Load(ctx context.Context, userID int64) (*Principal, error) BranchIDs(ctx context.Context, userID int64) ([]int64, error) - HasPermission(ctx context.Context, userID int64, code string) (bool, error) - HasModuleAccess(ctx context.Context, userID int64, module string) (bool, error) UserVisibleInBranches(ctx context.Context, userID int64, branchIDs []int64) (bool, error) } -// HasPermission checks whether the user's role grants the exact permission code. -func (s *Service) HasPermission(ctx context.Context, userID int64, code string) (bool, error) { - const query = ` - SELECT EXISTS ( - SELECT 1 - 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 AND ru.deleted_at IS NULL AND pr.deleted_at IS NULL - )` +const ( + principalTTL = time.Minute + versionCheckEvery = 2 * time.Second + principalCacheLimit = 10000 +) - var granted bool - if err := s.client.QueryRow(ctx, query, userID, code).Scan(&granted); err != nil { - return false, err - } - return granted, nil +type cachedPrincipal struct { + principal *Principal + loadedAt time.Time } -// HasModuleAccess is HasPermission matched against a permission's module -// instead of its exact code, so a new permission code created under an -// existing module (e.g. "loans") is recognized without a code change here. -func (s *Service) HasModuleAccess(ctx context.Context, userID int64, module string) (bool, error) { - const query = ` - SELECT EXISTS ( - SELECT 1 - 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.module = $2 AND ru.deleted_at IS NULL AND pr.deleted_at IS NULL - )` +// Service loads principals and caches them per user. The rbac_version row +// is bumped by DB triggers whenever roles, role_permissions, users.role_id +// or branch_user change; seeing a new version drops the whole cache, so a +// permission change takes effect within versionCheckEvery. +type Service struct { + client postgresql.Client + now func() time.Time - var granted bool - if err := s.client.QueryRow(ctx, query, userID, module).Scan(&granted); err != nil { - return false, err - } - return granted, nil + mu sync.Mutex + cache map[int64]cachedPrincipal + version int64 + checkedAt time.Time } -func (s *Service) RoleLookup(ctx context.Context, userID int64) (string, string, error) { - const query = ` - SELECT r.code, r.guard_name - FROM role_user ru - JOIN roles r ON r.id = ru.role_id - WHERE ru.user_id = $1 AND ru.deleted_at IS NULL AND r.deleted_at IS NULL - ORDER BY ru.id - LIMIT 1` +func NewService(client postgresql.Client) *Service { + return &Service{client: client, now: time.Now, cache: make(map[int64]cachedPrincipal)} +} - var code, guardName string - err := s.client.QueryRow(ctx, query, userID).Scan(&code, &guardName) +func (s *Service) Load(ctx context.Context, userID int64) (*Principal, error) { + if err := s.syncVersion(ctx); err != nil { + return nil, err + } + + now := s.now() + s.mu.Lock() + entry, ok := s.cache[userID] + s.mu.Unlock() + if ok && now.Sub(entry.loadedAt) < principalTTL { + return entry.principal, nil + } + + p, err := s.loadPrincipal(ctx, userID) + if err != nil || p == nil { + return p, err + } + + s.mu.Lock() + if len(s.cache) >= principalCacheLimit { + s.cache = make(map[int64]cachedPrincipal) + } + s.cache[userID] = cachedPrincipal{principal: p, loadedAt: now} + s.mu.Unlock() + return p, nil +} + +func (s *Service) syncVersion(ctx context.Context) error { + now := s.now() + s.mu.Lock() + fresh := now.Sub(s.checkedAt) < versionCheckEvery + s.mu.Unlock() + if fresh { + return nil + } + + var version int64 + if err := s.client.QueryRow(ctx, `SELECT version FROM rbac_version WHERE id = 1`).Scan(&version); err != nil { + return err + } + + s.mu.Lock() + if version != s.version { + s.cache = make(map[int64]cachedPrincipal) + s.version = version + } + s.checkedAt = now + s.mu.Unlock() + return nil +} + +const principalQuery = ` + SELECT r.id, r.code, r.scope, r.is_super, + ARRAY(SELECT rp.permission_code::text FROM role_permissions rp WHERE rp.role_id = r.id), + ARRAY( + SELECT bu.branch_id + FROM branch_user bu + JOIN branches b ON b.id = bu.branch_id AND b.deleted_at IS NULL + WHERE bu.user_id = u.id AND bu.deleted_at IS NULL + ORDER BY bu.id + ) + FROM users u + JOIN roles r ON r.id = u.role_id AND r.deleted_at IS NULL + WHERE u.id = $1 AND u.deleted_at IS NULL` + +func (s *Service) loadPrincipal(ctx context.Context, userID int64) (*Principal, error) { + p := &Principal{UserID: userID} + var scope string + var codes []string + err := s.client.QueryRow(ctx, principalQuery, userID).Scan( + &p.RoleID, &p.RoleCode, &scope, &p.IsSuper, &codes, &p.BranchIDs, + ) if errors.Is(err, pgx.ErrNoRows) { - return "", "", nil + return nil, nil } - return code, guardName, err + if err != nil { + return nil, err + } + p.Scope = Scope(scope) + p.Perms = make(map[perm.Code]struct{}, len(codes)) + for _, code := range codes { + p.Perms[perm.Code(code)] = struct{}{} + } + return p, nil } func (s *Service) BranchIDs(ctx context.Context, userID int64) ([]int64, error) { diff --git a/internal/identity/role/db/postgresql.go b/internal/identity/role/db/postgresql.go index addbbd8..b7d54c1 100644 --- a/internal/identity/role/db/postgresql.go +++ b/internal/identity/role/db/postgresql.go @@ -4,99 +4,184 @@ import ( "context" "errors" "fmt" - "strings" + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/identity/role" "online-back/internal/shared" "online-back/pkg/client/postgresql" "online-back/pkg/logging" "online-back/pkg/repository/genericrepo" + "github.com/jackc/pgconn" "github.com/jackc/pgx/v4" ) type repository struct { - client postgresql.Client - generic *genericrepo.Repository[role.RoleDTO] - logger *logging.Logger + client postgresql.Client + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) role.Repository { - return &repository{ - client: client, - generic: genericrepo.New(client, "roles r", roleColumns, scanRole), - logger: logger, - } + return &repository{client: client, logger: logger} } -const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated_at` - -const roleReturningColumns = `id, code, name, guard_name, created_at, updated_at` +const roleColumns = `r.id, r.code, r.name, r.scope, r.is_super, r.is_system, + ARRAY(SELECT rp.permission_code::text FROM role_permissions rp WHERE rp.role_id = r.id ORDER BY 1), + (SELECT COUNT(*) FROM users u WHERE u.role_id = r.id AND u.deleted_at IS NULL), + r.created_at, r.updated_at` func (r *repository) List(ctx context.Context, filter role.ListFilter) (role.ListRoleDTO, error) { - whereClause, args := buildListQuery(filter) + where := ` WHERE r.deleted_at IS NULL` + var args []interface{} + if filter.RoleName != "" { + args = append(args, shared.LikePattern(filter.RoleName)) + where += fmt.Sprintf(` AND (r.name ILIKE $%d OR r.code ILIKE $%d)`, len(args), len(args)) + } - items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") - if err != nil { + var count int64 + if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM roles r`+where, args...).Scan(&count); err != nil { return role.ListRoleDTO{}, err } + args = append(args, filter.Limit, (filter.Page-1)*filter.Limit) + query := fmt.Sprintf(`SELECT %s FROM roles r%s ORDER BY r.id LIMIT $%d OFFSET $%d`, + roleColumns, where, len(args)-1, len(args)) + rows, err := r.client.Query(ctx, query, args...) + if err != nil { + return role.ListRoleDTO{}, err + } + defer rows.Close() + + items := []role.RoleDTO{} + for rows.Next() { + item, err := scanRole(rows) + if err != nil { + return role.ListRoleDTO{}, err + } + items = append(items, item) + } + if err := rows.Err(); err != nil { + return role.ListRoleDTO{}, err + } return role.ListRoleDTO{Count: count, Roles: items}, nil } -func buildListQuery(filter role.ListFilter) (whereClause string, args []interface{}) { - var conditions []string - if filter.RoleName != "" { - args = append(args, shared.LikePattern(filter.RoleName)) - n := len(args) - conditions = append(conditions, fmt.Sprintf(`r.name ILIKE $%d`, n)) - } - - if len(conditions) == 0 { - return "", args - } - - return " WHERE " + strings.Join(conditions, " AND "), args +func (r *repository) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) { + return getByID(ctx, r.client, id) } -func (r *repository) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) { - return r.generic.GetByID(ctx, id) +type querier interface { + QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row +} + +func getByID(ctx context.Context, q querier, id int64) (role.RoleDTO, error) { + return scanRole(q.QueryRow(ctx, `SELECT `+roleColumns+` FROM roles r WHERE r.id = $1 AND r.deleted_at IS NULL`, id)) } func (r *repository) Create(ctx context.Context, dto role.CreateRoleDTO) (role.RoleDTO, error) { - query := fmt.Sprintf(` - INSERT INTO roles (code, name, guard_name) - VALUES ($1, $2, $3) - RETURNING %s`, roleReturningColumns) + tx, err := r.client.Begin(ctx) + if err != nil { + return role.RoleDTO{}, err + } + defer tx.Rollback(ctx) - return scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName)) + var id int64 + err = tx.QueryRow(ctx, `INSERT INTO roles (code, name, scope) VALUES ($1, $2, $3) RETURNING id`, + dto.Code, dto.Name, string(dto.Scope)).Scan(&id) + if isUniqueViolation(err) { + return role.RoleDTO{}, role.ErrDuplicateCode + } + if err != nil { + return role.RoleDTO{}, err + } + if err := setPermissions(ctx, tx, id, dto.Permissions); err != nil { + return role.RoleDTO{}, err + } + + item, err := getByID(ctx, tx, id) + if err != nil { + return role.RoleDTO{}, err + } + return item, tx.Commit(ctx) } func (r *repository) Update(ctx context.Context, id int64, dto role.UpdateRoleDTO) (role.RoleDTO, error) { - query := fmt.Sprintf(` - UPDATE roles SET - code = $1, name = $2, guard_name = $3, - updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') - WHERE id = $4 AND deleted_at IS NULL - RETURNING %s`, roleReturningColumns) - - item, err := scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id)) - if errors.Is(err, pgx.ErrNoRows) { + tx, err := r.client.Begin(ctx) + if err != nil { return role.RoleDTO{}, err } - return item, err + defer tx.Rollback(ctx) + + tag, err := tx.Exec(ctx, ` + UPDATE roles SET name = $1, scope = $2, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') + WHERE id = $3 AND deleted_at IS NULL`, dto.Name, string(dto.Scope), id) + if err != nil { + return role.RoleDTO{}, err + } + if tag.RowsAffected() == 0 { + return role.RoleDTO{}, pgx.ErrNoRows + } + if err := setPermissions(ctx, tx, id, dto.Permissions); err != nil { + return role.RoleDTO{}, err + } + + item, err := getByID(ctx, tx, id) + if err != nil { + return role.RoleDTO{}, err + } + return item, tx.Commit(ctx) +} + +// setPermissions makes the role hold exactly codes. +func setPermissions(ctx context.Context, tx pgx.Tx, roleID int64, codes []perm.Code) error { + values := make([]string, len(codes)) + for i, code := range codes { + values[i] = string(code) + } + if _, err := tx.Exec(ctx, + `DELETE FROM role_permissions WHERE role_id = $1 AND NOT (permission_code = ANY($2::varchar[]))`, + roleID, values); err != nil { + return err + } + _, err := tx.Exec(ctx, ` + INSERT INTO role_permissions (role_id, permission_code) + SELECT $1, unnest($2::varchar[]) + ON CONFLICT DO NOTHING`, roleID, values) + return err } func (r *repository) Delete(ctx context.Context, id int64) error { - return r.generic.Delete(ctx, id) + var inUse bool + if err := r.client.QueryRow(ctx, + `SELECT EXISTS (SELECT 1 FROM users WHERE role_id = $1 AND deleted_at IS NULL)`, id).Scan(&inUse); err != nil { + return err + } + if inUse { + return role.ErrInUse + } + return genericrepo.Delete(ctx, r.client, "roles", id) } func scanRole(row genericrepo.Scanner) (role.RoleDTO, error) { var item role.RoleDTO + var scope string + var codes []string if err := row.Scan( - &item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt, + &item.Id, &item.Code, &item.Name, &scope, &item.IsSuper, &item.IsSystem, &codes, &item.UsersCount, + &item.CreatedAt, &item.UpdatedAt, ); err != nil { return role.RoleDTO{}, err } + item.Scope = rbac.Scope(scope) + item.Permissions = make([]perm.Code, len(codes)) + for i, code := range codes { + item.Permissions[i] = perm.Code(code) + } return item, nil } + +func isUniqueViolation(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == "23505" +} diff --git a/internal/identity/role/dto.go b/internal/identity/role/dto.go index a50fa26..33ca669 100644 --- a/internal/identity/role/dto.go +++ b/internal/identity/role/dto.go @@ -1,26 +1,47 @@ package role -import "time" +import ( + "time" + + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" +) type RoleDTO struct { - Id int64 `json:"id"` - Code string `json:"code"` - Name string `json:"name"` - GuardName string `json:"guardName"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` + Id int64 `json:"id"` + Code string `json:"code"` + Name string `json:"name"` + Scope rbac.Scope `json:"scope"` + IsSuper bool `json:"isSuper"` + IsSystem bool `json:"isSystem"` + Permissions []perm.Code `json:"permissions"` + UsersCount int64 `json:"usersCount"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } +func (r RoleDTO) Info() rbac.RoleInfo { + return rbac.RoleInfo{ + ID: r.Id, Code: r.Code, Scope: r.Scope, IsSuper: r.IsSuper, IsSystem: r.IsSystem, Perms: r.Permissions, + } +} + +// CreateRoleDTO: scope is own (clients, only their records), branch (the +// user's branch_user branches) or all (every branch). Permissions are +// module codes from GET /permissions. type CreateRoleDTO struct { - Code string `json:"code" binding:"required"` - Name string `json:"name" binding:"required"` - GuardName string `json:"guardName" binding:"required,oneof=web operator admin"` + Code string `json:"code" binding:"required,max=64"` + Name string `json:"name" binding:"required"` + Scope rbac.Scope `json:"scope" binding:"required,oneof=own branch all"` + Permissions []perm.Code `json:"permissions" binding:"required"` } +// UpdateRoleDTO replaces name, scope and the whole permission set. The code +// is fixed at create time. type UpdateRoleDTO struct { - Code string `json:"code" binding:"required"` - Name string `json:"name" binding:"required"` - GuardName string `json:"guardName" binding:"required,oneof=web operator admin"` + Name string `json:"name" binding:"required"` + Scope rbac.Scope `json:"scope" binding:"required,oneof=own branch all"` + Permissions []perm.Code `json:"permissions" binding:"required"` } type ListFilter struct { diff --git a/internal/identity/role/handler.go b/internal/identity/role/handler.go index 3fa7876..6d67857 100644 --- a/internal/identity/role/handler.go +++ b/internal/identity/role/handler.go @@ -8,6 +8,8 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -27,7 +29,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Roles)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) @@ -41,7 +43,7 @@ func (h *handler) Register(router *gin.RouterGroup) { // @Tags role // @Produce json // @Security BearerAuth -// @Param role_name query string false "Filter by name" +// @Param role_name query string false "Filter by name or code" // @Param page query int false "Page number" default(1) // @Param limit query int false "Items per page" default(10) // @Success 200 {object} appresult.AppSuccess @@ -100,7 +102,7 @@ func (h *handler) getByID(c *gin.Context) { // create godoc // @Summary Create role -// @Description Creates a new role +// @Description Creates a role with a scope (own, branch, all) and its permission codes. The caller cannot create a role wider than their own scope or holding permissions they lack. // @Tags role // @Accept json // @Produce json @@ -108,6 +110,8 @@ func (h *handler) getByID(c *gin.Context) { // @Param body body CreateRoleDTO true "Role payload" // @Success 201 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError +// @Failure 403 {object} appresult.AppError +// @Failure 409 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /roles [post] func (h *handler) create(c *gin.Context) { @@ -116,8 +120,19 @@ func (h *handler) create(c *gin.Context) { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } + dto.Code = strings.TrimSpace(dto.Code) + dto.Permissions = dedupe(dto.Permissions) + + next := rbac.RoleInfo{Code: dto.Code, Scope: dto.Scope, Perms: dto.Permissions} + if !h.authorize(c, nil, next) { + return + } item, err := h.repository.Create(c.Request.Context(), dto) + if errors.Is(err, ErrDuplicateCode) { + c.JSON(http.StatusConflict, appresult.ErrDuplicate) + return + } if err != nil { h.logger.Errorf("create role failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) @@ -129,7 +144,7 @@ func (h *handler) create(c *gin.Context) { // update godoc // @Summary Update role -// @Description Updates an existing role +// @Description Replaces the role's name, scope and whole permission set. System roles keep their scope; the caller must be able to grant the role both before and after the change. // @Tags role // @Accept json // @Produce json @@ -138,6 +153,7 @@ func (h *handler) create(c *gin.Context) { // @Param body body UpdateRoleDTO true "Role payload" // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError +// @Failure 403 {object} appresult.AppError // @Failure 404 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /roles/{id} [put] @@ -153,6 +169,17 @@ func (h *handler) update(c *gin.Context) { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } + dto.Permissions = dedupe(dto.Permissions) + + existing, ok := h.load(c, id) + if !ok { + return + } + current := existing.Info() + next := rbac.RoleInfo{ID: id, Code: existing.Code, Scope: dto.Scope, IsSystem: existing.IsSystem, Perms: dto.Permissions} + if !h.authorize(c, ¤t, next) { + return + } item, err := h.repository.Update(c.Request.Context(), id, dto) if errors.Is(err, pgx.ErrNoRows) { @@ -170,14 +197,16 @@ func (h *handler) update(c *gin.Context) { // delete godoc // @Summary Delete role -// @Description Deletes a role +// @Description Deletes a role. System roles and roles still assigned to users cannot be deleted. // @Tags role // @Produce json // @Security BearerAuth // @Param id path int true "Role ID" // @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 /roles/{id} [delete] func (h *handler) delete(c *gin.Context) { @@ -187,7 +216,24 @@ func (h *handler) delete(c *gin.Context) { return } - if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { + existing, ok := h.load(c, id) + if !ok { + return + } + if existing.IsSystem { + c.JSON(http.StatusConflict, appresult.ErrSystemRole) + return + } + if err := rbac.PrincipalFrom(c).CanGrant(existing.Info()); err != nil { + h.logger.Warnf("role delete denied: %v", err) + c.JSON(http.StatusForbidden, appresult.ErrForbidden) + return + } + + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, ErrInUse) { + c.JSON(http.StatusConflict, appresult.ErrRoleInUse) + return + } else if errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return } else if err != nil { @@ -199,6 +245,49 @@ func (h *handler) delete(c *gin.Context) { c.JSON(http.StatusOK, appresult.SuccessWithData("role removed")) } +func (h *handler) load(c *gin.Context, id int64) (RoleDTO, bool) { + item, err := h.repository.GetByID(c.Request.Context(), id) + if errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return RoleDTO{}, false + } + if err != nil { + h.logger.Errorf("get role failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return RoleDTO{}, false + } + return item, true +} + +func (h *handler) authorize(c *gin.Context, current *rbac.RoleInfo, next rbac.RoleInfo) bool { + err := rbac.PrincipalFrom(c).CanSaveRole(current, next) + switch { + case err == nil: + return true + case errors.Is(err, rbac.ErrUnknownPerm), errors.Is(err, rbac.ErrInvalidScope): + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + case errors.Is(err, rbac.ErrSystemRole): + c.JSON(http.StatusConflict, appresult.ErrSystemRole) + default: + h.logger.Warnf("role save denied: %v", err) + c.JSON(http.StatusForbidden, appresult.ErrForbidden) + } + return false +} + +func dedupe(codes []perm.Code) []perm.Code { + seen := make(map[perm.Code]struct{}, len(codes)) + out := make([]perm.Code, 0, len(codes)) + for _, code := range codes { + if _, ok := seen[code]; ok { + continue + } + seen[code] = struct{}{} + out = append(out, code) + } + return out +} + func parseListFilter(c *gin.Context) (ListFilter, bool) { filter := ListFilter{ Page: shared.DefaultPage, diff --git a/internal/identity/role/storage.go b/internal/identity/role/storage.go index d0925c6..a93116f 100644 --- a/internal/identity/role/storage.go +++ b/internal/identity/role/storage.go @@ -1,11 +1,20 @@ package role -import "context" +import ( + "context" + "errors" +) + +var ( + ErrDuplicateCode = errors.New("role code already exists") + ErrInUse = errors.New("role is assigned to users") +) type Repository interface { List(ctx context.Context, filter ListFilter) (ListRoleDTO, error) GetByID(ctx context.Context, id int64) (RoleDTO, error) Create(ctx context.Context, dto CreateRoleDTO) (RoleDTO, error) Update(ctx context.Context, id int64, dto UpdateRoleDTO) (RoleDTO, error) + // Delete returns ErrInUse while any live user holds the role. Delete(ctx context.Context, id int64) error } diff --git a/internal/identity/roleusers/db/postgresql.go b/internal/identity/roleusers/db/postgresql.go deleted file mode 100644 index 50d35ba..0000000 --- a/internal/identity/roleusers/db/postgresql.go +++ /dev/null @@ -1,70 +0,0 @@ -package db - -import ( - "context" - "errors" - - "online-back/internal/identity/roleusers" - "online-back/pkg/client/postgresql" - "online-back/pkg/logging" - "online-back/pkg/repository/genericrepo" - - "github.com/jackc/pgx/v4" -) - -type repository struct { - client postgresql.Client - logger *logging.Logger -} - -func NewRepository(client postgresql.Client, logger *logging.Logger) roleusers.Repository { - return &repository{client: client, logger: logger} -} - -func (r *repository) Create(ctx context.Context, dto roleusers.CreateRoleUserDTO) (roleusers.RoleUserDTO, error) { - query := ` - WITH existing AS ( - SELECT id FROM role_user WHERE user_id = $2 AND deleted_at IS NULL ORDER BY id LIMIT 1 - ), updated AS ( - UPDATE role_user SET - role_id = $1, - updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') - WHERE id = (SELECT id FROM existing) - RETURNING id, role_id, user_id, created_at, updated_at - ), inserted AS ( - INSERT INTO role_user (role_id, user_id) - SELECT $1, $2 - WHERE NOT EXISTS (SELECT 1 FROM existing) - RETURNING id, role_id, user_id, created_at, updated_at - ), upserted AS ( - SELECT * FROM updated - UNION ALL - SELECT * FROM inserted - ) - SELECT upserted.id, upserted.role_id, r.name, upserted.user_id, u.name, upserted.created_at, upserted.updated_at - FROM upserted - JOIN roles r ON r.id = upserted.role_id - JOIN users u ON u.id = upserted.user_id` - - row := r.client.QueryRow(ctx, query, dto.RoleId, dto.UserId) - return scanRoleUser(row) -} - -func (r *repository) Delete(ctx context.Context, id int64) error { - return genericrepo.Delete(ctx, r.client, "role_user", id) -} - -func scanRoleUser(row genericrepo.Scanner) (roleusers.RoleUserDTO, error) { - var item roleusers.RoleUserDTO - - err := row.Scan( - &item.Id, &item.RoleId, &item.RoleName, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt, - ) - if errors.Is(err, pgx.ErrNoRows) { - return roleusers.RoleUserDTO{}, err - } - if err != nil { - return roleusers.RoleUserDTO{}, err - } - return item, nil -} diff --git a/internal/identity/roleusers/dto.go b/internal/identity/roleusers/dto.go deleted file mode 100644 index 1a4075a..0000000 --- a/internal/identity/roleusers/dto.go +++ /dev/null @@ -1,18 +0,0 @@ -package roleusers - -import "time" - -type RoleUserDTO struct { - Id int64 `json:"id"` - UserId int64 `json:"userId"` - UserName string `json:"userName"` - RoleId int64 `json:"roleId"` - RoleName string `json:"roleName"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` -} - -type CreateRoleUserDTO struct { - RoleId int64 `json:"roleId" binding:"required"` - UserId int64 `json:"userId" binding:"required"` -} diff --git a/internal/identity/roleusers/handler.go b/internal/identity/roleusers/handler.go deleted file mode 100644 index 4b06d61..0000000 --- a/internal/identity/roleusers/handler.go +++ /dev/null @@ -1,59 +0,0 @@ -package roleusers - -import ( - "online-back/internal/appresult" - "online-back/internal/handlers" - "online-back/internal/shared" - "online-back/pkg/logging" - - "github.com/gin-gonic/gin" -) - -const baseURL = "/role-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.POST("", h.create) - group.DELETE("/:id", h.delete) -} - -// create godoc -// @Summary Assign user to role -// @Description Creates a role-user assignment, or updates the user's existing role if one is already assigned -// @Tags role-users -// @Accept json -// @Produce json -// @Security BearerAuth -// @Param body body CreateRoleUserDTO true "Role-user payload" -// @Success 201 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /role-users [post] -func (h *handler) create(c *gin.Context) { - shared.CreateAssoc[CreateRoleUserDTO, RoleUserDTO](c, h.logger, h.repository, "role user") -} - -// delete godoc -// @Summary Remove user from role -// @Description Deletes a role-user assignment -// @Tags role-users -// @Produce json -// @Security BearerAuth -// @Param id path int true "Role-user ID" -// @Success 200 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 404 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /role-users/{id} [delete] -func (h *handler) delete(c *gin.Context) { - shared.DeleteAssoc[CreateRoleUserDTO, RoleUserDTO](c, h.logger, h.repository, "role user") -} diff --git a/internal/identity/roleusers/storage.go b/internal/identity/roleusers/storage.go deleted file mode 100644 index 020f7e1..0000000 --- a/internal/identity/roleusers/storage.go +++ /dev/null @@ -1,8 +0,0 @@ -package roleusers - -import "context" - -type Repository interface { - Create(ctx context.Context, dto CreateRoleUserDTO) (RoleUserDTO, error) - Delete(ctx context.Context, id int64) error -} diff --git a/internal/identity/router.go b/internal/identity/router.go index d2fe7ae..4291204 100644 --- a/internal/identity/router.go +++ b/internal/identity/router.go @@ -7,13 +7,8 @@ import ( "online-back/internal/identity/auth" authdb "online-back/internal/identity/auth/db" "online-back/internal/identity/permission" - permissiondb "online-back/internal/identity/permission/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" - roleusersdb "online-back/internal/identity/roleusers/db" "online-back/internal/identity/user" userdb "online-back/internal/identity/user/db" "online-back/internal/identity/userbranch" @@ -40,9 +35,7 @@ func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handl activitylog.NewHandler(logger, activitylogdb.NewRepository(client, logger)), auth.NewHandler(logger, authdb.NewRepository(client, logger), sms.NewLogSender(logger)), role.NewHandler(logger, roledb.NewRepository(client, logger)), - permission.NewHandler(logger, permissiondb.NewRepository(client, logger)), - roleusers.NewHandler(logger, roleusersdb.NewRepository(client, logger)), - permissionrole.NewHandler(logger, permissionroledb.NewRepository(client, logger)), + permission.NewHandler(), userbranch.NewHandler(logger, userbranchdb.NewRepository(client, logger)), } } diff --git a/internal/identity/user/db/postgresql.go b/internal/identity/user/db/postgresql.go index e65fb2f..9240395 100644 --- a/internal/identity/user/db/postgresql.go +++ b/internal/identity/user/db/postgresql.go @@ -30,17 +30,10 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) user.Reposi const userColumns = `u.id, u.email, u.name, u.first_name, u.last_name, u.username, u.phone, u.avatar, u.active, u.created_at, u.updated_at, r.id, r.code` -const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, role, active, created_at, updated_at` +const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, active, created_at, updated_at` const userFromClause = ` FROM users u -LEFT JOIN LATERAL ( - SELECT ru.role_id - FROM role_user ru - WHERE ru.user_id = u.id - ORDER BY ru.id - LIMIT 1 -) ru ON true -LEFT JOIN roles r ON r.id = ru.role_id ` +LEFT JOIN roles r ON r.id = u.role_id AND r.deleted_at IS NULL ` const userBranchesJSON = `COALESCE(( SELECT json_agg(jsonb_build_object( @@ -57,19 +50,13 @@ const userBranchesJSON = `COALESCE(( ) b ), '[]'::json)` +// userPermissionsJSON lists the effective permissions: every one for an +// is_super role, else the role's role_permissions. const userPermissionsJSON = `COALESCE(( - SELECT json_agg(jsonb_build_object( - 'id', p.id, - 'code', COALESCE(p.code, ''), - 'name', p.name, - 'guardName', p.guard_name, - 'module', COALESCE(p.module, '') - ) ORDER BY p.module, p.id) + SELECT json_agg(jsonb_build_object('code', p.code, 'name', p.name) ORDER BY p.code) FROM permissions p - WHERE p.deleted_at IS NULL - AND EXISTS ( - SELECT 1 FROM permission_role pr - WHERE pr.role_id = r.id AND pr.permission_id = p.id AND pr.deleted_at IS NULL + WHERE r.is_super OR EXISTS ( + SELECT 1 FROM role_permissions rp WHERE rp.role_id = r.id AND rp.permission_code = p.code ) ), '[]'::json)` @@ -225,7 +212,7 @@ func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error return item, err } -func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO) (user.UserDTO, error) { +func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO, roleID int64) (user.UserDTO, error) { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(dto.Password), bcrypt.DefaultCost) if err != nil { return user.UserDTO{}, err @@ -236,78 +223,56 @@ func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO) (user.U active = *dto.Active } - role := strings.TrimSpace(dto.Role) - if role == "" { - role = "user" - } - - tx, err := r.client.Begin(ctx) - if err != nil { - return user.UserDTO{}, err - } - defer tx.Rollback(ctx) - query := fmt.Sprintf(` - INSERT INTO users (email, password, name, first_name, last_name, username, phone, avatar, role, active) + INSERT INTO users (email, password, name, first_name, last_name, username, phone, avatar, role_id, active) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING %s`, userReturningColumns) - item, err := scanUser(tx.QueryRow(ctx, query, - dto.Email, hashedPassword, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, role, active, + item, err := scanUser(r.client.QueryRow(ctx, query, + dto.Email, hashedPassword, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, roleID, active, )) if err != nil { return user.UserDTO{}, err } - - if err := assignRoleByCode(ctx, tx, item.Id, role); err != nil { - return user.UserDTO{}, err - } - item.RoleId = roleIDByCode(ctx, tx, role) - - if err := tx.Commit(ctx); err != nil { - return user.UserDTO{}, err - } - return item, nil + return r.withRole(ctx, item, roleID) } -func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDTO) (user.UserDTO, error) { - role := strings.TrimSpace(dto.Role) - if role == "" { - role = "user" - } - - tx, err := r.client.Begin(ctx) - if err != nil { - return user.UserDTO{}, err - } - defer tx.Rollback(ctx) - +func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDTO, roleID int64) (user.UserDTO, error) { query := fmt.Sprintf(` UPDATE users SET email = $1, name = $2, first_name = $3, last_name = $4, username = $5, phone = $6, avatar = $7, - role = $8, active = $9, + role_id = $8, active = $9, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $10 AND deleted_at IS NULL RETURNING %s`, userReturningColumns) - item, err := scanUser(tx.QueryRow(ctx, query, - dto.Email, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, role, dto.Active, id, + item, err := scanUser(r.client.QueryRow(ctx, query, + dto.Email, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, roleID, dto.Active, id, )) - if errors.Is(err, pgx.ErrNoRows) { - return user.UserDTO{}, err - } if err != nil { return user.UserDTO{}, err } + return r.withRole(ctx, item, roleID) +} - if err := replaceRoleByCode(ctx, tx, item.Id, role); err != nil { - return user.UserDTO{}, err - } - item.RoleId = roleIDByCode(ctx, tx, role) - - if err := tx.Commit(ctx); err != nil { +func (r *repository) SetRole(ctx context.Context, id, roleID int64) error { + tag, err := r.client.Exec(ctx, ` + UPDATE users SET role_id = $1, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') + WHERE id = $2 AND deleted_at IS NULL`, roleID, id) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return pgx.ErrNoRows + } + return nil +} + +func (r *repository) withRole(ctx context.Context, item user.UserDTO, roleID int64) (user.UserDTO, error) { + if err := r.client.QueryRow(ctx, `SELECT code FROM roles WHERE id = $1`, roleID).Scan(&item.Role); err != nil { return user.UserDTO{}, err } + item.RoleId = &roleID return item, nil } @@ -315,48 +280,36 @@ func (r *repository) Delete(ctx context.Context, id int64) error { return genericrepo.Delete(ctx, r.client, "users", id) } -func (r *repository) RoleGuardName(ctx context.Context, code string) (string, error) { - var guardName string - err := r.client.QueryRow(ctx, `SELECT guard_name FROM roles WHERE code = $1`, code).Scan(&guardName) - if errors.Is(err, pgx.ErrNoRows) { - return "", nil - } - return guardName, err +func (r *repository) RoleByCode(ctx context.Context, code string) (*rbac.RoleInfo, error) { + return rbac.ScanRoleInfo(r.client.QueryRow(ctx, + rbac.RoleInfoSelect+`WHERE r.code = $1 AND r.deleted_at IS NULL`, strings.TrimSpace(code))) } -func assignRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode string) error { - tag, err := tx.Exec(ctx, ` - INSERT INTO role_user (role_id, user_id) - SELECT r.id, $1 FROM roles r WHERE r.code = $2`, userID, roleCode) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return fmt.Errorf("role %q not found", roleCode) - } - return nil +func (r *repository) RoleByID(ctx context.Context, id int64) (*rbac.RoleInfo, error) { + return rbac.ScanRoleInfo(r.client.QueryRow(ctx, + rbac.RoleInfoSelect+`WHERE r.id = $1 AND r.deleted_at IS NULL`, id)) } -func replaceRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode string) error { - if _, err := tx.Exec(ctx, `UPDATE role_user SET deleted_at = now() WHERE user_id = $1 AND deleted_at IS NULL`, userID); err != nil { - return err - } - return assignRoleByCode(ctx, tx, userID, roleCode) +func (r *repository) RoleOfUser(ctx context.Context, userID int64) (*rbac.RoleInfo, error) { + return rbac.ScanRoleInfo(r.client.QueryRow(ctx, + rbac.RoleInfoSelect+`JOIN users u ON u.role_id = r.id + WHERE u.id = $1 AND u.deleted_at IS NULL AND r.deleted_at IS NULL`, userID)) } -func roleIDByCode(ctx context.Context, tx pgx.Tx, roleCode string) *int64 { - var id int64 - if err := tx.QueryRow(ctx, `SELECT id FROM roles WHERE code = $1`, roleCode).Scan(&id); err != nil { - return nil - } - return &id +func (r *repository) CountSuperUsers(ctx context.Context) (int64, error) { + var count int64 + err := r.client.QueryRow(ctx, ` + SELECT COUNT(*) FROM users u + JOIN roles r ON r.id = u.role_id AND r.deleted_at IS NULL + WHERE r.is_super AND u.deleted_at IS NULL`).Scan(&count) + return count, err } func scanUser(row genericrepo.Scanner) (user.UserDTO, error) { var item user.UserDTO if err := row.Scan( &item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar, - &item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt, + &item.Active, &item.CreatedAt, &item.UpdatedAt, ); err != nil { return user.UserDTO{}, err } diff --git a/internal/identity/user/dto.go b/internal/identity/user/dto.go index 6bd7ca3..9178758 100644 --- a/internal/identity/user/dto.go +++ b/internal/identity/user/dto.go @@ -15,11 +15,8 @@ type StaffBranchDTO struct { } type UserPermissionDTO struct { - Id int64 `json:"id"` - Code string `json:"code"` - Name string `json:"name"` - GuardName string `json:"guardName"` - Module string `json:"module"` + Code string `json:"code"` + Name string `json:"name"` } type UserDTO struct { @@ -49,8 +46,10 @@ type CreateUserDTO struct { Username string `json:"username" binding:"required"` Phone string `json:"phone"` Avatar string `json:"avatar"` - Role string `json:"role"` - Active *bool `json:"active"` + // Role is a role code; RoleId wins when both are sent. Neither → "user". + Role string `json:"role"` + RoleId *int64 `json:"roleId"` + Active *bool `json:"active"` } type UpdateUserDTO struct { @@ -61,8 +60,15 @@ type UpdateUserDTO struct { Username string `json:"username" binding:"required"` Phone string `json:"phone"` Avatar string `json:"avatar"` - Role string `json:"role"` - Active bool `json:"active"` + // Role is a role code; RoleId wins when both are sent. Neither keeps + // the user's current role. + Role string `json:"role"` + RoleId *int64 `json:"roleId"` + Active bool `json:"active"` +} + +type SetUserRoleDTO struct { + RoleId int64 `json:"roleId" binding:"required"` } type ListFilter struct { @@ -70,8 +76,8 @@ type ListFilter struct { BranchIds []int64 Page int Limit int - // AllRoles, when true, skips the role=user filter so admin/superadmin - // callers see every user regardless of role. + // AllRoles, when true, skips the role=user filter so all-scope callers + // see every user regardless of role. AllRoles bool } diff --git a/internal/identity/user/handler.go b/internal/identity/user/handler.go index 9432733..865a350 100644 --- a/internal/identity/user/handler.go +++ b/internal/identity/user/handler.go @@ -14,6 +14,7 @@ import ( "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" @@ -26,7 +27,6 @@ import ( const ( baseURL = "/users" fileUploadURL = "/file" - fileURL = "/file/:id" publicFileURL = "/file/:file_name" ) @@ -40,20 +40,23 @@ func NewHandler(logger *logging.Logger, repository Repository) *handler { } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Users)) group.GET("", h.list) - group.GET("/clients", h.listClients) 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 := router.Group("", appresult.JwtTokenCheck()) - files.POST(fileUploadURL, h.fileUpload) - files.DELETE(fileURL, h.deleteFile) + files := rbac.Group(router, fileUploadURL, rbac.Authenticated()) + files.POST("", h.fileUpload) + files.DELETE("/:id", h.deleteFile) } func (h *handler) RegisterPublic(engine *gin.Engine) { @@ -62,7 +65,7 @@ func (h *handler) RegisterPublic(engine *gin.Engine) { // list godoc // @Summary List users -// @Description Returns paginated users, including roleId. Admin-guard callers (admin, superadmin, and other admin-guard roles) see users of every role; branch-scoped operators see role=user only, scoped to their branches. +// @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 @@ -80,7 +83,7 @@ func (h *handler) list(c *gin.Context) { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } - filter.AllRoles = rbac.IsAdminGuard(c) + filter.AllRoles = rbac.HasAllScope(c) rbac.BindBranchIDs(c, &filter.BranchIds) result, err := h.repository.List(c.Request.Context(), filter) @@ -194,7 +197,7 @@ func (h *handler) getByID(c *gin.Context) { // create godoc // @Summary Create user -// @Description Creates a new 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 @@ -202,6 +205,7 @@ func (h *handler) getByID(c *gin.Context) { // @Param body body CreateUserDTO true "User payload" // @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) { @@ -211,16 +215,15 @@ func (h *handler) create(c *gin.Context) { return } - if allowed, err := h.roleAssignmentAllowed(c, dto.Role); err != nil { - h.logger.Errorf("resolve role guard failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + next, ok := h.requestedRole(c, dto.RoleId, dto.Role, "user") + if !ok { return - } else if !allowed { - c.JSON(http.StatusForbidden, appresult.ErrForbidden) + } + if !h.authorizeRoleChange(c, 0, nil, next) { return } - item, err := h.repository.Create(c.Request.Context(), dto) + 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) @@ -232,7 +235,7 @@ func (h *handler) create(c *gin.Context) { // update godoc // @Summary Update user -// @Description Updates an existing 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 @@ -241,7 +244,9 @@ func (h *handler) create(c *gin.Context) { // @Param body body UpdateUserDTO true "User payload" // @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) { @@ -261,16 +266,21 @@ func (h *handler) update(c *gin.Context) { return } - if allowed, err := h.roleAssignmentAllowed(c, dto.Role); err != nil { - h.logger.Errorf("resolve role guard failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + current, ok := h.currentRole(c, id) + if !ok { return - } else if !allowed { - c.JSON(http.StatusForbidden, appresult.ErrForbidden) + } + 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) + 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 @@ -284,16 +294,81 @@ func (h *handler) update(c *gin.Context) { 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" +// @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 +// @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" // @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) { @@ -307,6 +382,23 @@ func (h *handler) delete(c *gin.Context) { 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 @@ -319,25 +411,100 @@ func (h *handler) delete(c *gin.Context) { c.JSON(http.StatusOK, appresult.SuccessWithData("user removed")) } -// roleAssignmentAllowed asks "would granting this role let the target run -// requests as guardAdmin?" using the role's real guard_name, the same input -// rbac.Guard() resolves on every request - not a hardcoded list of role -// names, which would drift the moment a new role is added. Without this, an -// operator holding users.manage could set role:"admin" on themselves via -// this same endpoint and escape branch scoping entirely. -func (h *handler) roleAssignmentAllowed(c *gin.Context, role string) (bool, error) { - if rbac.IsAdminGuard(c) { - return true, nil - } - code := strings.ToLower(strings.TrimSpace(role)) +// 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 = "user" + 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) } - guardName, err := h.repository.RoleGuardName(c.Request.Context(), code) if err != nil { - return false, err + h.logger.Errorf("resolve role failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return nil, false } - return rbac.EffectiveGuard(code, guardName) != rbac.GuardAdmin, nil + 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) { diff --git a/internal/identity/user/handler_test.go b/internal/identity/user/handler_test.go deleted file mode 100644 index 52ded12..0000000 --- a/internal/identity/user/handler_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package user - -import ( - "context" - "net/http" - "net/http/httptest" - "testing" - - "github.com/gin-gonic/gin" -) - -// stubRoleRepo only implements RoleGuardName meaningfully - the other -// methods exist solely to satisfy the Repository interface, since -// roleAssignmentAllowed never calls them. -type stubRoleRepo struct { - guards map[string]string -} - -func (s *stubRoleRepo) List(context.Context, ListFilter) (ListUserDTO, error) { - return ListUserDTO{}, nil -} -func (s *stubRoleRepo) ListStaff(context.Context, ListFilter) (ListUserDTO, error) { - return ListUserDTO{}, nil -} -func (s *stubRoleRepo) GetByID(context.Context, int64) (UserDTO, error) { return UserDTO{}, nil } -func (s *stubRoleRepo) GetByRole(context.Context, string, ListFilter) (ListUserDTO, error) { - return ListUserDTO{}, nil -} -func (s *stubRoleRepo) Create(context.Context, CreateUserDTO) (UserDTO, error) { return UserDTO{}, nil } -func (s *stubRoleRepo) Update(context.Context, int64, UpdateUserDTO) (UserDTO, error) { - return UserDTO{}, nil -} -func (s *stubRoleRepo) Delete(context.Context, int64) error { return nil } -func (s *stubRoleRepo) RoleGuardName(_ context.Context, code string) (string, error) { - return s.guards[code], nil -} - -var _ Repository = (*stubRoleRepo)(nil) - -func TestRoleAssignmentAllowed(t *testing.T) { - gin.SetMode(gin.TestMode) - - // Mirrors db/seed.sql's roles table, plus a role added after this code - // was written - to prove the check follows guard_name, not a hardcoded - // list of role names. - repo := &stubRoleRepo{guards: map[string]string{ - "user": "web", - "operator": "operator", - "admin": "admin", - "superadmin": "admin", - "manager": "admin", - "currency_maintainer": "admin", - "custom_branch_ops": "operator", - }} - h := &handler{repository: repo} - - newContext := func(guard string) *gin.Context { - w := httptest.NewRecorder() - c, _ := gin.CreateTestContext(w) - c.Request = httptest.NewRequest(http.MethodPut, "/", nil) - if guard != "" { - c.Set("guard", guard) - } - return c - } - - admin := newContext("admin") - for _, role := range []string{"", "user", "operator", "admin", "superadmin", "manager", "currency_maintainer", "unknown-role"} { - allowed, err := h.roleAssignmentAllowed(admin, role) - if err != nil { - t.Fatalf("role %q: unexpected error %v", role, err) - } - if !allowed { - t.Fatalf("admin guard should be able to assign role %q", role) - } - } - - operator := newContext("operator") - for _, role := range []string{"", "user", "operator", "USER", " Operator ", "custom_branch_ops"} { - allowed, err := h.roleAssignmentAllowed(operator, role) - if err != nil { - t.Fatalf("role %q: unexpected error %v", role, err) - } - if !allowed { - t.Fatalf("operator guard should be able to assign role %q", role) - } - } - for _, role := range []string{"admin", "superadmin", "manager", "currency_maintainer", "unknown-role"} { - allowed, err := h.roleAssignmentAllowed(operator, role) - if err != nil { - t.Fatalf("role %q: unexpected error %v", role, err) - } - if allowed { - t.Fatalf("operator guard must not be able to assign role %q", role) - } - } -} diff --git a/internal/identity/user/storage.go b/internal/identity/user/storage.go index 76145cb..df2b577 100644 --- a/internal/identity/user/storage.go +++ b/internal/identity/user/storage.go @@ -1,16 +1,26 @@ package user -import "context" +import ( + "context" + + "online-back/internal/identity/rbac" +) type Repository interface { List(ctx context.Context, filter ListFilter) (ListUserDTO, error) ListStaff(ctx context.Context, filter ListFilter) (ListUserDTO, error) GetByID(ctx context.Context, id int64) (UserDTO, error) GetByRole(ctx context.Context, role string, filter ListFilter) (ListUserDTO, error) - Create(ctx context.Context, dto CreateUserDTO) (UserDTO, error) - Update(ctx context.Context, id int64, dto UpdateUserDTO) (UserDTO, error) + Create(ctx context.Context, dto CreateUserDTO, roleID int64) (UserDTO, error) + Update(ctx context.Context, id int64, dto UpdateUserDTO, roleID int64) (UserDTO, error) + SetRole(ctx context.Context, id, roleID int64) error Delete(ctx context.Context, id int64) error - // RoleGuardName returns the guard_name of the role with the given code, - // or "" if no such role exists. - RoleGuardName(ctx context.Context, code string) (string, error) + + // RoleByCode / RoleByID return nil when no live role matches. + RoleByCode(ctx context.Context, code string) (*rbac.RoleInfo, error) + RoleByID(ctx context.Context, id int64) (*rbac.RoleInfo, error) + // RoleOfUser returns the user's current role, nil if the user is gone. + RoleOfUser(ctx context.Context, userID int64) (*rbac.RoleInfo, error) + // CountSuperUsers counts live users holding an is_super role. + CountSuperUsers(ctx context.Context) (int64, error) } diff --git a/internal/identity/userbranch/handler.go b/internal/identity/userbranch/handler.go index 4779fd6..423a075 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/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Users)) group.POST("", h.create) group.DELETE("/:id", h.delete) } diff --git a/internal/lending/loanorders/handler.go b/internal/lending/loanorders/handler.go index d65d1dc..f31ae97 100644 --- a/internal/lending/loanorders/handler.go +++ b/internal/lending/loanorders/handler.go @@ -9,6 +9,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -28,7 +29,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Require(perm.Loans)) group.GET("", h.list) group.GET("/mobile", h.listMobile) group.GET("/:id", h.getByID) diff --git a/internal/lending/loanpaidletter/handler.go b/internal/lending/loanpaidletter/handler.go index 147af83..3ef5a34 100644 --- a/internal/lending/loanpaidletter/handler.go +++ b/internal/lending/loanpaidletter/handler.go @@ -9,6 +9,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -28,7 +29,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Require(perm.Loans)) group.GET("", h.list) group.GET("/branches", h.listBranchesByProvince) group.GET("/:id", h.getByID) diff --git a/internal/lending/loansdocument/handler.go b/internal/lending/loansdocument/handler.go index 8305f16..d3b98ff 100644 --- a/internal/lending/loansdocument/handler.go +++ b/internal/lending/loansdocument/handler.go @@ -8,6 +8,8 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -27,7 +29,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Catalog(perm.Loans)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) diff --git a/internal/lending/loansrepayment/handler.go b/internal/lending/loansrepayment/handler.go index 86dbb5c..f33d2dd 100644 --- a/internal/lending/loansrepayment/handler.go +++ b/internal/lending/loansrepayment/handler.go @@ -9,6 +9,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -28,7 +29,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Require(perm.Loans)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) diff --git a/internal/lending/loantype/handler.go b/internal/lending/loantype/handler.go index 5fe256a..4de27b4 100644 --- a/internal/lending/loantype/handler.go +++ b/internal/lending/loantype/handler.go @@ -8,6 +8,8 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -27,7 +29,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Catalog(perm.Loans)) group.GET("", h.list) group.GET("/:id", h.getByID) group.POST("", h.create) diff --git a/internal/org/branches/handler.go b/internal/org/branches/handler.go index 1616924..7bf2edc 100644 --- a/internal/org/branches/handler.go +++ b/internal/org/branches/handler.go @@ -9,6 +9,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/org/province" "online-back/internal/shared" "online-back/pkg/logging" @@ -30,7 +31,7 @@ func NewHandler(logger *logging.Logger, repository Repository, provinces provinc } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Catalog(perm.Branches)) group.GET("", h.list) group.GET("/regions", h.listRegions) group.GET("/etraps", h.listEtraps) @@ -69,7 +70,7 @@ func (h *handler) list(c *gin.Context) { c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } - if !rbac.IsAdminGuard(c) { + if !rbac.HasAllScope(c) { for i := range result.Branches { clearBranchSecrets(&result.Branches[i]) } @@ -173,7 +174,7 @@ func (h *handler) getByID(c *gin.Context) { if !rbac.GuardBranch(c, item.Id) { return } - if !rbac.IsAdminGuard(c) { + if !rbac.HasAllScope(c) { clearBranchSecrets(&item) } diff --git a/internal/org/province/handler.go b/internal/org/province/handler.go index 7924f22..a569a1b 100644 --- a/internal/org/province/handler.go +++ b/internal/org/province/handler.go @@ -8,6 +8,8 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -27,7 +29,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Catalog(perm.Provinces)) group.GET("", h.list) // Use /branches/regions and /branches/etraps instead. // group.GET("/regions", h.listRegions) diff --git a/internal/payment/paymenthistory/handler.go b/internal/payment/paymenthistory/handler.go index a7c63fe..140b8ef 100644 --- a/internal/payment/paymenthistory/handler.go +++ b/internal/payment/paymenthistory/handler.go @@ -7,6 +7,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Cards)) group.GET("", h.list) group.GET("/:id", h.logs) } diff --git a/internal/payment/paymentsettings/handler.go b/internal/payment/paymentsettings/handler.go index 0eceb67..9da9762 100644 --- a/internal/payment/paymentsettings/handler.go +++ b/internal/payment/paymentsettings/handler.go @@ -6,6 +6,8 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" + "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/pkg/logging" "github.com/gin-gonic/gin" @@ -23,7 +25,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.StaffRead(perm.PaymentSettings)) group.GET("", h.get) group.PUT("", h.update) } diff --git a/internal/payment/visamasterpay/handler.go b/internal/payment/visamasterpay/handler.go index 06e857c..73ccc49 100644 --- a/internal/payment/visamasterpay/handler.go +++ b/internal/payment/visamasterpay/handler.go @@ -7,6 +7,7 @@ import ( "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" + "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" @@ -26,16 +27,14 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) + group := rbac.Group(router, baseURL, rbac.Require(perm.Cards)) group.GET("/:id/quote", h.quote) group.POST("/:id/pay", h.pay) group.GET("/:id/status", h.status) // callback is hit by the customer's/operator's browser after GBÜS - // redirects back - it carries no Bearer token, so it's registered on - // its own group with no JwtTokenCheck. See rbac.isPublicAdminPath, - // which must also list this path. - router.Group(baseURL).GET("/callback", h.callback) + // redirects back - it carries no Bearer token. + rbac.Group(router, baseURL+"/callback", rbac.Public()).GET("", h.callback) } // quote godoc