84 lines
1.8 KiB
Go
84 lines
1.8 KiB
Go
package acl
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"mediarr/database"
|
|
"mediarr/ident"
|
|
"mediarr/identity"
|
|
)
|
|
|
|
const maxDocumentDepth = 256
|
|
|
|
type Service struct {
|
|
db database.DatabaseClient
|
|
identity *identity.Service
|
|
}
|
|
|
|
func NewService(db database.DatabaseClient) *Service {
|
|
return &Service{
|
|
db: db,
|
|
identity: identity.NewService(db),
|
|
}
|
|
}
|
|
|
|
func (s *Service) documentChain(ctx context.Context, documentID ident.UUID) ([]database.Document, error) {
|
|
chain := make([]database.Document, 0, 8)
|
|
seen := make(map[ident.UUID]struct{})
|
|
current := documentID
|
|
|
|
for {
|
|
if _, exists := seen[current]; exists {
|
|
return nil, ErrDocumentCycle
|
|
}
|
|
seen[current] = struct{}{}
|
|
|
|
document, err := s.db.Queries.GetDocument(ctx, current)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, fmt.Errorf("%w: %s", ErrDocumentNotFound, current)
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
chain = append(chain, document)
|
|
if document.ParentID == nil {
|
|
return chain, nil
|
|
}
|
|
if len(chain) >= maxDocumentDepth {
|
|
return nil, ErrDocumentCycle
|
|
}
|
|
|
|
current = *document.ParentID
|
|
}
|
|
}
|
|
|
|
func (s *Service) loadSubject(ctx context.Context, subjectID ident.UUID) (*identity.Principal, error) {
|
|
subject, err := s.identity.GetPrincipal(ctx, subjectID)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, fmt.Errorf("%w: %s", ErrSubjectNotFound, subjectID)
|
|
}
|
|
return nil, err
|
|
}
|
|
if subject.Status != identity.StatusActive {
|
|
return nil, fmt.Errorf("%w: %s", ErrSubjectNotFound, subjectID)
|
|
}
|
|
|
|
return subject, nil
|
|
}
|
|
|
|
func (s *Service) IsActive(ctx context.Context, principalID ident.UUID) (bool, error) {
|
|
if _, err := s.loadSubject(ctx, principalID); err != nil {
|
|
if errors.Is(err, ErrSubjectNotFound) {
|
|
return false, nil
|
|
}
|
|
return false, err
|
|
}
|
|
|
|
return true, nil
|
|
}
|