Bind permissions to roles and scope operator access by branch.

Replace permission_user with permission_role, enforce RBAC on admin routes, and limit operators to their assigned branches.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-24 18:24:43 +05:00
parent 427d5b4e07
commit 1fd0abbcb2
57 changed files with 1281 additions and 657 deletions

View File

@@ -67,8 +67,19 @@ const profileBranchesJSON = `COALESCE((
) b
), '[]'::json)`
const profilePermissionsJSON = `COALESCE((
SELECT json_agg(jsonb_build_object(
'id', p.id,
'code', COALESCE(p.code, ''),
'name', p.name
) ORDER BY p.id)
FROM permission_role pr
JOIN permissions p ON p.id = pr.permission_id
WHERE pr.role_id = r.id
), '[]'::json)`
const profileQuery = `SELECT u.id, u.name, u.first_name, u.last_name, u.phone, u.avatar, u.created_at,
r.id, r.code, r.name, ` + profileBranchesJSON + profileFromClause + ` WHERE u.id = $1`
r.id, r.code, r.name, ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1`
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
phone := strings.TrimSpace(dto.Phone)
@@ -125,6 +136,7 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
var roleID sql.NullInt64
var roleCode, roleName sql.NullString
var branchesJSON []byte
var permissionsJSON []byte
err := row.Scan(
&profile.Id,
@@ -138,6 +150,7 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
&roleCode,
&roleName,
&branchesJSON,
&permissionsJSON,
)
if err != nil {
return auth.UserProfileDTO{}, err
@@ -151,12 +164,18 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
}
}
if len(branchesJSON) == 0 || string(branchesJSON) == "null" {
profile.Branches = []auth.ProfileBranchDTO{}
return profile, nil
profile.Branches = []auth.ProfileBranchDTO{}
if len(branchesJSON) > 0 && string(branchesJSON) != "null" {
if err := json.Unmarshal(branchesJSON, &profile.Branches); err != nil {
return auth.UserProfileDTO{}, err
}
}
if err := json.Unmarshal(branchesJSON, &profile.Branches); err != nil {
return auth.UserProfileDTO{}, err
profile.Permissions = []auth.ProfilePermissionDTO{}
if len(permissionsJSON) > 0 && string(permissionsJSON) != "null" {
if err := json.Unmarshal(permissionsJSON, &profile.Permissions); err != nil {
return auth.UserProfileDTO{}, err
}
}
return profile, nil
}