package rbac import ( "context" "errors" "sync" "time" "online-back/internal/identity/rbac/perm" "online-back/pkg/client/postgresql" "github.com/jackc/pgx/v4" ) // Authorizer is what the middleware and the scope helpers need. type Authorizer interface { // Load returns the caller's principal, or nil when the user or their // role no longer exists. Load(ctx context.Context, userID int64) (*Principal, error) BranchIDs(ctx context.Context, userID int64) ([]int64, error) UserVisibleInBranches(ctx context.Context, userID int64, branchIDs []int64) (bool, error) } const ( principalTTL = time.Minute versionCheckEvery = 2 * time.Second principalCacheLimit = 10000 ) type cachedPrincipal struct { principal *Principal loadedAt time.Time } // Service loads principals and caches them per user. The rbac_version row // is bumped by DB triggers whenever roles, role_permissions, users.role_id // or branch_user change; seeing a new version drops the whole cache, so a // permission change takes effect within versionCheckEvery. type Service struct { client postgresql.Client now func() time.Time mu sync.Mutex cache map[int64]cachedPrincipal version int64 checkedAt time.Time } func NewService(client postgresql.Client) *Service { return &Service{client: client, now: time.Now, cache: make(map[int64]cachedPrincipal)} } func (s *Service) Load(ctx context.Context, userID int64) (*Principal, error) { if err := s.syncVersion(ctx); err != nil { return nil, err } now := s.now() s.mu.Lock() entry, ok := s.cache[userID] s.mu.Unlock() if ok && now.Sub(entry.loadedAt) < principalTTL { return entry.principal, nil } p, err := s.loadPrincipal(ctx, userID) if err != nil || p == nil { return p, err } s.mu.Lock() if len(s.cache) >= principalCacheLimit { s.cache = make(map[int64]cachedPrincipal) } s.cache[userID] = cachedPrincipal{principal: p, loadedAt: now} s.mu.Unlock() return p, nil } func (s *Service) syncVersion(ctx context.Context) error { now := s.now() s.mu.Lock() fresh := now.Sub(s.checkedAt) < versionCheckEvery s.mu.Unlock() if fresh { return nil } var version int64 if err := s.client.QueryRow(ctx, `SELECT version FROM rbac_version WHERE id = 1`).Scan(&version); err != nil { return err } s.mu.Lock() if version != s.version { s.cache = make(map[int64]cachedPrincipal) s.version = version } s.checkedAt = now s.mu.Unlock() return nil } const principalQuery = ` SELECT r.id, r.code, r.scope, r.is_super, ARRAY(SELECT rp.permission_code::text FROM role_permissions rp WHERE rp.role_id = r.id), ARRAY( SELECT bu.branch_id FROM branch_user bu JOIN branches b ON b.id = bu.branch_id AND b.deleted_at IS NULL WHERE bu.user_id = u.id AND bu.deleted_at IS NULL ORDER BY bu.id ) FROM users u JOIN roles r ON r.id = u.role_id AND r.deleted_at IS NULL WHERE u.id = $1 AND u.deleted_at IS NULL` func (s *Service) loadPrincipal(ctx context.Context, userID int64) (*Principal, error) { p := &Principal{UserID: userID} var scope string var codes []string err := s.client.QueryRow(ctx, principalQuery, userID).Scan( &p.RoleID, &p.RoleCode, &scope, &p.IsSuper, &codes, &p.BranchIDs, ) if errors.Is(err, pgx.ErrNoRows) { return nil, nil } if err != nil { return nil, err } p.Scope = Scope(scope) p.Perms = make(map[perm.Code]struct{}, len(codes)) for _, code := range codes { p.Perms[perm.Code(code)] = struct{}{} } return p, nil } func (s *Service) BranchIDs(ctx context.Context, userID int64) ([]int64, error) { const query = ` SELECT bu.branch_id FROM branch_user bu JOIN branches b ON b.id = bu.branch_id WHERE bu.user_id = $1 AND bu.deleted_at IS NULL AND b.deleted_at IS NULL ORDER BY bu.id` rows, err := s.client.Query(ctx, query, userID) if err != nil { return nil, err } defer rows.Close() var ids []int64 for rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { return nil, err } ids = append(ids, id) } return ids, rows.Err() } func (s *Service) UserVisibleInBranches(ctx context.Context, userID int64, branchIDs []int64) (bool, error) { if len(branchIDs) == 0 { return false, nil } query := `SELECT ` + UserInBranchSQL("u.id", 2) + ` FROM users u WHERE u.id = $1 AND u.deleted_at IS NULL` var ok bool err := s.client.QueryRow(ctx, query, userID, branchIDs).Scan(&ok) if errors.Is(err, pgx.ErrNoRows) { return false, nil } return ok, err }