Ejemplo n.º 1
0
        /// <summary>
        /// Gets the authorization strategy's NHibernate filter definitions and a functional delegate for determining when to apply them.
        /// </summary>
        /// <returns>A read-only list of filter application details to be applied to the NHibernate configuration and mappings.</returns>
        public IReadOnlyList <FilterApplicationDetails> GetFilters()
        {
            var filters = new List <FilterApplicationDetails>
            {
                new FilterApplicationDetails(
                    "Namespace",
                    @"(Namespace IS NOT NULL AND Namespace LIKE :Namespace)",
                    @"({currentAlias}.Namespace IS NOT NULL AND {currentAlias}.Namespace LIKE :Namespace)",
                    (c, w, p, jt) =>
                {
                    // Ensure the Namespace parameter is represented as an object array
                    var namespacePrefixes = p["Namespace"] as object[] ?? new [] { p["Namespace"] };

                    // Combine the namespace filters using OR (only one must match to grant authorization)
                    var namespacesDisjunction = new Disjunction();

                    foreach (var namespacePrefix in namespacePrefixes)
                    {
                        namespacesDisjunction.Add(Restrictions.Like("Namespace", namespacePrefix));
                    }

                    // Add the final namespaces criteria to the supplied WHERE clause (junction)
                    w.Add(
                        new AndExpression(
                            Restrictions.IsNotNull("Namespace"),
                            namespacesDisjunction));
                },
                    (t, p) => !DescriptorEntitySpecification.IsEdFiDescriptorEntity(t) && p.HasPropertyNamed("Namespace")),
            }.AsReadOnly();

            return(filters);
        }
Ejemplo n.º 2
0
 public void Should_return_true_for_descriptor_resource()
 {
     AssertHelper.All(
         () => Assert.That(DescriptorEntitySpecification.IsEdFiDescriptorEntity(typeof(AbsenceEventCategoryDescriptor)), Is.True),
         () => Assert.That(DescriptorEntitySpecification.IsEdFiDescriptorEntity(nameof(AbsenceEventCategoryDescriptor)), Is.True)
         );
 }
Ejemplo n.º 3
0
 public void Should_return_true_for_descriptor_entity()
 {
     AssertHelper.All(
         () => Assert.That(DescriptorEntitySpecification.IsEdFiDescriptorEntity(typeof(CountryDescriptor)), Is.True),
         () => Assert.That(DescriptorEntitySpecification.IsEdFiDescriptorEntity(nameof(CountryDescriptor)), Is.True)
         );
 }
Ejemplo n.º 4
0
        public string GetValue(string descriptorName, int id)
        {
            EnsureCacheInitialized();

            // If no id supplied, return the default string value
            if (!DescriptorEntitySpecification.IsEdFiDescriptorEntity(descriptorName) || id == default(int))
            {
                return(default(string));
            }

            var lookupKey = GetDescriptorLookupKeyById(descriptorName, id);

            if (TryGetCachedValue(lookupKey, out string codeValue))
            {
                return(codeValue);
            }

            if (!TryRefreshSingleDescriptorCacheById(descriptorName, id) ||
                !TryGetCachedValue(lookupKey, out codeValue))
            {
                // If a non-default result is provided, add it to the cache
                if (codeValue != default(string))
                {
                    UpdateDescriptorLookupCache(
                        CreateDescriptorLookup(descriptorName, id, codeValue));
                }
            }

            if (string.IsNullOrEmpty(codeValue))
            {
                throw new BadRequestException($"Unable to resolve id '{id}' to an existing resource {descriptorName}.");
            }

            return(codeValue);
        }
Ejemplo n.º 5
0
        public int GetId(string descriptorName, string descriptorValue)
        {
            EnsureCacheInitialized();

            // If not a descriptor name or no value is supplied, return default int value.
            if (!DescriptorEntitySpecification.IsEdFiDescriptorEntity(descriptorName) || string.IsNullOrWhiteSpace(descriptorValue))
            {
                return(default(int));
            }

            var lookupKey = GetDescriptorLookupKeyByValue(descriptorName, descriptorValue);

            if (TryGetCachedId(lookupKey, out int id))
            {
                return(id);
            }

            if (!TryRefreshSingleDescriptorCache(descriptorName) ||
                !TryGetCachedId(lookupKey, out id))
            {
                // If a non-default result is provided, add it to the cache
                if (id != default(int))
                {
                    UpdateDescriptorLookupCache(
                        CreateDescriptorLookup(descriptorName, id, descriptorValue));
                }
            }

            if (id == default(int))
            {
                throw new BadRequestException($"Unable to resolve value '{descriptorValue}' to an existing '{descriptorName}' resource.");
            }

            return(id);
        }
Ejemplo n.º 6
0
        private string GetParentResource(Entity entity)
        {
            var resourceName = entity.Name;

            if (resourceName.EndsWith("type", StringComparison.InvariantCultureIgnoreCase))
            {
                return("types");
            }

            if (DescriptorEntitySpecification.IsEdFiDescriptorEntity(resourceName))
            {
                return(ManagedDescriptorSpecification.IsEdFiManagedDescriptor(resourceName)
                    ? "managedDescriptors"
                    : "systemDescriptors");
            }

            if (EducationOrganizationEntitySpecification.IsEducationOrganizationEntity(resourceName))
            {
                return("educationOrganizations");
            }

            if (PersonEntitySpecification.IsPersonEntity(resourceName))
            {
                return("people");
            }

            if (AssessmentSpecification.IsAssessmentEntity(resourceName))
            {
                return("assessmentMetadata");
            }

            if (resourceName.Equals("educationContent", StringComparison.InvariantCultureIgnoreCase))
            {
                return(null);
            }

            if (EducationStandardSpecification.IsEducationStandardEntity(resourceName))
            {
                return("educationStandards");
            }

            if (PrimaryRelationshipEntitySpecification.IsPrimaryRelationshipEntity(resourceName))
            {
                return("primaryRelationships");
            }

            if (SurveySpecification.IsSurveyEntity(resourceName))
            {
                return("surveyDomain");
            }

            return("relationshipBasedData");
        }
 private Dictionary <Resource, IEnumerable <AuthorizationContextProperty> > InitializeAuthorizationPropertiesByResource()
 {
     return(_resourcesToRender
            .Where(
                r => !DescriptorEntitySpecification.IsEdFiDescriptorEntity(r.Name))
            .Select(
                r =>
                new
     {
         Resource = r, AuthorizationResourceProperties =
             AuthorizationResourceProperties(r)
     })
            .Where(r => r.AuthorizationResourceProperties.Any())
            .ToDictionary(
                k => k.Resource,
                v => v.AuthorizationResourceProperties));
 }
        private IList <DescriptorLookup> GetDescriptorCacheData(string descriptorName, int?id = null)
        {
            if (!DescriptorEntitySpecification.IsEdFiDescriptorEntity(descriptorName))
            {
                _log.Error($"{descriptorName} is not a descriptor, but is being passed as one");
                throw new ArgumentException($"{descriptorName} is not a descriptor, but is being passed as one");
            }

            try
            {
                string descriptorFullName;

                if (!_descriptorFullNameByName.Value.TryGetValue(descriptorName, out descriptorFullName))
                {
                    throw new KeyNotFoundException($"descriptorName {descriptorName} is not a known descriptor entity name.");
                }

                using (var session = _sessionFactory.OpenSession())
                {
                    var descriptorIdColumnName = descriptorName + "Id";

                    var criteria = session.CreateCriteria(descriptorFullName)
                                   .SetProjection(
                        Projections.ProjectionList()
                        .Add(Projections.Property(descriptorIdColumnName), "Id")
                        .Add(Projections.Property("Namespace"), "Namespace")
                        .Add(Projections.Property("CodeValue"), "CodeValue"));

                    if (id.HasValue)
                    {
                        criteria.Add(Restrictions.Eq(descriptorIdColumnName, id.Value));
                    }

                    return(TransformToDescriptorLookups(
                               descriptorName,
                               criteria.SetResultTransformer(Transformers.AliasToBean <DescriptorEntry>())
                               .List <DescriptorEntry>())
                           .ToList());
                }
            }
            catch (Exception ex)
            {
                _log.Error($"Error creating hql query for {descriptorName}.", ex);
                throw;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Gets the authorization strategy's NHibernate filter definitions and a functional delegate for determining when to apply them.
        /// </summary>
        /// <returns>A read-only list of filter application details to be applied to the NHibernate configuration and mappings.</returns>
        public IReadOnlyList <FilterApplicationDetails> GetFilters()
        {
            var filters = new List <FilterApplicationDetails>
            {
                new FilterApplicationDetails(
                    "CreatedByOwnershipTokenId",
                    @"(CreatedByOwnershipTokenId IS NOT NULL AND CreatedByOwnershipTokenId IN (:CreatedByOwnershipTokenId))",
                    @"({currentAlias}.CreatedByOwnershipTokenId IS NOT NULL AND {currentAlias}.CreatedByOwnershipTokenId IN (:CreatedByOwnershipTokenId))",
                    (c, w, p, jt) =>
                {
                    w.ApplyPropertyFilters(p, "CreatedByOwnershipTokenId");
                },
                    (t, p) => !DescriptorEntitySpecification.IsEdFiDescriptorEntity(t) && p.HasPropertyNamed("CreatedByOwnershipTokenId")),
            }.AsReadOnly();

            return(filters);
        }
Ejemplo n.º 10
0
 public static bool IsDescriptorEntity(this Entity entity)
 {
     return(DescriptorEntitySpecification.IsEdFiDescriptorEntity(entity.Name));
 }
Ejemplo n.º 11
0
        private void InitializeLazyMembers()
        {
            // A property that is part of a "unified key" has multiple incoming associations
            _isUnified = new Lazy <bool>(
                () => IncomingAssociations.Count > 1);

            _lookupEntity = new Lazy <Entity>(
                () =>
            {
                // Detached properties are not lookup properties
                if (Entity == null)
                {
                    return(null);
                }

                // Is this property a TypeId or DescriptorId on the table?  If so, it's not a lookup property.
                if (DescriptorEntitySpecification.IsEdFiDescriptorEntity(Entity.Name) &&
                    PropertyName == Entity.Name + "Id")        // TODO: Embedded convention - Types/descriptor properties use entity name + "Id" suffix
                {
                    return(null);
                }

                var currentAssociation = IncomingAssociations.FirstOrDefault(
                    x =>
                    x.AssociationType == AssociationViewType.FromBase ||
                    x.AssociationType == AssociationViewType.OneToOneIncoming ||
                    x.AssociationType == AssociationViewType.ManyToOne

                    // Prevent processing self-recursive relationships with key unification on current property (prevent endless loop)
                    && !(x.IsSelfReferencing && PropertyName.EqualsIgnoreCase(
                             x.PropertyMappingByThisName[PropertyName]
                             .OtherProperty.PropertyName)));

                if (currentAssociation == null)
                {
                    return(null);
                }

                var currentThisProperty = this;

                while (currentAssociation != null)
                {
                    var otherProperty = currentAssociation.PropertyMappingByThisName[currentThisProperty.PropertyName]
                                        .OtherProperty;

                    if (ModelComparers.EntityProperty.Equals(currentThisProperty, otherProperty))
                    {
                        throw new Exception(
                            "Association property mapping endpoints refer to the same property.");
                    }

                    currentThisProperty = otherProperty;

                    // Stop looking if we've hit a lookup table (Type or Descriptor)
                    if (currentThisProperty.Entity.IsLookup)
                    {
                        break;
                    }

                    currentAssociation = otherProperty.IncomingAssociations.FirstOrDefault(
                        x =>
                        x.AssociationType == AssociationViewType.FromBase ||
                        x.AssociationType == AssociationViewType.OneToOneIncoming ||
                        x.AssociationType == AssociationViewType.ManyToOne &&
                        !(x.IsSelfReferencing && currentThisProperty.PropertyName.EqualsIgnoreCase(
                              x.PropertyMappingByThisName[
                                  currentThisProperty
                                  .PropertyName]
                              .OtherProperty
                              .PropertyName)));
                }

                return
                (currentThisProperty.Entity.IsLookup &&
                 currentThisProperty.Entity.Aggregate != Entity.Aggregate
                            ? currentThisProperty.Entity
                            : null);
            });
        }