public void MemberHasBuiltinProperties() { var provider = ScopeProvider; using (var scope = provider.CreateScope()) { var repository = CreateRepository(provider); var memberType = MemberTypeBuilder.CreateSimpleMemberType(); MemberTypeRepository.Save(memberType); var member = MemberBuilder.CreateSimpleMember(memberType, "Johnny Hefty", "*****@*****.**", "123", "hefty"); repository.Save(member); var sut = repository.Get(member.Id); Assert.That(memberType.CompositionPropertyGroups.Count(), Is.EqualTo(2)); Assert.That(memberType.CompositionPropertyTypes.Count(), Is.EqualTo(3 + ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Count)); Assert.That(sut.Properties.Count(), Is.EqualTo(3 + ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Count)); var grp = memberType.CompositionPropertyGroups.FirstOrDefault(x => x.Name == Constants.Conventions.Member.StandardPropertiesGroupName); Assert.IsNotNull(grp); var aliases = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper).Select(x => x.Key) .ToArray(); foreach (var p in memberType.CompositionPropertyTypes.Where(x => aliases.Contains(x.Alias))) { Assert.AreEqual(grp.Id, p.PropertyGroupId.Value); } } }
public void Can_Persist_Member_Type() { var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { var repository = CreateRepository(provider); var memberType = (IMemberType)MockedContentTypes.CreateSimpleMemberType(); repository.Save(memberType); var sut = repository.Get(memberType.Id); var standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(); Assert.That(sut, Is.Not.Null); Assert.That(sut.PropertyGroups.Count, Is.EqualTo(2)); Assert.That(sut.PropertyTypes.Count(), Is.EqualTo(3 + standardProps.Count)); Assert.That(sut.PropertyGroups.Any(x => x.HasIdentity == false || x.Id == 0), Is.False); Assert.That(sut.PropertyTypes.Any(x => x.HasIdentity == false || x.Id == 0), Is.False); TestHelper.AssertPropertyValuesAreEqual(sut, memberType, "yyyy-MM-dd HH:mm:ss"); } }
protected override void PersistNewItem(IMemberType entity) { ValidateAlias(entity); entity.AddingEntity(); //set a default icon if one is not specified if (entity.Icon.IsNullOrWhiteSpace()) { entity.Icon = Cms.Core.Constants.Icons.Member; } //By Convention we add 9 standard PropertyTypes to an Umbraco MemberType entity.AddPropertyGroup(Cms.Core.Constants.Conventions.Member.StandardPropertiesGroupAlias, Cms.Core.Constants.Conventions.Member.StandardPropertiesGroupName); var standardPropertyTypes = ConventionsHelper.GetStandardPropertyTypeStubs(_shortStringHelper); foreach (var standardPropertyType in standardPropertyTypes) { entity.AddPropertyType(standardPropertyType.Value, Cms.Core.Constants.Conventions.Member.StandardPropertiesGroupAlias, Cms.Core.Constants.Conventions.Member.StandardPropertiesGroupName); } EnsureExplicitDataTypeForBuiltInProperties(entity); PersistNewBaseContentType(entity); //Handles the MemberTypeDto (cmsMemberType table) var memberTypeDtos = ContentTypeFactory.BuildMemberPropertyTypeDtos(entity); foreach (var memberTypeDto in memberTypeDtos) { Database.Insert(memberTypeDto); } entity.ResetDirtyProperties(); }
public void Answer_Is_Encrypted() { IMember createdMember = null; var memberType = MockedContentTypes.CreateSimpleMemberType(); foreach (var p in ConventionsHelper.GetStandardPropertyTypeStubs()) { memberType.AddPropertyType(p.Value); } var memberTypeServiceMock = new Mock <IMemberTypeService>(); memberTypeServiceMock.Setup(x => x.GetDefault()).Returns("Member"); var membershipServiceMock = new Mock <IMembershipMemberService>(); membershipServiceMock.Setup(service => service.Exists("test")).Returns(false); membershipServiceMock.Setup(service => service.GetByEmail("*****@*****.**")).Returns(() => null); membershipServiceMock.Setup( service => service.CreateWithIdentity(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>())) .Callback((string u, string e, string p, string m, bool isApproved) => { createdMember = new Member("test", e, u, p, memberType, isApproved); }) .Returns(() => createdMember); var provider = new MembersMembershipProvider(membershipServiceMock.Object, memberTypeServiceMock.Object); provider.Initialize("test", new NameValueCollection()); MembershipCreateStatus status; provider.CreateUser("test", "test", "testtest$1", "*****@*****.**", "test", "test", true, "test", out status); Assert.AreNotEqual("test", createdMember.RawPasswordAnswerValue); Assert.AreEqual(provider.EncryptString("test"), createdMember.RawPasswordAnswerValue); }
public void Built_In_Member_Type_Properties_Are_Automatically_Added_When_Creating() { var stubs = ConventionsHelper.GetStandardPropertyTypeStubs(); var provider = TestObjects.GetScopeProvider(Logger); using (provider.CreateScope()) { var repository = CreateRepository(provider); IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); // created without the stub properties Assert.AreEqual(1, memberType.PropertyGroups.Count); Assert.AreEqual(3, memberType.PropertyTypes.Count()); // saving *new* member type adds the stub properties repository.Save(memberType); // saving has added (and saved) the stub properties Assert.AreEqual(2, memberType.PropertyGroups.Count); Assert.AreEqual(3 + stubs.Count, memberType.PropertyTypes.Count()); // getting with stub properties memberType = repository.Get(memberType.Id); Assert.AreEqual(2, memberType.PropertyGroups.Count); Assert.AreEqual(3 + stubs.Count, memberType.PropertyTypes.Count()); } }
/// <summary> /// Creates a model to use for registering new members with custom member properties /// </summary> /// <param name="memberTypeAlias"></param> /// <returns></returns> public virtual RegisterModel CreateRegistrationModel(string memberTypeAlias = null) { var provider = _membershipProvider; if (provider.IsUmbracoMembershipProvider()) { memberTypeAlias = memberTypeAlias ?? Constants.Conventions.MemberTypes.DefaultAlias; var memberType = _memberTypeService.Get(memberTypeAlias); if (memberType == null) { throw new InvalidOperationException("Could not find a member type with alias " + memberTypeAlias); } var builtIns = ConventionsHelper.GetStandardPropertyTypeStubs().Select(x => x.Key).ToArray(); var model = RegisterModel.CreateModel(); model.MemberTypeAlias = memberTypeAlias; model.MemberProperties = GetMemberPropertiesViewModel(memberType, builtIns).ToList(); return(model); } else { var model = RegisterModel.CreateModel(); model.MemberTypeAlias = string.Empty; return(model); } }
public void Built_In_Member_Type_Properties_Missing_Are_Automatically_Added_When_Creating() { Dictionary <string, PropertyType> stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType(); // created without the stub properties Assert.AreEqual(1, memberType.PropertyGroups.Count); Assert.AreEqual(3, memberType.PropertyTypes.Count()); // add one stub property, others are still missing memberType.AddPropertyType(stubs.First().Value, Constants.Conventions.Member.StandardPropertiesGroupAlias, Constants.Conventions.Member.StandardPropertiesGroupName); // saving *new* member type adds the (missing) stub properties repository.Save(memberType); // saving has added (and saved) the (missing) stub properties Assert.AreEqual(2, memberType.PropertyGroups.Count); Assert.AreEqual(3 + stubs.Count, memberType.PropertyTypes.Count()); // getting with stub properties memberType = repository.Get(memberType.Id); Assert.AreEqual(2, memberType.PropertyGroups.Count); Assert.AreEqual(3 + stubs.Count, memberType.PropertyTypes.Count()); } }
public void Can_Persist_Member_Type() { IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { MemberTypeRepository repository = CreateRepository(provider); var memberType = (IMemberType)MemberTypeBuilder.CreateSimpleMemberType(); repository.Save(memberType); IMemberType sut = repository.Get(memberType.Id); Dictionary <string, PropertyType> standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); Assert.That(sut, Is.Not.Null); Assert.That(sut.PropertyGroups.Count, Is.EqualTo(2)); Assert.That(sut.PropertyTypes.Count(), Is.EqualTo(3 + standardProps.Count)); Assert.That(sut.PropertyGroups.Any(x => x.HasIdentity == false || x.Id == 0), Is.False); Assert.That(sut.PropertyTypes.Any(x => x.HasIdentity == false || x.Id == 0), Is.False); TestHelper.AssertPropertyValuesAreEqual(sut, memberType); } }
public void usings_are_ordered_system_first_then_alphabetically() { var isFailed = false; var builder = new StringBuilder(); foreach (var sourcePath in ConventionsHelper.GetCSharpSourcePaths()) { var source = File.ReadAllText(sourcePath); var syntaxTree = CSharpSyntaxTree.ParseText(source); var usings = ((CompilationUnitSyntax)syntaxTree.GetRoot()).Usings; var sorted = usings.OrderBy(u => u, UsingComparer.Instance).ToList(); if (usings.SequenceEqual(sorted) == false) { isFailed = true; builder.AppendLine($"Usings ordered incorrectly in '{sourcePath}'"); builder.Append(" ("); builder.Append(string.Join(", ", sorted)); builder.AppendLine(")"); } } isFailed.ShouldBeFalse(builder.ToString()); }
/// <summary> /// This will remove all of the special membership provider properties which were required to display the property editors /// for editing - but the values have been mapped back to the MemberSave object directly - we don't want to keep these properties /// on the IMember because they will attempt to be persisted which we don't want since they might not even exist. /// </summary> /// <param name="contentType"></param> private void FilterMembershipProviderProperties(IContentTypeBase contentType) { var defaultProps = ConventionsHelper.GetStandardPropertyTypeStubs(_shortStringHelper); //remove all membership properties, these values are set with the membership provider. var exclude = defaultProps.Select(x => x.Value.Alias).ToArray(); FilterContentTypeProperties(contentType, exclude); }
public void each_interface_name_starts_with_capital_I() { var interfaces = ConventionsHelper.GetAllAssemblies().GetInterfaces(); var invalidNameInterfaces = interfaces.Where(t => t.Name.StartsWith("I") == false); invalidNameInterfaces.ShouldBeEmpty(); }
protected List <MemberPropertyModel> GetMemberPropertiesViewModel(IMemberType memberType, IMember?member = null) { var viewProperties = new List <MemberPropertyModel>(); var builtIns = ConventionsHelper.GetStandardPropertyTypeStubs(_shortStringHelper).Select(x => x.Key).ToArray(); IOrderedEnumerable <IPropertyType> propertyTypes = memberType.PropertyTypes .Where(x => builtIns.Contains(x.Alias) == false && memberType.MemberCanEditProperty(x.Alias)) .OrderBy(p => p.SortOrder); foreach (IPropertyType prop in propertyTypes) { var value = string.Empty; if (member != null) { IProperty?propValue = member.Properties[prop.Alias]; if (propValue != null && propValue.GetValue() != null) { value = propValue.GetValue()?.ToString(); } } var viewProperty = new MemberPropertyModel { Alias = prop.Alias, Name = prop.Name, Value = value }; // TODO: Perhaps one day we'll ship with our own EditorTempates but for now developers // can just render their own. ////This is a rudimentary check to see what data template we should render //// if developers want to change the template they can do so dynamically in their views or controllers //// for a given property. ////These are the default built-in MVC template types: “Boolean”, “Decimal”, “EmailAddress”, “HiddenInput”, “HTML”, “Object”, “String”, “Text”, and “Url” //// by default we'll render a text box since we've defined that metadata on the UmbracoProperty.Value property directly. // if (prop.DataTypeId == new Guid(Constants.PropertyEditors.TrueFalse)) // { // viewProperty.EditorTemplate = "UmbracoBoolean"; // } // else // { // switch (prop.DataTypeDatabaseType) // { // case DataTypeDatabaseType.Integer: // viewProperty.EditorTemplate = "Decimal"; // break; // case DataTypeDatabaseType.Ntext: // viewProperty.EditorTemplate = "Text"; // break; // case DataTypeDatabaseType.Date: // case DataTypeDatabaseType.Nvarchar: // break; // } // } viewProperties.Add(viewProperty); } return(viewProperties); }
/// <summary> /// Override so we can specify explicit db type's on any property types that are built-in. /// </summary> /// <param name="propertyEditorAlias"></param> /// <param name="storageType"></param> /// <param name="propertyTypeAlias"></param> /// <returns></returns> protected override PropertyType CreatePropertyType(string propertyEditorAlias, ValueStorageType storageType, string propertyTypeAlias) { //custom property type constructor logic to set explicit dbtype's for built in properties var builtinProperties = ConventionsHelper.GetStandardPropertyTypeStubs(_shortStringHelper); var readonlyStorageType = builtinProperties.TryGetValue(propertyTypeAlias, out var propertyType); storageType = readonlyStorageType ? propertyType.ValueStorageType : storageType; return(new PropertyType(_shortStringHelper, propertyEditorAlias, storageType, readonlyStorageType, propertyTypeAlias)); }
protected override void RegisterProviders(IDependencyRegistrator dependencyRegistrator) { var builders = BuildersCollectionHelper.FillMissingBuilders( ConventionsHelper.FindContractToBuilderMatches().Values.ToArray(), BuilderFactory.CreateBuilderInstance); dependencyRegistrator.RegisterBuilders(RegistrationHelper.RegisterBuilderProduct, ConventionsHelper.FindContractToBuilderMatches(), builders); }
public void each_interface_cadkit_starts_with_capital_I() { var interfaces = ConventionsHelper.Interfaces("CADKit"); Assert.NotEmpty(interfaces); var interfacesNotStartingWithI = interfaces .Where(x => x.Name.StartsWith("I", StringComparison.CurrentCulture) == false); Assert.Empty(interfacesNotStartingWithI); }
public void each_interface_has_at_least_one_implementation() { var interfaces = ConventionsHelper.GetAllAssemblies().GetInterfaces(); var concreteTypes = ConventionsHelper.GetAllAssemblies().GetClasses().Where(x => x.IsAbstract == false) .ToList(); foreach (var @interface in interfaces) { concreteTypes.Any(x => @interface.IsAssignableFrom(x)).ShouldBeTrue(); } }
/// <summary> /// Creates a new profile model filled in with the current members details if they are logged in which allows for editing /// profile properties /// </summary> /// <returns></returns> public virtual ProfileModel GetCurrentMemberProfileModel() { if (IsLoggedIn() == false) { return(null); } var provider = _membershipProvider; if (provider.IsUmbracoMembershipProvider()) { var membershipUser = provider.GetCurrentUserOnline(); var member = GetCurrentPersistedMember(); //this shouldn't happen but will if the member is deleted in the back office while the member is trying // to use the front-end! if (member == null) { //log them out since they've been removed FormsAuthentication.SignOut(); return(null); } var model = ProfileModel.CreateModel(); model.Name = member.Name; model.MemberTypeAlias = member.ContentTypeAlias; model.Email = membershipUser.Email; model.UserName = membershipUser.UserName; model.PasswordQuestion = membershipUser.PasswordQuestion; model.Comment = membershipUser.Comment; model.IsApproved = membershipUser.IsApproved; model.IsLockedOut = membershipUser.IsLockedOut; model.LastLockoutDate = membershipUser.LastLockoutDate; model.CreationDate = membershipUser.CreationDate; model.LastLoginDate = membershipUser.LastLoginDate; model.LastActivityDate = membershipUser.LastActivityDate; model.LastPasswordChangedDate = membershipUser.LastPasswordChangedDate; var memberType = _memberTypeService.Get(member.ContentTypeId); var builtIns = ConventionsHelper.GetStandardPropertyTypeStubs().Select(x => x.Key).ToArray(); model.MemberProperties = GetMemberPropertiesViewModel(memberType, builtIns, member).ToList(); return(model); } //we can try to look up an associated member by the provider user key // TODO: Support this at some point! throw new NotSupportedException("Currently a member profile cannot be edited unless using the built-in Umbraco membership providers"); }
public void each_class_in_Repository_namespace_implements_interfaces() { var repositorys = ConventionsHelper.Classes("SODP.Repository") .Where(x => x.Namespace.EndsWith(".Repository", StringComparison.CurrentCulture)); Assert.NotEmpty(repositorys); var repositoryClassesWithoutInterfaces = repositorys .Where(x => x.GetInterfaces().Length == 0); Assert.Empty(repositoryClassesWithoutInterfaces); }
public void each_class_in_CoreController_namespace_implements_interfaces() { var controllers = ConventionsHelper.Classes("SODP.Core") .Where(x => x.Namespace.EndsWith(".Controller", StringComparison.CurrentCulture)); Assert.NotEmpty(controllers); var controllerClassesWithoutInterfaces = controllers .Where(x => x.GetInterfaces().Length == 0); Assert.Empty(controllerClassesWithoutInterfaces); }
/// <summary> /// Ensure that all the built-in membership provider properties have their correct data type /// and property editors assigned. This occurs prior to saving so that the correct values are persisted. /// </summary> /// <param name="memberType"></param> private static void EnsureExplicitDataTypeForBuiltInProperties(IContentTypeBase memberType) { var builtinProperties = ConventionsHelper.GetStandardPropertyTypeStubs(); foreach (var propertyType in memberType.PropertyTypes) { if (builtinProperties.ContainsKey(propertyType.Alias)) { //this reset's its current data type reference which will be re-assigned based on the property editor assigned on the next line propertyType.DataTypeId = 0; propertyType.DataTypeKey = default; } } }
public void DateTime_Now_is_never_used() { var sourcePaths = ConventionsHelper.GetCSharpSourcePaths() .Where(path => path.EndsWith("\\Time.cs") == false); foreach (var sourcePath in sourcePaths) { var source = File.ReadAllText(sourcePath); var tree = CSharpSyntaxTree.ParseText(source); var memberAccesses = tree.GetRoot().DescendantNodes().OfType <MemberAccessExpressionSyntax>().ToList(); var dateTimeNowInvocations = memberAccesses.Where(x => x.Expression.Parent.ToString().Equals("datetime.now", StringComparison.OrdinalIgnoreCase)); dateTimeNowInvocations.ShouldBeEmpty(); } }
public void Rebuild_Member_Xml_On_Property_Removal() { var standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(); var contentType1 = MockedContentTypes.CreateSimpleMemberType("test1", "Test1"); ServiceContext.MemberTypeService.Save(contentType1); var contentItems1 = MockedMember.CreateSimpleMember(contentType1, 10).ToArray(); foreach (var x in contentItems1) { ServiceContext.MemberService.Save(x); } var alias = contentType1.PropertyTypes.First(x => standardProps.ContainsKey(x.Alias) == false).Alias; var elementToMatch = "<" + alias + ">"; using (var scope = ScopeProvider.CreateScope()) { foreach (var c in contentItems1) { var xml = scope.Database.FirstOrDefault <ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.Contains(elementToMatch)); //verify that it is there before we remove the property } scope.Complete(); } //remove a property (NOT ONE OF THE DEFAULTS) contentType1.RemovePropertyType(alias); ServiceContext.MemberTypeService.Save(contentType1); var reQueried = ServiceContext.MemberTypeService.Get(contentType1.Id); var reContent = ServiceContext.MemberService.GetById(contentItems1.First().Id); using (var scope = ScopeProvider.CreateScope()) { foreach (var c in contentItems1) { var xml = scope.Database.FirstOrDefault <ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsFalse(xml.Xml.Contains(elementToMatch)); //verify that it is no longer there } scope.Complete(); } }
public void Bug_Changing_Built_In_Member_Type_Property_Type_Aliases_Results_In_Exception() { var stubs = ConventionsHelper.GetStandardPropertyTypeStubs(); var provider = TestObjects.GetScopeProvider(Logger); using (provider.CreateScope()) { var repository = CreateRepository(provider); IMemberType memberType = MockedContentTypes.CreateSimpleMemberType("mtype"); // created without the stub properties Assert.AreEqual(1, memberType.PropertyGroups.Count); Assert.AreEqual(3, memberType.PropertyTypes.Count()); // saving *new* member type adds the stub properties repository.Save(memberType); // saving has added (and saved) the stub properties Assert.AreEqual(2, memberType.PropertyGroups.Count); Assert.AreEqual(3 + stubs.Count, memberType.PropertyTypes.Count()); foreach (var stub in stubs) { var prop = memberType.PropertyTypes.First(x => x.Alias == stub.Key); prop.Alias = prop.Alias + "__0000"; } // saving *existing* member type does *not* ensure stub properties repository.Save(memberType); // therefore, nothing has changed Assert.AreEqual(2, memberType.PropertyGroups.Count); Assert.AreEqual(3 + stubs.Count, memberType.PropertyTypes.Count()); // fetching ensures that the stub properties are there memberType = repository.Get("mtype"); Assert.IsNotNull(memberType); Assert.AreEqual(2, memberType.PropertyGroups.Count); Assert.AreEqual(3 + stubs.Count * 2, memberType.PropertyTypes.Count()); } }
public void Bug_Changing_Built_In_Member_Type_Property_Type_Aliases_Results_In_Exception() { Dictionary <string, PropertyType> stubs = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper); IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { MemberTypeRepository repository = CreateRepository(provider); IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType("mtype"); // created without the stub properties Assert.AreEqual(1, memberType.PropertyGroups.Count); Assert.AreEqual(3, memberType.PropertyTypes.Count()); // saving *new* member type adds the stub properties repository.Save(memberType); // saving has added (and saved) the stub properties Assert.AreEqual(2, memberType.PropertyGroups.Count); Assert.AreEqual(3 + stubs.Count, memberType.PropertyTypes.Count()); foreach (KeyValuePair <string, PropertyType> stub in stubs) { IPropertyType prop = memberType.PropertyTypes.First(x => x.Alias == stub.Key); prop.Alias += "__0000"; } // saving *existing* member type does *not* ensure stub properties repository.Save(memberType); // therefore, nothing has changed Assert.AreEqual(2, memberType.PropertyGroups.Count); Assert.AreEqual(3 + stubs.Count, memberType.PropertyTypes.Count()); // fetching ensures that the stub properties are there memberType = repository.Get("mtype"); Assert.IsNotNull(memberType); Assert.AreEqual(2, memberType.PropertyGroups.Count); Assert.AreEqual(3 + (stubs.Count * 2), memberType.PropertyTypes.Count()); } }
/// <summary> /// This ensures that the internal membership property types are removed from validation before processing the /// validation /// since those properties are actually mapped to real properties of the IMember. /// This also validates any posted data for fields that are sensitive. /// </summary> /// <param name="model"></param> /// <param name="modelWithProperties"></param> /// <param name="actionContext"></param> /// <returns></returns> public override bool ValidateProperties(MemberSave?model, IContentProperties <ContentPropertyBasic>?modelWithProperties, ActionExecutingContext actionContext) { var propertiesToValidate = model?.Properties.ToList(); Dictionary <string, PropertyType> defaultProps = ConventionsHelper.GetStandardPropertyTypeStubs(_shortStringHelper); var exclude = defaultProps.Select(x => x.Value.Alias).ToArray(); foreach (var remove in exclude) { propertiesToValidate?.RemoveAll(property => property.Alias == remove); } //if the user doesn't have access to sensitive values, then we need to validate the incoming properties to check //if a sensitive value is being submitted. if (_backofficeSecurity?.CurrentUser?.HasAccessToSensitiveData() == false) { IMemberType?contentType = _memberTypeService.Get(model?.PersistedContent?.ContentTypeId ?? default); var sensitiveProperties = contentType? .PropertyTypes.Where(x => contentType.IsSensitiveProperty(x.Alias)) .ToList(); if (sensitiveProperties is not null) { foreach (IPropertyType sensitiveProperty in sensitiveProperties) { ContentPropertyBasic?prop = propertiesToValidate?.FirstOrDefault(x => x.Alias == sensitiveProperty.Alias); if (prop != null) { //this should not happen, this means that there was data posted for a sensitive property that //the user doesn't have access to, which means that someone is trying to hack the values. var message = $"property with alias: {prop.Alias} cannot be posted"; actionContext.Result = new NotFoundObjectResult(new InvalidOperationException(message)); return(false); } } } } return(ValidateProperties(propertiesToValidate, model?.PersistedContent?.Properties.ToList(), actionContext)); }
public void Password_Hashed_With_Salt() { IMember createdMember = null; var memberType = MockedContentTypes.CreateSimpleMemberType(); foreach (var p in ConventionsHelper.GetStandardPropertyTypeStubs()) { memberType.AddPropertyType(p.Value); } var memberTypeServiceMock = new Mock <IMemberTypeService>(); memberTypeServiceMock.Setup(x => x.GetDefault()).Returns("Member"); var membershipServiceMock = new Mock <IMembershipMemberService>(); membershipServiceMock.Setup(service => service.Exists("test")).Returns(false); membershipServiceMock.Setup(service => service.GetByEmail("*****@*****.**")).Returns(() => null); membershipServiceMock.Setup( service => service.CreateWithIdentity(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>())) .Callback((string u, string e, string p, string m, bool isApproved) => { createdMember = new Member("test", e, u, p, memberType, isApproved); }) .Returns(() => createdMember); var provider = new MembersMembershipProvider(membershipServiceMock.Object, memberTypeServiceMock.Object); provider.Initialize("test", new NameValueCollection { { "passwordFormat", "Hashed" }, { "hashAlgorithmType", "HMACSHA256" } }); MembershipCreateStatus status; provider.CreateUser("test", "test", "testtest$1", "*****@*****.**", "test", "test", true, "test", out status); Assert.AreNotEqual("test", createdMember.RawPasswordValue); string salt; var storedPassword = provider.StoredPassword(createdMember.RawPasswordValue, out salt); var hashedPassword = provider.EncryptOrHashPassword("testtest$1", salt); Assert.AreEqual(hashedPassword, storedPassword); }
/// <summary> /// Re-fetches the database data to map to the PersistedContent object and re-assigns the already mapped the posted properties so that the display object is up-to-date /// </summary> /// <param name="contentItem"></param> /// <param name="lookup"></param> /// <remarks> /// This is done during an update if the membership provider has changed some underlying data - we need to ensure that our model is consistent with that data /// </remarks> private void RefetchMemberData(MemberSave contentItem, LookupType lookup) { var currProps = contentItem.PersistedContent.Properties.ToArray(); switch (MembershipScenario) { case MembershipScenario.NativeUmbraco: switch (lookup) { case LookupType.ByKey: //Go and re-fetch the persisted item contentItem.PersistedContent = Services.MemberService.GetByKey(contentItem.Key); break; case LookupType.ByUserName: contentItem.PersistedContent = Services.MemberService.GetByUsername(contentItem.Username.Trim()); break; } break; case MembershipScenario.CustomProviderWithUmbracoLink: case MembershipScenario.StandaloneCustomProvider: default: var membershipUser = _provider.GetUser(contentItem.Key, false); //Go and re-fetch the persisted item contentItem.PersistedContent = Mapper.Map <MembershipUser, IMember>(membershipUser); break; } UpdateName(contentItem); // re-assign the mapped values that are not part of the membership provider properties. var builtInAliases = ConventionsHelper.GetStandardPropertyTypeStubs().Select(x => x.Key).ToArray(); foreach (var p in contentItem.PersistedContent.Properties) { var valueMapped = currProps.FirstOrDefault(x => x.Alias == p.Alias); if (builtInAliases.Contains(p.Alias) == false && valueMapped != null) { p.SetValue(valueMapped.GetValue()); } } }
public void Deleting_PropertyType_Removes_The_Property_From_Member() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "*****@*****.**", "pass", "test"); ServiceContext.MemberService.Save(member); var initProps = member.Properties.Count; //remove a property (NOT ONE OF THE DEFAULTS) var standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(); memberType.RemovePropertyType(memberType.PropertyTypes.First(x => standardProps.ContainsKey(x.Alias) == false).Alias); ServiceContext.MemberTypeService.Save(memberType); //re-load it from the db member = ServiceContext.MemberService.GetById(member.Id); Assert.AreEqual(initProps - 1, member.Properties.Count); }
/// <summary> /// Ensure that all the built-in membership provider properties have their correct data type /// and property editors assigned. This occurs prior to saving so that the correct values are persisted. /// </summary> /// <param name="memberType"></param> private void EnsureExplicitDataTypeForBuiltInProperties(IContentTypeBase memberType) { var builtinProperties = ConventionsHelper.GetStandardPropertyTypeStubs(_shortStringHelper); foreach (var propertyType in memberType.PropertyTypes) { if (builtinProperties.ContainsKey(propertyType.Alias)) { //this reset's its current data type reference which will be re-assigned based on the property editor assigned on the next line if (builtinProperties.TryGetValue(propertyType.Alias, out var propDefinition) && propDefinition != null) { propertyType.DataTypeId = propDefinition.DataTypeId; propertyType.DataTypeKey = propDefinition.DataTypeKey; } else { propertyType.DataTypeId = 0; propertyType.DataTypeKey = default; } } } }
/// <summary> /// This ensures that the internal membership property types are removed from validation before processing the validation /// since those properties are actually mapped to real properties of the IMember. /// This also validates any posted data for fields that are sensitive. /// </summary> /// <param name="model"></param> /// <param name="modelWithProperties"></param> /// <param name="actionContext"></param> /// <returns></returns> public override bool ValidateProperties(MemberSave model, IContentProperties <ContentPropertyBasic> modelWithProperties, HttpActionContext actionContext) { var propertiesToValidate = model.Properties.ToList(); var defaultProps = ConventionsHelper.GetStandardPropertyTypeStubs(); var exclude = defaultProps.Select(x => x.Value.Alias).ToArray(); foreach (var remove in exclude) { propertiesToValidate.RemoveAll(property => property.Alias == remove); } //if the user doesn't have access to sensitive values, then we need to validate the incoming properties to check //if a sensitive value is being submitted. if (UmbracoContextAccessor.UmbracoContext.Security.CurrentUser.HasAccessToSensitiveData() == false) { var contentType = _memberTypeService.Get(model.PersistedContent.ContentTypeId); var sensitiveProperties = contentType .PropertyTypes.Where(x => contentType.IsSensitiveProperty(x.Alias)) .ToList(); foreach (var sensitiveProperty in sensitiveProperties) { var prop = propertiesToValidate.FirstOrDefault(x => x.Alias == sensitiveProperty.Alias); if (prop != null) { //this should not happen, this means that there was data posted for a sensitive property that //the user doesn't have access to, which means that someone is trying to hack the values. var message = $"property with alias: {prop.Alias} cannot be posted"; actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.NotFound, new InvalidOperationException(message)); return(false); } } } return(ValidateProperties(propertiesToValidate, model.PersistedContent.Properties.ToList(), actionContext)); }