ch logika
This commit is contained in:
1 parent
e0d03730de
commit
d3e188affe
28 files changed
+405
-656
No files matched your search
@@ -16,7 +16,6 @@ DROP TABLE IF EXISTS card_types;
|
|||||||
DROP TABLE IF EXISTS branch_user;
|
DROP TABLE IF EXISTS branch_user;
|
||||||
DROP TABLE IF EXISTS branches;
|
DROP TABLE IF EXISTS branches;
|
||||||
DROP TABLE IF EXISTS provinces;
|
DROP TABLE IF EXISTS provinces;
|
||||||
DROP TABLE IF EXISTS permission_user;
|
|
||||||
DROP TABLE IF EXISTS permission_role;
|
DROP TABLE IF EXISTS permission_role;
|
||||||
DROP TABLE IF EXISTS role_user;
|
DROP TABLE IF EXISTS role_user;
|
||||||
DROP TABLE IF EXISTS permissions;
|
DROP TABLE IF EXISTS permissions;
|
||||||
@@ -64,7 +63,6 @@ DROP INDEX IF EXISTS idx_permissions_module;
|
|||||||
DROP INDEX IF EXISTS idx_permissions_guard_name;
|
DROP INDEX IF EXISTS idx_permissions_guard_name;
|
||||||
DROP INDEX IF EXISTS idx_roles_code;
|
DROP INDEX IF EXISTS idx_roles_code;
|
||||||
DROP INDEX IF EXISTS idx_permission_role_role_id;
|
DROP INDEX IF EXISTS idx_permission_role_role_id;
|
||||||
DROP INDEX IF EXISTS idx_permission_user_user_id;
|
|
||||||
DROP INDEX IF EXISTS idx_role_user_user_id;
|
DROP INDEX IF EXISTS idx_role_user_user_id;
|
||||||
|
|
||||||
DROP TABLE IF EXISTS currencies;
|
DROP TABLE IF EXISTS currencies;
|
||||||
|
|||||||
@@ -77,22 +77,6 @@ CREATE TABLE IF NOT EXISTS permission_role (
|
|||||||
CONSTRAINT permission_role_permission_id_role_id_key UNIQUE (permission_id, role_id)
|
CONSTRAINT permission_role_permission_id_role_id_key UNIQUE (permission_id, role_id)
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Per-user permission override on top of the role's baseline: 'allow' grants
|
|
||||||
-- a permission the user's role does not have, 'deny' revokes one the role
|
|
||||||
-- does grant. An admin can flip their mind by re-assigning the same
|
|
||||||
-- permission/user pair with a different effect (upsert), rather than having
|
|
||||||
-- to delete the old override first.
|
|
||||||
CREATE TABLE IF NOT EXISTS permission_user (
|
|
||||||
id bigserial PRIMARY KEY,
|
|
||||||
permission_id bigint REFERENCES permissions(id),
|
|
||||||
user_id bigint REFERENCES users(id),
|
|
||||||
effect character varying(10) NOT NULL DEFAULT 'allow',
|
|
||||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
|
||||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
|
||||||
CONSTRAINT permission_user_permission_id_user_id_key UNIQUE (permission_id, user_id),
|
|
||||||
CONSTRAINT permission_user_effect_chk CHECK (effect IN ('allow', 'deny'))
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS provinces (
|
CREATE TABLE IF NOT EXISTS provinces (
|
||||||
id bigserial PRIMARY KEY,
|
id bigserial PRIMARY KEY,
|
||||||
name json NOT NULL DEFAULT '{}'::json,
|
name json NOT NULL DEFAULT '{}'::json,
|
||||||
@@ -349,7 +333,7 @@ CREATE TABLE IF NOT EXISTS loans (
|
|||||||
CREATE TABLE IF NOT EXISTS loan_paid_off_letters (
|
CREATE TABLE IF NOT EXISTS loan_paid_off_letters (
|
||||||
id bigserial PRIMARY KEY,
|
id bigserial PRIMARY KEY,
|
||||||
unique_id character varying(255),
|
unique_id character varying(255),
|
||||||
region character varying(2) NOT NULL,
|
region character varying(255) NOT NULL,
|
||||||
branch_id bigint NOT NULL,
|
branch_id bigint NOT NULL,
|
||||||
user_id bigint,
|
user_id bigint,
|
||||||
customer_name character varying(255) NOT NULL,
|
customer_name character varying(255) NOT NULL,
|
||||||
@@ -525,7 +509,6 @@ CREATE TABLE IF NOT EXISTS currencies (
|
|||||||
-- table scan.
|
-- table scan.
|
||||||
CREATE INDEX IF NOT EXISTS idx_role_user_user_id ON role_user(user_id);
|
CREATE INDEX IF NOT EXISTS idx_role_user_user_id ON role_user(user_id);
|
||||||
CREATE INDEX IF NOT EXISTS idx_permission_role_role_id ON permission_role(role_id);
|
CREATE INDEX IF NOT EXISTS idx_permission_role_role_id ON permission_role(role_id);
|
||||||
CREATE INDEX IF NOT EXISTS idx_permission_user_user_id ON permission_user(user_id);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_roles_code ON roles(code);
|
CREATE INDEX IF NOT EXISTS idx_roles_code ON roles(code);
|
||||||
CREATE INDEX IF NOT EXISTS idx_permissions_code ON permissions(code);
|
CREATE INDEX IF NOT EXISTS idx_permissions_code ON permissions(code);
|
||||||
CREATE INDEX IF NOT EXISTS idx_permissions_module ON permissions(module);
|
CREATE INDEX IF NOT EXISTS idx_permissions_module ON permissions(module);
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
-- Reverse 20260905130000_add_soft_delete.up.sql
|
-- Reverse 20260905130000_add_soft_delete.up.sql
|
||||||
|
|
||||||
DROP INDEX IF EXISTS permission_user_permission_id_user_id_idx;
|
|
||||||
ALTER TABLE permission_user ADD CONSTRAINT permission_user_permission_id_user_id_key UNIQUE (permission_id, user_id);
|
|
||||||
|
|
||||||
DROP INDEX IF EXISTS permission_role_permission_id_role_id_idx;
|
DROP INDEX IF EXISTS permission_role_permission_id_role_id_idx;
|
||||||
ALTER TABLE permission_role ADD CONSTRAINT permission_role_permission_id_role_id_key UNIQUE (permission_id, role_id);
|
ALTER TABLE permission_role ADD CONSTRAINT permission_role_permission_id_role_id_key UNIQUE (permission_id, role_id);
|
||||||
|
|
||||||
@@ -42,7 +39,6 @@ ALTER TABLE card_types DROP COLUMN IF EXISTS deleted_at;
|
|||||||
ALTER TABLE branch_user DROP COLUMN IF EXISTS deleted_at;
|
ALTER TABLE branch_user DROP COLUMN IF EXISTS deleted_at;
|
||||||
ALTER TABLE branches DROP COLUMN IF EXISTS deleted_at;
|
ALTER TABLE branches DROP COLUMN IF EXISTS deleted_at;
|
||||||
ALTER TABLE provinces DROP COLUMN IF EXISTS deleted_at;
|
ALTER TABLE provinces DROP COLUMN IF EXISTS deleted_at;
|
||||||
ALTER TABLE permission_user DROP COLUMN IF EXISTS deleted_at;
|
|
||||||
ALTER TABLE permission_role DROP COLUMN IF EXISTS deleted_at;
|
ALTER TABLE permission_role DROP COLUMN IF EXISTS deleted_at;
|
||||||
ALTER TABLE role_user DROP COLUMN IF EXISTS deleted_at;
|
ALTER TABLE role_user DROP COLUMN IF EXISTS deleted_at;
|
||||||
ALTER TABLE permissions DROP COLUMN IF EXISTS deleted_at;
|
ALTER TABLE permissions DROP COLUMN IF EXISTS deleted_at;
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ ALTER TABLE roles ADD COLUMN deleted_at TIMESTAMPTZ;
|
|||||||
ALTER TABLE permissions ADD COLUMN deleted_at TIMESTAMPTZ;
|
ALTER TABLE permissions ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||||
ALTER TABLE role_user ADD COLUMN deleted_at TIMESTAMPTZ;
|
ALTER TABLE role_user ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||||
ALTER TABLE permission_role ADD COLUMN deleted_at TIMESTAMPTZ;
|
ALTER TABLE permission_role ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||||
ALTER TABLE permission_user ADD COLUMN deleted_at TIMESTAMPTZ;
|
|
||||||
ALTER TABLE provinces ADD COLUMN deleted_at TIMESTAMPTZ;
|
ALTER TABLE provinces ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||||
ALTER TABLE branches ADD COLUMN deleted_at TIMESTAMPTZ;
|
ALTER TABLE branches ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||||
ALTER TABLE branch_user ADD COLUMN deleted_at TIMESTAMPTZ;
|
ALTER TABLE branch_user ADD COLUMN deleted_at TIMESTAMPTZ;
|
||||||
@@ -30,8 +29,8 @@ ALTER TABLE currencies ADD COLUMN deleted_at TIMESTAMPTZ;
|
|||||||
|
|
||||||
-- Rescope existing uniqueness constraints to active (non-soft-deleted) rows
|
-- Rescope existing uniqueness constraints to active (non-soft-deleted) rows
|
||||||
-- only, so a soft-deleted row's unique value (username, phone, branch code,
|
-- only, so a soft-deleted row's unique value (username, phone, branch code,
|
||||||
-- backup file name, currency pair, permission-role/permission-user pair) can
|
-- backup file name, currency pair, permission-role pair) can be reused by a
|
||||||
-- be reused by a new row.
|
-- new row.
|
||||||
|
|
||||||
DROP INDEX IF EXISTS idx_users_username;
|
DROP INDEX IF EXISTS idx_users_username;
|
||||||
CREATE UNIQUE INDEX idx_users_username
|
CREATE UNIQUE INDEX idx_users_username
|
||||||
@@ -62,8 +61,3 @@ ALTER TABLE permission_role DROP CONSTRAINT IF EXISTS permission_role_permission
|
|||||||
CREATE UNIQUE INDEX permission_role_permission_id_role_id_idx
|
CREATE UNIQUE INDEX permission_role_permission_id_role_id_idx
|
||||||
ON permission_role (permission_id, role_id)
|
ON permission_role (permission_id, role_id)
|
||||||
WHERE deleted_at IS NULL;
|
WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
ALTER TABLE permission_user DROP CONSTRAINT IF EXISTS permission_user_permission_id_user_id_key;
|
|
||||||
CREATE UNIQUE INDEX permission_user_permission_id_user_id_idx
|
|
||||||
ON permission_user (permission_id, user_id)
|
|
||||||
WHERE deleted_at IS NULL;
|
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- Reverse 20260905150000_widen_loan_paid_off_letters_region.up.sql
|
||||||
|
--
|
||||||
|
-- Only safe if no row currently holds a region value longer than 2
|
||||||
|
-- characters; if the widened column is already in real use with longer
|
||||||
|
-- values, narrowing it back will fail (or truncate, if forced), and that is
|
||||||
|
-- exactly the failure mode this migration set out to remove.
|
||||||
|
ALTER TABLE loan_paid_off_letters ALTER COLUMN region TYPE character varying(2);
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
-- loan_paid_off_letters.region was originally character varying(2), mirroring
|
||||||
|
-- branches' 2-letter region codes (AG/AH/BL/DZ/MR/LB). Every sibling order
|
||||||
|
-- table (card_orders, card_pin_orders, card_rekwizit_orders, loan_orders,
|
||||||
|
-- visa_master_payment_orders) stores region as free text instead. Sending a
|
||||||
|
-- normal region name here (e.g. "Ashgabat") overflowed the column and
|
||||||
|
-- surfaced to the client as a raw 500 instead of a validation error.
|
||||||
|
--
|
||||||
|
-- init.up.sql has already been edited in place to varchar(255) for fresh
|
||||||
|
-- databases, but per this project's migration convention (see
|
||||||
|
-- 20260905130000_add_soft_delete), that edit alone does not reach a database
|
||||||
|
-- that was migrated before the edit. This migration widens the column there
|
||||||
|
-- too. Running it against a database created after the init.up.sql edit is a
|
||||||
|
-- harmless no-op (the column is already varchar(255)).
|
||||||
|
|
||||||
|
ALTER TABLE loan_paid_off_letters ALTER COLUMN region TYPE character varying(255);
|
||||||
+28
-15
@@ -2,13 +2,13 @@
|
|||||||
-- Usage: make seed
|
-- Usage: make seed
|
||||||
-- or: PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/seed.sql
|
-- or: PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/seed.sql
|
||||||
-- Login (password = test1234):
|
-- Login (password = test1234):
|
||||||
-- superadmin@bank.tm / +993 61 92 92 48
|
-- superadmin@bank.tm / +993 61 92 92 48 (hemme zada rugsatly, ýeke-täk bypass rol)
|
||||||
-- admin@bank.tm
|
-- admin@bank.tm (ähli permission berlen)
|
||||||
-- manager@bank.tm
|
-- manager@bank.tm (admin guard, ýöne diňe cards + loans saha)
|
||||||
-- operator@bank.tm (cards saha)
|
-- operator@bank.tm (cards saha)
|
||||||
-- loanop@bank.tm (loans saha)
|
-- loanop@bank.tm (loans saha)
|
||||||
-- bothop@bank.tm (cards + loans)
|
-- bothop@bank.tm (cards + loans)
|
||||||
-- currency@bank.tm (admin guard — walýuta)
|
-- currency@bank.tm (admin guard — diňe walýuta sahasy)
|
||||||
-- serdar@bank.tm … leyla@bank.tm (role=user)
|
-- serdar@bank.tm … leyla@bank.tm (role=user)
|
||||||
|
|
||||||
BEGIN;
|
BEGIN;
|
||||||
@@ -34,7 +34,6 @@ TRUNCATE TABLE
|
|||||||
branches,
|
branches,
|
||||||
provinces,
|
provinces,
|
||||||
permission_role,
|
permission_role,
|
||||||
permission_user,
|
|
||||||
role_user,
|
role_user,
|
||||||
permissions,
|
permissions,
|
||||||
roles,
|
roles,
|
||||||
@@ -119,13 +118,13 @@ INSERT INTO users (email, password, name, first_name, last_name, username, phone
|
|||||||
'loanop@bank.tm',
|
'loanop@bank.tm',
|
||||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
'Loan Operator', 'Jeren', 'Atayeva', 'loanop',
|
'Loan Operator', 'Jeren', 'Atayeva', 'loanop',
|
||||||
'+993 61 92 92 37', 'operator', true
|
'+993 61 92 92 37', 'loan_operator', true
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
'bothop@bank.tm',
|
'bothop@bank.tm',
|
||||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
'Full Operator', 'Batyr', 'Myradow', 'bothop',
|
'Full Operator', 'Batyr', 'Myradow', 'bothop',
|
||||||
'+993 61 92 92 36', 'operator', true
|
'+993 61 92 92 36', 'full_operator', true
|
||||||
);
|
);
|
||||||
|
|
||||||
-- ---------------------------------------------------------------------------
|
-- ---------------------------------------------------------------------------
|
||||||
@@ -134,6 +133,8 @@ INSERT INTO users (email, password, name, first_name, last_name, username, phone
|
|||||||
INSERT INTO roles (code, name, guard_name) VALUES
|
INSERT INTO roles (code, name, guard_name) VALUES
|
||||||
('user', 'User', 'web'),
|
('user', 'User', 'web'),
|
||||||
('operator', 'Operator', 'operator'),
|
('operator', 'Operator', 'operator'),
|
||||||
|
('loan_operator', 'Loan Operator', 'operator'),
|
||||||
|
('full_operator', 'Full Operator (cards + loans)', 'operator'),
|
||||||
('admin', 'Admin', 'admin'),
|
('admin', 'Admin', 'admin'),
|
||||||
('superadmin', 'Superadmin', 'admin'),
|
('superadmin', 'Superadmin', 'admin'),
|
||||||
('manager', 'Branch Manager', 'admin'),
|
('manager', 'Branch Manager', 'admin'),
|
||||||
@@ -181,14 +182,26 @@ FROM permissions p
|
|||||||
JOIN roles r ON r.code = 'operator'
|
JOIN roles r ON r.code = 'operator'
|
||||||
WHERE p.code = 'cards';
|
WHERE p.code = 'cards';
|
||||||
|
|
||||||
-- loanop (user 12): loans only — deny role cards, allow loans.
|
-- loanop (user 12): loans saha only.
|
||||||
-- bothop (user 13): keep role cards, add loans.
|
INSERT INTO permission_role (permission_id, role_id)
|
||||||
INSERT INTO permission_user (permission_id, user_id, effect)
|
SELECT p.id, r.id
|
||||||
SELECT p.id, 12, 'deny' FROM permissions p WHERE p.code = 'cards'
|
FROM permissions p
|
||||||
UNION ALL
|
JOIN roles r ON r.code = 'loan_operator'
|
||||||
SELECT p.id, 12, 'allow' FROM permissions p WHERE p.code = 'loans'
|
WHERE p.code = 'loans';
|
||||||
UNION ALL
|
|
||||||
SELECT p.id, 13, 'allow' FROM permissions p 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)
|
-- Provinces — name = etrap, region = welaýat (admin location list)
|
||||||
|
|||||||
+17
-133
@@ -2445,6 +2445,12 @@ const docTemplate = `{
|
|||||||
"$ref": "#/definitions/appresult.AppError"
|
"$ref": "#/definitions/appresult.AppError"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"409": {
|
||||||
|
"description": "Conflict",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/appresult.AppError"
|
||||||
|
}
|
||||||
|
},
|
||||||
"500": {
|
"500": {
|
||||||
"description": "Internal Server Error",
|
"description": "Internal Server Error",
|
||||||
"schema": {
|
"schema": {
|
||||||
@@ -2559,6 +2565,12 @@ const docTemplate = `{
|
|||||||
"$ref": "#/definitions/appresult.AppError"
|
"$ref": "#/definitions/appresult.AppError"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"409": {
|
||||||
|
"description": "Conflict",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/appresult.AppError"
|
||||||
|
}
|
||||||
|
},
|
||||||
"500": {
|
"500": {
|
||||||
"description": "Internal Server Error",
|
"description": "Internal Server Error",
|
||||||
"schema": {
|
"schema": {
|
||||||
@@ -4988,109 +5000,6 @@ const docTemplate = `{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"/permission-users": {
|
|
||||||
"post": {
|
|
||||||
"security": [
|
|
||||||
{
|
|
||||||
"BearerAuth": []
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"description": "Grants (\"allow\") or revokes (\"deny\") a permission for a specific user on top of their role, or updates the effect if the pair is already assigned",
|
|
||||||
"consumes": [
|
|
||||||
"application/json"
|
|
||||||
],
|
|
||||||
"produces": [
|
|
||||||
"application/json"
|
|
||||||
],
|
|
||||||
"tags": [
|
|
||||||
"permission-users"
|
|
||||||
],
|
|
||||||
"summary": "Assign a permission override to a user",
|
|
||||||
"parameters": [
|
|
||||||
{
|
|
||||||
"description": "Permission-user payload",
|
|
||||||
"name": "body",
|
|
||||||
"in": "body",
|
|
||||||
"required": true,
|
|
||||||
"schema": {
|
|
||||||
"$ref": "#/definitions/permissionuser.CreatePermissionUserDTO"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"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-users/{id}": {
|
|
||||||
"delete": {
|
|
||||||
"security": [
|
|
||||||
{
|
|
||||||
"BearerAuth": []
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"description": "Deletes a permission-user assignment, falling back to the user's role for that permission",
|
|
||||||
"produces": [
|
|
||||||
"application/json"
|
|
||||||
],
|
|
||||||
"tags": [
|
|
||||||
"permission-users"
|
|
||||||
],
|
|
||||||
"summary": "Remove a user's permission override",
|
|
||||||
"parameters": [
|
|
||||||
{
|
|
||||||
"type": "integer",
|
|
||||||
"description": "Permission-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"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/permissions": {
|
"/permissions": {
|
||||||
"get": {
|
"get": {
|
||||||
"security": [
|
"security": [
|
||||||
@@ -7451,7 +7360,8 @@ const docTemplate = `{
|
|||||||
"required": [
|
"required": [
|
||||||
"address",
|
"address",
|
||||||
"name",
|
"name",
|
||||||
"region"
|
"region",
|
||||||
|
"uniqueCode"
|
||||||
],
|
],
|
||||||
"properties": {
|
"properties": {
|
||||||
"active": {
|
"active": {
|
||||||
@@ -7495,6 +7405,9 @@ const docTemplate = `{
|
|||||||
},
|
},
|
||||||
"region": {
|
"region": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
|
},
|
||||||
|
"uniqueCode": {
|
||||||
|
"type": "string"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -8554,9 +8467,6 @@ const docTemplate = `{
|
|||||||
"status": {
|
"status": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"uniqueId": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"userId": {
|
"userId": {
|
||||||
"type": "integer"
|
"type": "integer"
|
||||||
},
|
},
|
||||||
@@ -8785,9 +8695,6 @@ const docTemplate = `{
|
|||||||
"status": {
|
"status": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"uniqueId": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"userId": {
|
"userId": {
|
||||||
"type": "integer"
|
"type": "integer"
|
||||||
},
|
},
|
||||||
@@ -9228,29 +9135,6 @@ const docTemplate = `{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"permissionuser.CreatePermissionUserDTO": {
|
|
||||||
"type": "object",
|
|
||||||
"required": [
|
|
||||||
"effect",
|
|
||||||
"permissionId",
|
|
||||||
"userId"
|
|
||||||
],
|
|
||||||
"properties": {
|
|
||||||
"effect": {
|
|
||||||
"type": "string",
|
|
||||||
"enum": [
|
|
||||||
"allow",
|
|
||||||
"deny"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"permissionId": {
|
|
||||||
"type": "integer"
|
|
||||||
},
|
|
||||||
"userId": {
|
|
||||||
"type": "integer"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"province.CreateProvinceDTO": {
|
"province.CreateProvinceDTO": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"required": [
|
"required": [
|
||||||
|
|||||||
+17
-133
@@ -2439,6 +2439,12 @@
|
|||||||
"$ref": "#/definitions/appresult.AppError"
|
"$ref": "#/definitions/appresult.AppError"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"409": {
|
||||||
|
"description": "Conflict",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/appresult.AppError"
|
||||||
|
}
|
||||||
|
},
|
||||||
"500": {
|
"500": {
|
||||||
"description": "Internal Server Error",
|
"description": "Internal Server Error",
|
||||||
"schema": {
|
"schema": {
|
||||||
@@ -2553,6 +2559,12 @@
|
|||||||
"$ref": "#/definitions/appresult.AppError"
|
"$ref": "#/definitions/appresult.AppError"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"409": {
|
||||||
|
"description": "Conflict",
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/definitions/appresult.AppError"
|
||||||
|
}
|
||||||
|
},
|
||||||
"500": {
|
"500": {
|
||||||
"description": "Internal Server Error",
|
"description": "Internal Server Error",
|
||||||
"schema": {
|
"schema": {
|
||||||
@@ -4982,109 +4994,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"/permission-users": {
|
|
||||||
"post": {
|
|
||||||
"security": [
|
|
||||||
{
|
|
||||||
"BearerAuth": []
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"description": "Grants (\"allow\") or revokes (\"deny\") a permission for a specific user on top of their role, or updates the effect if the pair is already assigned",
|
|
||||||
"consumes": [
|
|
||||||
"application/json"
|
|
||||||
],
|
|
||||||
"produces": [
|
|
||||||
"application/json"
|
|
||||||
],
|
|
||||||
"tags": [
|
|
||||||
"permission-users"
|
|
||||||
],
|
|
||||||
"summary": "Assign a permission override to a user",
|
|
||||||
"parameters": [
|
|
||||||
{
|
|
||||||
"description": "Permission-user payload",
|
|
||||||
"name": "body",
|
|
||||||
"in": "body",
|
|
||||||
"required": true,
|
|
||||||
"schema": {
|
|
||||||
"$ref": "#/definitions/permissionuser.CreatePermissionUserDTO"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"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-users/{id}": {
|
|
||||||
"delete": {
|
|
||||||
"security": [
|
|
||||||
{
|
|
||||||
"BearerAuth": []
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"description": "Deletes a permission-user assignment, falling back to the user's role for that permission",
|
|
||||||
"produces": [
|
|
||||||
"application/json"
|
|
||||||
],
|
|
||||||
"tags": [
|
|
||||||
"permission-users"
|
|
||||||
],
|
|
||||||
"summary": "Remove a user's permission override",
|
|
||||||
"parameters": [
|
|
||||||
{
|
|
||||||
"type": "integer",
|
|
||||||
"description": "Permission-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"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/permissions": {
|
"/permissions": {
|
||||||
"get": {
|
"get": {
|
||||||
"security": [
|
"security": [
|
||||||
@@ -7445,7 +7354,8 @@
|
|||||||
"required": [
|
"required": [
|
||||||
"address",
|
"address",
|
||||||
"name",
|
"name",
|
||||||
"region"
|
"region",
|
||||||
|
"uniqueCode"
|
||||||
],
|
],
|
||||||
"properties": {
|
"properties": {
|
||||||
"active": {
|
"active": {
|
||||||
@@ -7489,6 +7399,9 @@
|
|||||||
},
|
},
|
||||||
"region": {
|
"region": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
|
},
|
||||||
|
"uniqueCode": {
|
||||||
|
"type": "string"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -8548,9 +8461,6 @@
|
|||||||
"status": {
|
"status": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"uniqueId": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"userId": {
|
"userId": {
|
||||||
"type": "integer"
|
"type": "integer"
|
||||||
},
|
},
|
||||||
@@ -8779,9 +8689,6 @@
|
|||||||
"status": {
|
"status": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"uniqueId": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"userId": {
|
"userId": {
|
||||||
"type": "integer"
|
"type": "integer"
|
||||||
},
|
},
|
||||||
@@ -9222,29 +9129,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"permissionuser.CreatePermissionUserDTO": {
|
|
||||||
"type": "object",
|
|
||||||
"required": [
|
|
||||||
"effect",
|
|
||||||
"permissionId",
|
|
||||||
"userId"
|
|
||||||
],
|
|
||||||
"properties": {
|
|
||||||
"effect": {
|
|
||||||
"type": "string",
|
|
||||||
"enum": [
|
|
||||||
"allow",
|
|
||||||
"deny"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"permissionId": {
|
|
||||||
"type": "integer"
|
|
||||||
},
|
|
||||||
"userId": {
|
|
||||||
"type": "integer"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"province.CreateProvinceDTO": {
|
"province.CreateProvinceDTO": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"required": [
|
"required": [
|
||||||
|
|||||||
+11
-87
@@ -137,10 +137,13 @@ definitions:
|
|||||||
type: integer
|
type: integer
|
||||||
region:
|
region:
|
||||||
type: string
|
type: string
|
||||||
|
uniqueCode:
|
||||||
|
type: string
|
||||||
required:
|
required:
|
||||||
- address
|
- address
|
||||||
- name
|
- name
|
||||||
- region
|
- region
|
||||||
|
- uniqueCode
|
||||||
type: object
|
type: object
|
||||||
branches.LocalizedText:
|
branches.LocalizedText:
|
||||||
properties:
|
properties:
|
||||||
@@ -861,8 +864,6 @@ definitions:
|
|||||||
type: string
|
type: string
|
||||||
status:
|
status:
|
||||||
type: string
|
type: string
|
||||||
uniqueId:
|
|
||||||
type: string
|
|
||||||
userId:
|
userId:
|
||||||
type: integer
|
type: integer
|
||||||
workCompany:
|
workCompany:
|
||||||
@@ -1022,8 +1023,6 @@ definitions:
|
|||||||
type: string
|
type: string
|
||||||
status:
|
status:
|
||||||
type: string
|
type: string
|
||||||
uniqueId:
|
|
||||||
type: string
|
|
||||||
userId:
|
userId:
|
||||||
type: integer
|
type: integer
|
||||||
workCompany:
|
workCompany:
|
||||||
@@ -1346,22 +1345,6 @@ definitions:
|
|||||||
- permissionId
|
- permissionId
|
||||||
- roleId
|
- roleId
|
||||||
type: object
|
type: object
|
||||||
permissionuser.CreatePermissionUserDTO:
|
|
||||||
properties:
|
|
||||||
effect:
|
|
||||||
enum:
|
|
||||||
- allow
|
|
||||||
- deny
|
|
||||||
type: string
|
|
||||||
permissionId:
|
|
||||||
type: integer
|
|
||||||
userId:
|
|
||||||
type: integer
|
|
||||||
required:
|
|
||||||
- effect
|
|
||||||
- permissionId
|
|
||||||
- userId
|
|
||||||
type: object
|
|
||||||
province.CreateProvinceDTO:
|
province.CreateProvinceDTO:
|
||||||
properties:
|
properties:
|
||||||
active:
|
active:
|
||||||
@@ -3231,6 +3214,10 @@ paths:
|
|||||||
description: Bad Request
|
description: Bad Request
|
||||||
schema:
|
schema:
|
||||||
$ref: '#/definitions/appresult.AppError'
|
$ref: '#/definitions/appresult.AppError'
|
||||||
|
"409":
|
||||||
|
description: Conflict
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/appresult.AppError'
|
||||||
"500":
|
"500":
|
||||||
description: Internal Server Error
|
description: Internal Server Error
|
||||||
schema:
|
schema:
|
||||||
@@ -3336,6 +3323,10 @@ paths:
|
|||||||
description: Not Found
|
description: Not Found
|
||||||
schema:
|
schema:
|
||||||
$ref: '#/definitions/appresult.AppError'
|
$ref: '#/definitions/appresult.AppError'
|
||||||
|
"409":
|
||||||
|
description: Conflict
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/appresult.AppError'
|
||||||
"500":
|
"500":
|
||||||
description: Internal Server Error
|
description: Internal Server Error
|
||||||
schema:
|
schema:
|
||||||
@@ -4867,73 +4858,6 @@ paths:
|
|||||||
summary: Remove permission from role
|
summary: Remove permission from role
|
||||||
tags:
|
tags:
|
||||||
- permission-roles
|
- permission-roles
|
||||||
/permission-users:
|
|
||||||
post:
|
|
||||||
consumes:
|
|
||||||
- application/json
|
|
||||||
description: Grants ("allow") or revokes ("deny") a permission for a specific
|
|
||||||
user on top of their role, or updates the effect if the pair is already assigned
|
|
||||||
parameters:
|
|
||||||
- description: Permission-user payload
|
|
||||||
in: body
|
|
||||||
name: body
|
|
||||||
required: true
|
|
||||||
schema:
|
|
||||||
$ref: '#/definitions/permissionuser.CreatePermissionUserDTO'
|
|
||||||
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 a permission override to a user
|
|
||||||
tags:
|
|
||||||
- permission-users
|
|
||||||
/permission-users/{id}:
|
|
||||||
delete:
|
|
||||||
description: Deletes a permission-user assignment, falling back to the user's
|
|
||||||
role for that permission
|
|
||||||
parameters:
|
|
||||||
- description: Permission-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 a user's permission override
|
|
||||||
tags:
|
|
||||||
- permission-users
|
|
||||||
/permissions:
|
/permissions:
|
||||||
get:
|
get:
|
||||||
description: Returns paginated permissions with optional filters
|
description: Returns paginated permissions with optional filters
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ var swaggerTagOrder = []struct {
|
|||||||
{Name: "role-users", Description: "Role users"},
|
{Name: "role-users", Description: "Role users"},
|
||||||
{Name: "permission", Description: "Permissions"},
|
{Name: "permission", Description: "Permissions"},
|
||||||
{Name: "permission-roles", Description: "Permission roles"},
|
{Name: "permission-roles", Description: "Permission roles"},
|
||||||
{Name: "permission-users", Description: "Per-user permission overrides"},
|
|
||||||
{Name: "payment-card", Description: "Payment cards"},
|
{Name: "payment-card", Description: "Payment cards"},
|
||||||
{Name: "reason-card", Description: "Reason cards"},
|
{Name: "reason-card", Description: "Reason cards"},
|
||||||
{Name: "cards", Description: "Cards"},
|
{Name: "cards", Description: "Cards"},
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ var (
|
|||||||
ErrConflict = NewAppError(nil, "A user with this phone or username already exists.", "SE-00008")
|
ErrConflict = NewAppError(nil, "A user with this phone or username already exists.", "SE-00008")
|
||||||
ErrInvalidCode = NewAppError(nil, "Invalid or expired verification code.", "SE-00009")
|
ErrInvalidCode = NewAppError(nil, "Invalid or expired verification code.", "SE-00009")
|
||||||
ErrPasswordMismatch = NewAppError(nil, "Password confirmation does not match.", "SE-00010")
|
ErrPasswordMismatch = NewAppError(nil, "Password confirmation does not match.", "SE-00010")
|
||||||
|
ErrDuplicate = NewAppError(nil, "A record with these values already exists.", "SE-00012")
|
||||||
)
|
)
|
||||||
|
|
||||||
type AppError struct {
|
type AppError struct {
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"online-back/pkg/logging"
|
"online-back/pkg/logging"
|
||||||
"online-back/pkg/repository/genericrepo"
|
"online-back/pkg/repository/genericrepo"
|
||||||
|
|
||||||
|
"github.com/jackc/pgconn"
|
||||||
"github.com/jackc/pgx/v4"
|
"github.com/jackc/pgx/v4"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -125,7 +126,11 @@ func (r *repository) Create(ctx context.Context, dto currency.CreateCurrencyDTO)
|
|||||||
LEFT JOIN users cu ON cu.id = c.created_by
|
LEFT JOIN users cu ON cu.id = c.created_by
|
||||||
LEFT JOIN users uu ON uu.id = c.updated_by`
|
LEFT JOIN users uu ON uu.id = c.updated_by`
|
||||||
|
|
||||||
return scanCurrencyWithUsers(r.client.QueryRow(ctx, query, from, to, value, dto.CreatedBy))
|
item, err := scanCurrencyWithUsers(r.client.QueryRow(ctx, query, from, to, value, dto.CreatedBy))
|
||||||
|
if isUniqueViolation(err) {
|
||||||
|
return currency.CurrencyDTO{}, currency.ErrDuplicate
|
||||||
|
}
|
||||||
|
return item, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repository) Update(ctx context.Context, id int64, dto currency.UpdateCurrencyDTO) (currency.CurrencyDTO, error) {
|
func (r *repository) Update(ctx context.Context, id int64, dto currency.UpdateCurrencyDTO) (currency.CurrencyDTO, error) {
|
||||||
@@ -148,6 +153,9 @@ func (r *repository) Update(ctx context.Context, id int64, dto currency.UpdateCu
|
|||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return currency.CurrencyDTO{}, err
|
return currency.CurrencyDTO{}, err
|
||||||
}
|
}
|
||||||
|
if isUniqueViolation(err) {
|
||||||
|
return currency.CurrencyDTO{}, currency.ErrDuplicate
|
||||||
|
}
|
||||||
return item, err
|
return item, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,6 +163,15 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
|||||||
return r.generic.Delete(ctx, id)
|
return r.generic.Delete(ctx, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// isUniqueViolation reports whether err is a Postgres unique-constraint
|
||||||
|
// violation (e.g. the currencies_from_to_idx partial unique index rejecting
|
||||||
|
// a duplicate active currency_from/currency_to pair), so callers can map it
|
||||||
|
// to a clean 409 instead of letting it fall through as a generic 500.
|
||||||
|
func isUniqueViolation(err error) bool {
|
||||||
|
var pgErr *pgconn.PgError
|
||||||
|
return errors.As(err, &pgErr) && pgErr.Code == "23505"
|
||||||
|
}
|
||||||
|
|
||||||
func normalizeRate(from, to string, value currency.RateValue) (string, string, string) {
|
func normalizeRate(from, to string, value currency.RateValue) (string, string, string) {
|
||||||
return strings.ToUpper(strings.TrimSpace(from)),
|
return strings.ToUpper(strings.TrimSpace(from)),
|
||||||
strings.ToUpper(strings.TrimSpace(to)),
|
strings.ToUpper(strings.TrimSpace(to)),
|
||||||
|
|||||||
@@ -110,6 +110,7 @@ func (h *handler) getByID(c *gin.Context) {
|
|||||||
// @Param body body CreateCurrencyDTO true "Currency rate payload"
|
// @Param body body CreateCurrencyDTO true "Currency rate payload"
|
||||||
// @Success 201 {object} CurrencyDTO
|
// @Success 201 {object} CurrencyDTO
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 409 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /currencies [post]
|
// @Router /currencies [post]
|
||||||
func (h *handler) create(c *gin.Context) {
|
func (h *handler) create(c *gin.Context) {
|
||||||
@@ -122,6 +123,10 @@ func (h *handler) create(c *gin.Context) {
|
|||||||
dto.CreatedBy = currentUserID(c)
|
dto.CreatedBy = currentUserID(c)
|
||||||
|
|
||||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||||
|
if errors.Is(err, ErrDuplicate) {
|
||||||
|
c.JSON(http.StatusConflict, appresult.ErrDuplicate)
|
||||||
|
return
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Errorf("create currency failed: %v", err)
|
h.logger.Errorf("create currency failed: %v", err)
|
||||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
@@ -143,6 +148,7 @@ func (h *handler) create(c *gin.Context) {
|
|||||||
// @Success 200 {object} CurrencyDTO
|
// @Success 200 {object} CurrencyDTO
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 404 {object} appresult.AppError
|
// @Failure 404 {object} appresult.AppError
|
||||||
|
// @Failure 409 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /currencies/{id} [put]
|
// @Router /currencies/{id} [put]
|
||||||
func (h *handler) update(c *gin.Context) {
|
func (h *handler) update(c *gin.Context) {
|
||||||
@@ -165,6 +171,10 @@ func (h *handler) update(c *gin.Context) {
|
|||||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if errors.Is(err, ErrDuplicate) {
|
||||||
|
c.JSON(http.StatusConflict, appresult.ErrDuplicate)
|
||||||
|
return
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Errorf("update currency failed: %v", err)
|
h.logger.Errorf("update currency failed: %v", err)
|
||||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
|
|||||||
@@ -1,6 +1,14 @@
|
|||||||
package currency
|
package currency
|
||||||
|
|
||||||
import "context"
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrDuplicate is returned by Repository.Create/Update when the
|
||||||
|
// currency_from/currency_to pair already exists among active (non-deleted)
|
||||||
|
// rows, so the handler can respond with a clean 409 instead of a raw 500.
|
||||||
|
var ErrDuplicate = errors.New("currency pair already exists")
|
||||||
|
|
||||||
type Repository interface {
|
type Repository interface {
|
||||||
List(ctx context.Context, filter ListFilter) (ListCurrencyDTO, error)
|
List(ctx context.Context, filter ListFilter) (ListCurrencyDTO, error)
|
||||||
|
|||||||
@@ -80,19 +80,9 @@ const profilePermissionsJSON = `COALESCE((
|
|||||||
) ORDER BY p.module, p.id)
|
) ORDER BY p.module, p.id)
|
||||||
FROM permissions p
|
FROM permissions p
|
||||||
WHERE p.deleted_at IS NULL
|
WHERE p.deleted_at IS NULL
|
||||||
AND NOT EXISTS (
|
AND EXISTS (
|
||||||
SELECT 1 FROM permission_user pu
|
SELECT 1 FROM permission_role pr
|
||||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'deny' AND pu.deleted_at IS NULL
|
WHERE pr.role_id = r.id AND pr.permission_id = p.id AND pr.deleted_at IS NULL
|
||||||
)
|
|
||||||
AND (
|
|
||||||
EXISTS (
|
|
||||||
SELECT 1 FROM permission_user pu
|
|
||||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'allow' AND pu.deleted_at IS NULL
|
|
||||||
)
|
|
||||||
OR 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
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
), '[]'::json)`
|
), '[]'::json)`
|
||||||
|
|
||||||
|
|||||||
@@ -1,60 +0,0 @@
|
|||||||
package db
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"online-back/internal/identity/permissionuser"
|
|
||||||
"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) permissionuser.Repository {
|
|
||||||
return &repository{client: client, logger: logger}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) Create(ctx context.Context, dto permissionuser.CreatePermissionUserDTO) (permissionuser.PermissionUserDTO, error) {
|
|
||||||
query := `
|
|
||||||
WITH upserted AS (
|
|
||||||
INSERT INTO permission_user (permission_id, user_id, effect)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
ON CONFLICT (permission_id, user_id) WHERE deleted_at IS NULL DO UPDATE SET
|
|
||||||
effect = EXCLUDED.effect,
|
|
||||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
|
||||||
RETURNING id, permission_id, user_id, effect, created_at, updated_at
|
|
||||||
)
|
|
||||||
SELECT upserted.id, upserted.permission_id, p.name, upserted.user_id, u.name, upserted.effect, upserted.created_at, upserted.updated_at
|
|
||||||
FROM upserted
|
|
||||||
JOIN permissions p ON p.id = upserted.permission_id
|
|
||||||
JOIN users u ON u.id = upserted.user_id`
|
|
||||||
|
|
||||||
row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.UserId, dto.Effect)
|
|
||||||
return scanPermissionUser(row)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
|
||||||
return genericrepo.Delete(ctx, r.client, "permission_user", id)
|
|
||||||
}
|
|
||||||
|
|
||||||
func scanPermissionUser(row genericrepo.Scanner) (permissionuser.PermissionUserDTO, error) {
|
|
||||||
var item permissionuser.PermissionUserDTO
|
|
||||||
|
|
||||||
err := row.Scan(
|
|
||||||
&item.Id, &item.PermissionId, &item.PermissionName, &item.UserId, &item.UserName, &item.Effect, &item.CreatedAt, &item.UpdatedAt,
|
|
||||||
)
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return permissionuser.PermissionUserDTO{}, err
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return permissionuser.PermissionUserDTO{}, err
|
|
||||||
}
|
|
||||||
return item, nil
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
package permissionuser
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
type PermissionUserDTO struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
UserId int64 `json:"userId"`
|
|
||||||
UserName string `json:"userName"`
|
|
||||||
PermissionId int64 `json:"permissionId"`
|
|
||||||
PermissionName string `json:"permissionName"`
|
|
||||||
Effect string `json:"effect"`
|
|
||||||
CreatedAt time.Time `json:"createdAt"`
|
|
||||||
UpdatedAt time.Time `json:"updatedAt"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type CreatePermissionUserDTO struct {
|
|
||||||
PermissionId int64 `json:"permissionId" binding:"required"`
|
|
||||||
UserId int64 `json:"userId" binding:"required"`
|
|
||||||
Effect string `json:"effect" binding:"required,oneof=allow deny"`
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
package permissionuser
|
|
||||||
|
|
||||||
import (
|
|
||||||
"online-back/internal/appresult"
|
|
||||||
"online-back/internal/handlers"
|
|
||||||
"online-back/internal/shared"
|
|
||||||
"online-back/pkg/logging"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
const baseURL = "/permission-users"
|
|
||||||
|
|
||||||
type handler struct {
|
|
||||||
logger *logging.Logger
|
|
||||||
repository Repository
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
|
||||||
return &handler{logger: logger, repository: repository}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *handler) Register(router *gin.RouterGroup) {
|
|
||||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
|
||||||
group.POST("", h.create)
|
|
||||||
group.DELETE("/:id", h.delete)
|
|
||||||
}
|
|
||||||
|
|
||||||
// create godoc
|
|
||||||
// @Summary Assign a permission override to a user
|
|
||||||
// @Description Grants ("allow") or revokes ("deny") a permission for a specific user on top of their role, or updates the effect if the pair is already assigned
|
|
||||||
// @Tags permission-users
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Param body body CreatePermissionUserDTO true "Permission-user payload"
|
|
||||||
// @Success 201 {object} appresult.AppSuccess
|
|
||||||
// @Failure 400 {object} appresult.AppError
|
|
||||||
// @Failure 500 {object} appresult.AppError
|
|
||||||
// @Router /permission-users [post]
|
|
||||||
func (h *handler) create(c *gin.Context) {
|
|
||||||
shared.CreateAssoc[CreatePermissionUserDTO, PermissionUserDTO](c, h.logger, h.repository, "permission user")
|
|
||||||
}
|
|
||||||
|
|
||||||
// delete godoc
|
|
||||||
// @Summary Remove a user's permission override
|
|
||||||
// @Description Deletes a permission-user assignment, falling back to the user's role for that permission
|
|
||||||
// @Tags permission-users
|
|
||||||
// @Produce json
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Param id path int true "Permission-user ID"
|
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
|
||||||
// @Failure 400 {object} appresult.AppError
|
|
||||||
// @Failure 404 {object} appresult.AppError
|
|
||||||
// @Failure 500 {object} appresult.AppError
|
|
||||||
// @Router /permission-users/{id} [delete]
|
|
||||||
func (h *handler) delete(c *gin.Context) {
|
|
||||||
shared.DeleteAssoc[CreatePermissionUserDTO, PermissionUserDTO](c, h.logger, h.repository, "permission user")
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
package permissionuser
|
|
||||||
|
|
||||||
import "context"
|
|
||||||
|
|
||||||
type Repository interface {
|
|
||||||
Create(ctx context.Context, dto CreatePermissionUserDTO) (PermissionUserDTO, error)
|
|
||||||
Delete(ctx context.Context, id int64) error
|
|
||||||
}
|
|
||||||
@@ -18,14 +18,15 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
roleUser = "user"
|
roleUser = "user"
|
||||||
roleOperator = "operator"
|
roleOperator = "operator"
|
||||||
guardWeb = "web"
|
roleSuperadmin = "superadmin"
|
||||||
guardOperator = "operator"
|
guardWeb = "web"
|
||||||
guardAdmin = "admin"
|
guardOperator = "operator"
|
||||||
adminPrefix = "/api/admin"
|
guardAdmin = "admin"
|
||||||
contextRole = "role"
|
adminPrefix = "/api/admin"
|
||||||
contextGuard = "guard"
|
contextRole = "role"
|
||||||
|
contextGuard = "guard"
|
||||||
)
|
)
|
||||||
|
|
||||||
func RequirePermission(service Authorizer, code string) gin.HandlerFunc {
|
func RequirePermission(service Authorizer, code string) gin.HandlerFunc {
|
||||||
@@ -96,12 +97,52 @@ func Guard(service Authorizer) gin.HandlerFunc {
|
|||||||
c.Next()
|
c.Next()
|
||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
c.Next()
|
enforceAdmin(c, service, userID, code)
|
||||||
return
|
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) {
|
func enforceOperator(c *gin.Context, service Authorizer, userID int64) {
|
||||||
ids, err := service.BranchIDs(c.Request.Context(), userID)
|
ids, err := service.BranchIDs(c.Request.Context(), userID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -120,6 +161,18 @@ func enforceOperator(c *gin.Context, service Authorizer, userID int64) {
|
|||||||
return
|
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 operator path", logrus.Fields{"userId": userID, "module": module})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if perm := operatorPathPermission(c.Request.Method, c.Request.URL.Path); perm != "" {
|
if perm := operatorPathPermission(c.Request.Method, c.Request.URL.Path); perm != "" {
|
||||||
granted, err := service.HasPermission(c.Request.Context(), userID, perm)
|
granted, err := service.HasPermission(c.Request.Context(), userID, perm)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -485,10 +538,13 @@ func adminREST(path string) string {
|
|||||||
return rest
|
return rest
|
||||||
}
|
}
|
||||||
|
|
||||||
// operatorPathPermission returns "cards" or "loans" for saha endpoints.
|
// operatorPathModule returns the permission module ("cards" or "loans") that
|
||||||
// Empty string: shared catalog (profile, file, dashboard, branches, provinces,
|
// guards a saha endpoint. Matching by module rather than a fixed code lets an
|
||||||
// users/clients, currencies read) — any operator may call it.
|
// admin grant access under a new permission code created in that module
|
||||||
func operatorPathPermission(method, path string) string {
|
// (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)
|
rest := adminREST(path)
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
@@ -512,7 +568,19 @@ func operatorPathPermission(method, path string) string {
|
|||||||
"/loans-documents",
|
"/loans-documents",
|
||||||
}):
|
}):
|
||||||
return "loans"
|
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"}):
|
case matchesPrefix(rest, []string{"/users/clients"}):
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
@@ -526,6 +594,46 @@ func operatorPathPermission(method, path string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// adminPathPermission returns the "<module>.view"/"<module>.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")
|
||||||
|
}
|
||||||
|
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func viewOrManage(method, module string) string {
|
||||||
|
if method == http.MethodGet {
|
||||||
|
return module + ".view"
|
||||||
|
}
|
||||||
|
return module + ".manage"
|
||||||
|
}
|
||||||
|
|
||||||
var operatorWritePrefixes = []string{
|
var operatorWritePrefixes = []string{
|
||||||
"/profile",
|
"/profile",
|
||||||
"/file",
|
"/file",
|
||||||
|
|||||||
@@ -160,10 +160,10 @@ func TestOperatorCardsAndLoansSahalar(t *testing.T) {
|
|||||||
if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/card-balances", "7", nil); status != http.StatusForbidden {
|
if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/card-balances", "7", nil); status != http.StatusForbidden {
|
||||||
t.Fatalf("loans GET balances=%d", status)
|
t.Fatalf("loans GET balances=%d", status)
|
||||||
}
|
}
|
||||||
if got := operatorPathPermission(http.MethodGet, "/api/admin/card-balances"); got != "cards" {
|
if got := operatorPathModule(http.MethodGet, "/api/admin/card-balances"); got != "cards" {
|
||||||
t.Fatalf("card-balances path=%q", got)
|
t.Fatalf("card-balances path=%q", got)
|
||||||
}
|
}
|
||||||
if got := operatorPathPermission(http.MethodPost, "/api/admin/card-orders"); got != "cards" {
|
if got := operatorPathModule(http.MethodPost, "/api/admin/card-orders"); got != "cards" {
|
||||||
t.Fatalf("card-orders path=%q", got)
|
t.Fatalf("card-orders path=%q", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -187,22 +187,22 @@ func TestAllCardAndLoanRoutesMapped(t *testing.T) {
|
|||||||
"/api/admin/loans-documents",
|
"/api/admin/loans-documents",
|
||||||
}
|
}
|
||||||
for _, path := range cardPaths {
|
for _, path := range cardPaths {
|
||||||
if got := operatorPathPermission(http.MethodGet, path); got != "cards" {
|
if got := operatorPathModule(http.MethodGet, path); got != "cards" {
|
||||||
t.Errorf("GET %s perm=%q, want cards", path, got)
|
t.Errorf("GET %s module=%q, want cards", path, got)
|
||||||
}
|
}
|
||||||
if got := operatorPathPermission(http.MethodPost, path); got != "cards" {
|
if got := operatorPathModule(http.MethodPost, path); got != "cards" {
|
||||||
t.Errorf("POST %s perm=%q, want cards", path, got)
|
t.Errorf("POST %s module=%q, want cards", path, got)
|
||||||
}
|
}
|
||||||
if !operatorRoleAllows(http.MethodGet, path) || !operatorRoleAllows(http.MethodPost, path) {
|
if !operatorRoleAllows(http.MethodGet, path) || !operatorRoleAllows(http.MethodPost, path) {
|
||||||
t.Errorf("%s not on operator allowlist", path)
|
t.Errorf("%s not on operator allowlist", path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, path := range loanPaths {
|
for _, path := range loanPaths {
|
||||||
if got := operatorPathPermission(http.MethodGet, path); got != "loans" {
|
if got := operatorPathModule(http.MethodGet, path); got != "loans" {
|
||||||
t.Errorf("GET %s perm=%q, want loans", path, got)
|
t.Errorf("GET %s module=%q, want loans", path, got)
|
||||||
}
|
}
|
||||||
if got := operatorPathPermission(http.MethodPost, path); got != "loans" {
|
if got := operatorPathModule(http.MethodPost, path); got != "loans" {
|
||||||
t.Errorf("POST %s perm=%q, want loans", path, got)
|
t.Errorf("POST %s module=%q, want loans", path, got)
|
||||||
}
|
}
|
||||||
if !operatorRoleAllows(http.MethodGet, path) || !operatorRoleAllows(http.MethodPost, path) {
|
if !operatorRoleAllows(http.MethodGet, path) || !operatorRoleAllows(http.MethodPost, path) {
|
||||||
t.Errorf("%s not on operator allowlist", path)
|
t.Errorf("%s not on operator allowlist", path)
|
||||||
@@ -378,6 +378,72 @@ func TestGuardMatrix(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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/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) {
|
func TestGuardOptionsAndPublicSkipAuthz(t *testing.T) {
|
||||||
gin.SetMode(gin.TestMode)
|
gin.SetMode(gin.TestMode)
|
||||||
auth := &stubAuth{role: roleUser}
|
auth := &stubAuth{role: roleUser}
|
||||||
@@ -655,6 +721,13 @@ func (s *stubAuth) HasPermission(_ context.Context, _ int64, code string) (bool,
|
|||||||
return s.perms[code], 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) {
|
func (s *stubAuth) UserVisibleInBranches(context.Context, int64, []int64) (bool, error) {
|
||||||
return s.visible, s.visibleErr
|
return s.visible, s.visibleErr
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,35 +22,20 @@ type Authorizer interface {
|
|||||||
RoleLookup(ctx context.Context, userID int64) (code, guardName string, err error)
|
RoleLookup(ctx context.Context, userID int64) (code, guardName string, err error)
|
||||||
BranchIDs(ctx context.Context, userID int64) ([]int64, error)
|
BranchIDs(ctx context.Context, userID int64) ([]int64, error)
|
||||||
HasPermission(ctx context.Context, userID int64, code string) (bool, 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)
|
UserVisibleInBranches(ctx context.Context, userID int64, branchIDs []int64) (bool, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// HasPermission checks the role's baseline grant, then lets a per-user
|
// HasPermission checks whether the user's role grants the exact permission code.
|
||||||
// permission_user override win: an explicit "deny" always wins (even over
|
|
||||||
// another allow), an explicit "allow" grants a permission the role does
|
|
||||||
// not, and no override falls back to the role.
|
|
||||||
func (s *Service) HasPermission(ctx context.Context, userID int64, code string) (bool, error) {
|
func (s *Service) HasPermission(ctx context.Context, userID int64, code string) (bool, error) {
|
||||||
const query = `
|
const query = `
|
||||||
SELECT
|
SELECT EXISTS (
|
||||||
CASE
|
SELECT 1
|
||||||
WHEN EXISTS (
|
FROM role_user ru
|
||||||
SELECT 1 FROM permission_user pu
|
JOIN permission_role pr ON pr.role_id = ru.role_id
|
||||||
JOIN permissions p ON p.id = pu.permission_id
|
JOIN permissions p ON p.id = pr.permission_id
|
||||||
WHERE pu.user_id = $1 AND p.code = $2 AND pu.effect = 'deny' AND pu.deleted_at IS NULL
|
WHERE ru.user_id = $1 AND p.code = $2 AND ru.deleted_at IS NULL AND pr.deleted_at IS NULL
|
||||||
) THEN false
|
)`
|
||||||
WHEN EXISTS (
|
|
||||||
SELECT 1 FROM permission_user pu
|
|
||||||
JOIN permissions p ON p.id = pu.permission_id
|
|
||||||
WHERE pu.user_id = $1 AND p.code = $2 AND pu.effect = 'allow' AND pu.deleted_at IS NULL
|
|
||||||
) THEN true
|
|
||||||
ELSE 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
|
|
||||||
)
|
|
||||||
END`
|
|
||||||
|
|
||||||
var granted bool
|
var granted bool
|
||||||
if err := s.client.QueryRow(ctx, query, userID, code).Scan(&granted); err != nil {
|
if err := s.client.QueryRow(ctx, query, userID, code).Scan(&granted); err != nil {
|
||||||
@@ -59,6 +44,26 @@ func (s *Service) HasPermission(ctx context.Context, userID int64, code string)
|
|||||||
return granted, nil
|
return granted, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
)`
|
||||||
|
|
||||||
|
var granted bool
|
||||||
|
if err := s.client.QueryRow(ctx, query, userID, module).Scan(&granted); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return granted, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Service) RoleLookup(ctx context.Context, userID int64) (string, string, error) {
|
func (s *Service) RoleLookup(ctx context.Context, userID int64) (string, string, error) {
|
||||||
const query = `
|
const query = `
|
||||||
SELECT r.code, r.guard_name
|
SELECT r.code, r.guard_name
|
||||||
|
|||||||
@@ -10,8 +10,6 @@ import (
|
|||||||
permissiondb "online-back/internal/identity/permission/db"
|
permissiondb "online-back/internal/identity/permission/db"
|
||||||
"online-back/internal/identity/permissionrole"
|
"online-back/internal/identity/permissionrole"
|
||||||
permissionroledb "online-back/internal/identity/permissionrole/db"
|
permissionroledb "online-back/internal/identity/permissionrole/db"
|
||||||
"online-back/internal/identity/permissionuser"
|
|
||||||
permissionuserdb "online-back/internal/identity/permissionuser/db"
|
|
||||||
"online-back/internal/identity/role"
|
"online-back/internal/identity/role"
|
||||||
roledb "online-back/internal/identity/role/db"
|
roledb "online-back/internal/identity/role/db"
|
||||||
"online-back/internal/identity/roleusers"
|
"online-back/internal/identity/roleusers"
|
||||||
@@ -45,7 +43,6 @@ func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handl
|
|||||||
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
|
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
|
||||||
roleusers.NewHandler(logger, roleusersdb.NewRepository(client, logger)),
|
roleusers.NewHandler(logger, roleusersdb.NewRepository(client, logger)),
|
||||||
permissionrole.NewHandler(logger, permissionroledb.NewRepository(client, logger)),
|
permissionrole.NewHandler(logger, permissionroledb.NewRepository(client, logger)),
|
||||||
permissionuser.NewHandler(logger, permissionuserdb.NewRepository(client, logger)),
|
|
||||||
userbranch.NewHandler(logger, userbranchdb.NewRepository(client, logger)),
|
userbranch.NewHandler(logger, userbranchdb.NewRepository(client, logger)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -67,19 +67,9 @@ const userPermissionsJSON = `COALESCE((
|
|||||||
) ORDER BY p.module, p.id)
|
) ORDER BY p.module, p.id)
|
||||||
FROM permissions p
|
FROM permissions p
|
||||||
WHERE p.deleted_at IS NULL
|
WHERE p.deleted_at IS NULL
|
||||||
AND NOT EXISTS (
|
AND EXISTS (
|
||||||
SELECT 1 FROM permission_user pu
|
SELECT 1 FROM permission_role pr
|
||||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'deny' AND pu.deleted_at IS NULL
|
WHERE pr.role_id = r.id AND pr.permission_id = p.id AND pr.deleted_at IS NULL
|
||||||
)
|
|
||||||
AND (
|
|
||||||
EXISTS (
|
|
||||||
SELECT 1 FROM permission_user pu
|
|
||||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'allow' AND pu.deleted_at IS NULL
|
|
||||||
)
|
|
||||||
OR 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
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
), '[]'::json)`
|
), '[]'::json)`
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math/rand"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"online-back/internal/identity/rbac"
|
"online-back/internal/identity/rbac"
|
||||||
@@ -20,9 +19,8 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// regionUniqueCodePrefix maps a branch's region code to the 2-digit prefix
|
// regionUniqueCodePrefix maps a branch's region code to the 2-digit prefix
|
||||||
// used when generating its unique_code. The suffix is 2 random digits, so
|
// its unique_code must start with, so a branch's code always identifies its
|
||||||
// each region can hold at most 100 branches before generateUniqueCode's
|
// region at a glance.
|
||||||
// retry budget is exhausted.
|
|
||||||
var regionUniqueCodePrefix = map[string]string{
|
var regionUniqueCodePrefix = map[string]string{
|
||||||
"AG": "13", // Aşgabat
|
"AG": "13", // Aşgabat
|
||||||
"AH": "23", // Ahal
|
"AH": "23", // Ahal
|
||||||
@@ -32,14 +30,18 @@ var regionUniqueCodePrefix = map[string]string{
|
|||||||
"LB": "83", // Lebap
|
"LB": "83", // Lebap
|
||||||
}
|
}
|
||||||
|
|
||||||
const maxUniqueCodeAttempts = 20
|
// validateUniqueCode checks that a client-supplied unique_code starts with
|
||||||
|
// the 2-digit prefix for the given region (the DTO's "numeric,len=4" binding
|
||||||
func generateUniqueCode(region string) (string, error) {
|
// already guarantees 4 digits).
|
||||||
|
func validateUniqueCode(region, code string) error {
|
||||||
prefix, ok := regionUniqueCodePrefix[region]
|
prefix, ok := regionUniqueCodePrefix[region]
|
||||||
if !ok {
|
if !ok {
|
||||||
return "", fmt.Errorf("unsupported region")
|
return fmt.Errorf("unsupported region")
|
||||||
}
|
}
|
||||||
return prefix + fmt.Sprintf("%02d", rand.Intn(100)), nil
|
if !strings.HasPrefix(code, prefix) {
|
||||||
|
return fmt.Errorf("unique code must start with %s for region %s", prefix, region)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type repository struct {
|
type repository struct {
|
||||||
@@ -172,6 +174,9 @@ func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) (
|
|||||||
if err := r.ensureProvince(ctx, dto.ProvinceId); err != nil {
|
if err := r.ensureProvince(ctx, dto.ProvinceId); err != nil {
|
||||||
return branches.BranchDTO{}, err
|
return branches.BranchDTO{}, err
|
||||||
}
|
}
|
||||||
|
if err := validateUniqueCode(dto.Region, dto.UniqueCode); err != nil {
|
||||||
|
return branches.BranchDTO{}, err
|
||||||
|
}
|
||||||
|
|
||||||
name, address, err := marshalBranchJSON(dto.Name, dto.Address)
|
name, address, err := marshalBranchJSON(dto.Name, dto.Address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -197,26 +202,17 @@ func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) (
|
|||||||
FROM inserted i
|
FROM inserted i
|
||||||
LEFT JOIN provinces p ON p.id = i.province_id`
|
LEFT JOIN provinces p ON p.id = i.province_id`
|
||||||
|
|
||||||
for attempt := 0; attempt < maxUniqueCodeAttempts; attempt++ {
|
row := r.client.QueryRow(ctx, query,
|
||||||
code, err := generateUniqueCode(dto.Region)
|
dto.UniqueCode, name, address, dto.Region, dto.ProvinceId, dto.PhoneNumbers,
|
||||||
if err != nil {
|
dto.BillingUsername, dto.BillingPassword, dto.BillingSberUsername, dto.BillingSberPassword,
|
||||||
return branches.BranchDTO{}, err
|
dto.BillingVisaMasterUsername, dto.BillingVisaMasterPassword,
|
||||||
}
|
dto.BillingSwiftUsername, dto.BillingSwiftPassword, active,
|
||||||
|
)
|
||||||
row := r.client.QueryRow(ctx, query,
|
item, err := scanBranch(row)
|
||||||
code, name, address, dto.Region, dto.ProvinceId, dto.PhoneNumbers,
|
if isUniqueViolation(err) {
|
||||||
dto.BillingUsername, dto.BillingPassword, dto.BillingSberUsername, dto.BillingSberPassword,
|
return branches.BranchDTO{}, fmt.Errorf("unique code already exists")
|
||||||
dto.BillingVisaMasterUsername, dto.BillingVisaMasterPassword,
|
|
||||||
dto.BillingSwiftUsername, dto.BillingSwiftPassword, active,
|
|
||||||
)
|
|
||||||
item, err := scanBranch(row)
|
|
||||||
if isUniqueViolation(err) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
return item, err
|
|
||||||
}
|
}
|
||||||
|
return item, err
|
||||||
return branches.BranchDTO{}, fmt.Errorf("could not generate a unique branch code, try again")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBranchDTO) (branches.BranchDTO, error) {
|
func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBranchDTO) (branches.BranchDTO, error) {
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ type BranchDTO struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type CreateBranchDTO struct {
|
type CreateBranchDTO struct {
|
||||||
|
UniqueCode string `json:"uniqueCode" binding:"required,numeric,len=4"`
|
||||||
Name LocalizedText `json:"name" binding:"required"`
|
Name LocalizedText `json:"name" binding:"required"`
|
||||||
Address LocalizedText `json:"address" binding:"required"`
|
Address LocalizedText `json:"address" binding:"required"`
|
||||||
Region string `json:"region" binding:"required"`
|
Region string `json:"region" binding:"required"`
|
||||||
|
|||||||
@@ -290,8 +290,11 @@ func (h *handler) delete(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func isClientError(err error) bool {
|
func isClientError(err error) bool {
|
||||||
switch err.Error() {
|
switch {
|
||||||
case "province not found", "unsupported region", "could not generate a unique branch code, try again":
|
case err.Error() == "province not found",
|
||||||
|
err.Error() == "unsupported region",
|
||||||
|
err.Error() == "unique code already exists",
|
||||||
|
strings.HasPrefix(err.Error(), "unique code must start with"):
|
||||||
return true
|
return true
|
||||||
default:
|
default:
|
||||||
return false
|
return false
|
||||||
|
|||||||
Reference in new issue
Block a user