ch logika
This commit is contained in:
@@ -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