ch logika
This commit is contained in:
@@ -16,7 +16,6 @@ DROP TABLE IF EXISTS card_types;
|
||||
DROP TABLE IF EXISTS branch_user;
|
||||
DROP TABLE IF EXISTS branches;
|
||||
DROP TABLE IF EXISTS provinces;
|
||||
DROP TABLE IF EXISTS permission_user;
|
||||
DROP TABLE IF EXISTS permission_role;
|
||||
DROP TABLE IF EXISTS role_user;
|
||||
DROP TABLE IF EXISTS permissions;
|
||||
@@ -64,7 +63,6 @@ DROP INDEX IF EXISTS idx_permissions_module;
|
||||
DROP INDEX IF EXISTS idx_permissions_guard_name;
|
||||
DROP INDEX IF EXISTS idx_roles_code;
|
||||
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 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)
|
||||
);
|
||||
|
||||
-- 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 (
|
||||
id bigserial PRIMARY KEY,
|
||||
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 (
|
||||
id bigserial PRIMARY KEY,
|
||||
unique_id character varying(255),
|
||||
region character varying(2) NOT NULL,
|
||||
region character varying(255) NOT NULL,
|
||||
branch_id bigint NOT NULL,
|
||||
user_id bigint,
|
||||
customer_name character varying(255) NOT NULL,
|
||||
@@ -525,7 +509,6 @@ CREATE TABLE IF NOT EXISTS currencies (
|
||||
-- table scan.
|
||||
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_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_permissions_code ON permissions(code);
|
||||
CREATE INDEX IF NOT EXISTS idx_permissions_module ON permissions(module);
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
-- 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;
|
||||
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 branches 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 role_user 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 role_user 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 branches 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
|
||||
-- only, so a soft-deleted row's unique value (username, phone, branch code,
|
||||
-- backup file name, currency pair, permission-role/permission-user pair) can
|
||||
-- be reused by a new row.
|
||||
-- backup file name, currency pair, permission-role pair) can be reused by a
|
||||
-- new row.
|
||||
|
||||
DROP INDEX IF EXISTS 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
|
||||
ON permission_role (permission_id, role_id)
|
||||
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);
|
||||
43
db/seed.sql
43
db/seed.sql
@@ -2,13 +2,13 @@
|
||||
-- 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
|
||||
-- admin@bank.tm
|
||||
-- manager@bank.tm
|
||||
-- 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 — walýuta)
|
||||
-- currency@bank.tm (admin guard — diňe walýuta sahasy)
|
||||
-- serdar@bank.tm … leyla@bank.tm (role=user)
|
||||
|
||||
BEGIN;
|
||||
@@ -34,7 +34,6 @@ TRUNCATE TABLE
|
||||
branches,
|
||||
provinces,
|
||||
permission_role,
|
||||
permission_user,
|
||||
role_user,
|
||||
permissions,
|
||||
roles,
|
||||
@@ -119,13 +118,13 @@ INSERT INTO users (email, password, name, first_name, last_name, username, phone
|
||||
'loanop@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Loan Operator', 'Jeren', 'Atayeva', 'loanop',
|
||||
'+993 61 92 92 37', 'operator', true
|
||||
'+993 61 92 92 37', 'loan_operator', true
|
||||
),
|
||||
(
|
||||
'bothop@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'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
|
||||
('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'),
|
||||
@@ -181,14 +182,26 @@ FROM permissions p
|
||||
JOIN roles r ON r.code = 'operator'
|
||||
WHERE p.code = 'cards';
|
||||
|
||||
-- loanop (user 12): loans only — deny role cards, allow loans.
|
||||
-- bothop (user 13): keep role cards, add loans.
|
||||
INSERT INTO permission_user (permission_id, user_id, effect)
|
||||
SELECT p.id, 12, 'deny' FROM permissions p WHERE p.code = 'cards'
|
||||
UNION ALL
|
||||
SELECT p.id, 12, 'allow' FROM permissions p WHERE p.code = 'loans'
|
||||
UNION ALL
|
||||
SELECT p.id, 13, 'allow' FROM permissions p WHERE p.code = 'loans';
|
||||
-- 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)
|
||||
|
||||
150
docs/docs.go
150
docs/docs.go
@@ -2445,6 +2445,12 @@ const docTemplate = `{
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Conflict",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
@@ -2559,6 +2565,12 @@ const docTemplate = `{
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Conflict",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"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": {
|
||||
"get": {
|
||||
"security": [
|
||||
@@ -7451,7 +7360,8 @@ const docTemplate = `{
|
||||
"required": [
|
||||
"address",
|
||||
"name",
|
||||
"region"
|
||||
"region",
|
||||
"uniqueCode"
|
||||
],
|
||||
"properties": {
|
||||
"active": {
|
||||
@@ -7495,6 +7405,9 @@ const docTemplate = `{
|
||||
},
|
||||
"region": {
|
||||
"type": "string"
|
||||
},
|
||||
"uniqueCode": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -8554,9 +8467,6 @@ const docTemplate = `{
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"uniqueId": {
|
||||
"type": "string"
|
||||
},
|
||||
"userId": {
|
||||
"type": "integer"
|
||||
},
|
||||
@@ -8785,9 +8695,6 @@ const docTemplate = `{
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"uniqueId": {
|
||||
"type": "string"
|
||||
},
|
||||
"userId": {
|
||||
"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": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
|
||||
@@ -2439,6 +2439,12 @@
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Conflict",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
@@ -2553,6 +2559,12 @@
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Conflict",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"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": {
|
||||
"get": {
|
||||
"security": [
|
||||
@@ -7445,7 +7354,8 @@
|
||||
"required": [
|
||||
"address",
|
||||
"name",
|
||||
"region"
|
||||
"region",
|
||||
"uniqueCode"
|
||||
],
|
||||
"properties": {
|
||||
"active": {
|
||||
@@ -7489,6 +7399,9 @@
|
||||
},
|
||||
"region": {
|
||||
"type": "string"
|
||||
},
|
||||
"uniqueCode": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -8548,9 +8461,6 @@
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"uniqueId": {
|
||||
"type": "string"
|
||||
},
|
||||
"userId": {
|
||||
"type": "integer"
|
||||
},
|
||||
@@ -8779,9 +8689,6 @@
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"uniqueId": {
|
||||
"type": "string"
|
||||
},
|
||||
"userId": {
|
||||
"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": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
|
||||
@@ -137,10 +137,13 @@ definitions:
|
||||
type: integer
|
||||
region:
|
||||
type: string
|
||||
uniqueCode:
|
||||
type: string
|
||||
required:
|
||||
- address
|
||||
- name
|
||||
- region
|
||||
- uniqueCode
|
||||
type: object
|
||||
branches.LocalizedText:
|
||||
properties:
|
||||
@@ -861,8 +864,6 @@ definitions:
|
||||
type: string
|
||||
status:
|
||||
type: string
|
||||
uniqueId:
|
||||
type: string
|
||||
userId:
|
||||
type: integer
|
||||
workCompany:
|
||||
@@ -1022,8 +1023,6 @@ definitions:
|
||||
type: string
|
||||
status:
|
||||
type: string
|
||||
uniqueId:
|
||||
type: string
|
||||
userId:
|
||||
type: integer
|
||||
workCompany:
|
||||
@@ -1346,22 +1345,6 @@ definitions:
|
||||
- permissionId
|
||||
- roleId
|
||||
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:
|
||||
properties:
|
||||
active:
|
||||
@@ -3231,6 +3214,10 @@ paths:
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"409":
|
||||
description: Conflict
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
@@ -3336,6 +3323,10 @@ paths:
|
||||
description: Not Found
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"409":
|
||||
description: Conflict
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
@@ -4867,73 +4858,6 @@ paths:
|
||||
summary: Remove permission from role
|
||||
tags:
|
||||
- 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:
|
||||
get:
|
||||
description: Returns paginated permissions with optional filters
|
||||
|
||||
@@ -16,7 +16,6 @@ var swaggerTagOrder = []struct {
|
||||
{Name: "role-users", Description: "Role users"},
|
||||
{Name: "permission", Description: "Permissions"},
|
||||
{Name: "permission-roles", Description: "Permission roles"},
|
||||
{Name: "permission-users", Description: "Per-user permission overrides"},
|
||||
{Name: "payment-card", Description: "Payment cards"},
|
||||
{Name: "reason-card", Description: "Reason cards"},
|
||||
{Name: "cards", Description: "Cards"},
|
||||
|
||||
@@ -12,6 +12,7 @@ var (
|
||||
ErrConflict = NewAppError(nil, "A user with this phone or username already exists.", "SE-00008")
|
||||
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")
|
||||
)
|
||||
|
||||
type AppError struct {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgconn"
|
||||
"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 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) {
|
||||
@@ -148,6 +153,9 @@ func (r *repository) Update(ctx context.Context, id int64, dto currency.UpdateCu
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return currency.CurrencyDTO{}, err
|
||||
}
|
||||
if isUniqueViolation(err) {
|
||||
return currency.CurrencyDTO{}, currency.ErrDuplicate
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
@@ -155,6 +163,15 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
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) {
|
||||
return strings.ToUpper(strings.TrimSpace(from)),
|
||||
strings.ToUpper(strings.TrimSpace(to)),
|
||||
|
||||
@@ -110,6 +110,7 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
// @Param body body CreateCurrencyDTO true "Currency rate payload"
|
||||
// @Success 201 {object} CurrencyDTO
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 409 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /currencies [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
@@ -122,6 +123,10 @@ func (h *handler) create(c *gin.Context) {
|
||||
dto.CreatedBy = currentUserID(c)
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if errors.Is(err, ErrDuplicate) {
|
||||
c.JSON(http.StatusConflict, appresult.ErrDuplicate)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("create currency failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
@@ -143,6 +148,7 @@ func (h *handler) create(c *gin.Context) {
|
||||
// @Success 200 {object} CurrencyDTO
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 409 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /currencies/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
@@ -165,6 +171,10 @@ func (h *handler) update(c *gin.Context) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrDuplicate) {
|
||||
c.JSON(http.StatusConflict, appresult.ErrDuplicate)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update currency failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
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 {
|
||||
List(ctx context.Context, filter ListFilter) (ListCurrencyDTO, error)
|
||||
|
||||
@@ -80,19 +80,9 @@ const profilePermissionsJSON = `COALESCE((
|
||||
) ORDER BY p.module, p.id)
|
||||
FROM permissions p
|
||||
WHERE p.deleted_at IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM permission_user pu
|
||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'deny' AND pu.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
|
||||
)
|
||||
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
|
||||
)
|
||||
), '[]'::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 (
|
||||
roleUser = "user"
|
||||
roleOperator = "operator"
|
||||
guardWeb = "web"
|
||||
guardOperator = "operator"
|
||||
guardAdmin = "admin"
|
||||
adminPrefix = "/api/admin"
|
||||
contextRole = "role"
|
||||
contextGuard = "guard"
|
||||
roleUser = "user"
|
||||
roleOperator = "operator"
|
||||
roleSuperadmin = "superadmin"
|
||||
guardWeb = "web"
|
||||
guardOperator = "operator"
|
||||
guardAdmin = "admin"
|
||||
adminPrefix = "/api/admin"
|
||||
contextRole = "role"
|
||||
contextGuard = "guard"
|
||||
)
|
||||
|
||||
func RequirePermission(service Authorizer, code string) gin.HandlerFunc {
|
||||
@@ -96,12 +97,52 @@ func Guard(service Authorizer) gin.HandlerFunc {
|
||||
c.Next()
|
||||
return
|
||||
default:
|
||||
c.Next()
|
||||
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 {
|
||||
@@ -120,6 +161,18 @@ func enforceOperator(c *gin.Context, service Authorizer, userID int64) {
|
||||
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 != "" {
|
||||
granted, err := service.HasPermission(c.Request.Context(), userID, perm)
|
||||
if err != nil {
|
||||
@@ -485,10 +538,13 @@ func adminREST(path string) string {
|
||||
return rest
|
||||
}
|
||||
|
||||
// operatorPathPermission returns "cards" or "loans" for saha endpoints.
|
||||
// Empty string: shared catalog (profile, file, dashboard, branches, provinces,
|
||||
// users/clients, currencies read) — any operator may call it.
|
||||
func operatorPathPermission(method, path string) string {
|
||||
// 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 {
|
||||
@@ -512,7 +568,19 @@ func operatorPathPermission(method, path string) string {
|
||||
"/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 ""
|
||||
|
||||
@@ -526,6 +594,46 @@ func operatorPathPermission(method, path string) string {
|
||||
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{
|
||||
"/profile",
|
||||
"/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 {
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -187,22 +187,22 @@ func TestAllCardAndLoanRoutesMapped(t *testing.T) {
|
||||
"/api/admin/loans-documents",
|
||||
}
|
||||
for _, path := range cardPaths {
|
||||
if got := operatorPathPermission(http.MethodGet, path); got != "cards" {
|
||||
t.Errorf("GET %s perm=%q, want cards", path, got)
|
||||
if got := operatorPathModule(http.MethodGet, path); got != "cards" {
|
||||
t.Errorf("GET %s module=%q, want cards", path, got)
|
||||
}
|
||||
if got := operatorPathPermission(http.MethodPost, path); got != "cards" {
|
||||
t.Errorf("POST %s perm=%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 := operatorPathPermission(http.MethodGet, path); got != "loans" {
|
||||
t.Errorf("GET %s perm=%q, want loans", path, got)
|
||||
if got := operatorPathModule(http.MethodGet, path); got != "loans" {
|
||||
t.Errorf("GET %s module=%q, want loans", path, got)
|
||||
}
|
||||
if got := operatorPathPermission(http.MethodPost, path); got != "loans" {
|
||||
t.Errorf("POST %s perm=%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)
|
||||
@@ -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) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
auth := &stubAuth{role: roleUser}
|
||||
@@ -655,6 +721,13 @@ func (s *stubAuth) HasPermission(_ context.Context, _ int64, code string) (bool,
|
||||
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
|
||||
}
|
||||
|
||||
@@ -22,35 +22,20 @@ type Authorizer interface {
|
||||
RoleLookup(ctx context.Context, userID int64) (code, guardName string, err 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 the role's baseline grant, then lets a per-user
|
||||
// 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.
|
||||
// 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
|
||||
CASE
|
||||
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 = 'deny' AND pu.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`
|
||||
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
|
||||
)`
|
||||
|
||||
var granted bool
|
||||
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
|
||||
}
|
||||
|
||||
// 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) {
|
||||
const query = `
|
||||
SELECT r.code, r.guard_name
|
||||
|
||||
@@ -10,8 +10,6 @@ import (
|
||||
permissiondb "online-back/internal/identity/permission/db"
|
||||
"online-back/internal/identity/permissionrole"
|
||||
permissionroledb "online-back/internal/identity/permissionrole/db"
|
||||
"online-back/internal/identity/permissionuser"
|
||||
permissionuserdb "online-back/internal/identity/permissionuser/db"
|
||||
"online-back/internal/identity/role"
|
||||
roledb "online-back/internal/identity/role/db"
|
||||
"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)),
|
||||
roleusers.NewHandler(logger, roleusersdb.NewRepository(client, logger)),
|
||||
permissionrole.NewHandler(logger, permissionroledb.NewRepository(client, logger)),
|
||||
permissionuser.NewHandler(logger, permissionuserdb.NewRepository(client, logger)),
|
||||
userbranch.NewHandler(logger, userbranchdb.NewRepository(client, logger)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,19 +67,9 @@ const userPermissionsJSON = `COALESCE((
|
||||
) ORDER BY p.module, p.id)
|
||||
FROM permissions p
|
||||
WHERE p.deleted_at IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM permission_user pu
|
||||
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'deny' AND pu.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
|
||||
)
|
||||
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
|
||||
)
|
||||
), '[]'::json)`
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/rbac"
|
||||
@@ -20,9 +19,8 @@ import (
|
||||
)
|
||||
|
||||
// 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
|
||||
// each region can hold at most 100 branches before generateUniqueCode's
|
||||
// retry budget is exhausted.
|
||||
// its unique_code must start with, so a branch's code always identifies its
|
||||
// region at a glance.
|
||||
var regionUniqueCodePrefix = map[string]string{
|
||||
"AG": "13", // Aşgabat
|
||||
"AH": "23", // Ahal
|
||||
@@ -32,14 +30,18 @@ var regionUniqueCodePrefix = map[string]string{
|
||||
"LB": "83", // Lebap
|
||||
}
|
||||
|
||||
const maxUniqueCodeAttempts = 20
|
||||
|
||||
func generateUniqueCode(region string) (string, error) {
|
||||
// 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
|
||||
// already guarantees 4 digits).
|
||||
func validateUniqueCode(region, code string) error {
|
||||
prefix, ok := regionUniqueCodePrefix[region]
|
||||
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 {
|
||||
@@ -172,6 +174,9 @@ func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) (
|
||||
if err := r.ensureProvince(ctx, dto.ProvinceId); err != nil {
|
||||
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)
|
||||
if err != nil {
|
||||
@@ -197,26 +202,17 @@ func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) (
|
||||
FROM inserted i
|
||||
LEFT JOIN provinces p ON p.id = i.province_id`
|
||||
|
||||
for attempt := 0; attempt < maxUniqueCodeAttempts; attempt++ {
|
||||
code, err := generateUniqueCode(dto.Region)
|
||||
if err != nil {
|
||||
return branches.BranchDTO{}, err
|
||||
}
|
||||
|
||||
row := r.client.QueryRow(ctx, query,
|
||||
code, name, address, dto.Region, dto.ProvinceId, dto.PhoneNumbers,
|
||||
dto.BillingUsername, dto.BillingPassword, dto.BillingSberUsername, dto.BillingSberPassword,
|
||||
dto.BillingVisaMasterUsername, dto.BillingVisaMasterPassword,
|
||||
dto.BillingSwiftUsername, dto.BillingSwiftPassword, active,
|
||||
)
|
||||
item, err := scanBranch(row)
|
||||
if isUniqueViolation(err) {
|
||||
continue
|
||||
}
|
||||
return item, err
|
||||
row := r.client.QueryRow(ctx, query,
|
||||
dto.UniqueCode, name, address, dto.Region, dto.ProvinceId, dto.PhoneNumbers,
|
||||
dto.BillingUsername, dto.BillingPassword, dto.BillingSberUsername, dto.BillingSberPassword,
|
||||
dto.BillingVisaMasterUsername, dto.BillingVisaMasterPassword,
|
||||
dto.BillingSwiftUsername, dto.BillingSwiftPassword, active,
|
||||
)
|
||||
item, err := scanBranch(row)
|
||||
if isUniqueViolation(err) {
|
||||
return branches.BranchDTO{}, fmt.Errorf("unique code already exists")
|
||||
}
|
||||
|
||||
return branches.BranchDTO{}, fmt.Errorf("could not generate a unique branch code, try again")
|
||||
return item, err
|
||||
}
|
||||
|
||||
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 {
|
||||
UniqueCode string `json:"uniqueCode" binding:"required,numeric,len=4"`
|
||||
Name LocalizedText `json:"name" binding:"required"`
|
||||
Address LocalizedText `json:"address" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
|
||||
@@ -290,8 +290,11 @@ func (h *handler) delete(c *gin.Context) {
|
||||
}
|
||||
|
||||
func isClientError(err error) bool {
|
||||
switch err.Error() {
|
||||
case "province not found", "unsupported region", "could not generate a unique branch code, try again":
|
||||
switch {
|
||||
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
|
||||
default:
|
||||
return false
|
||||
|
||||
Reference in New Issue
Block a user