Ejemplo n.º 1
0
        //[UmbracoAuthorize(Permissions = new[] { FixedPermissionIds.Rollback })]
        public virtual JsonResult RollbackForm(HiveId id, HiveId revisionId)
        {
            using (var uow = Hive.Create <IContentStore>())
            {
                var entity = uow.Repositories.Get <TypedEntity>(id);
                if (entity == null)
                {
                    throw new NullReferenceException("Could not find entity with id " + id);
                }

                var revision = uow.Repositories.Revisions.Get <TypedEntity>(id, revisionId);
                if (revision == null)
                {
                    throw new NullReferenceException("Could not find revision with id " + revisionId);
                }

                var newRevision = revision.CopyToNewRevision();

                uow.Repositories.Revisions.AddOrUpdate(newRevision);
                uow.Complete();

                var successMsg = "Rollback.Success.Message".Localize(this, new
                {
                    Name = entity.GetAttributeValue(NodeNameAttributeDefinition.AliasValue, "Name")
                });

                Notifications.Add(new NotificationMessage(
                                      successMsg,
                                      "Rollback.Title".Localize(this), NotificationType.Success));

                return(new CustomJsonResult(new
                {
                    success = true,
                    notifications = Notifications,
                    msg = successMsg
                }.ToJsonString));
            }
        }
Ejemplo n.º 2
0
        public virtual ActionResult Sort(HiveId?id)
        {
            if (id.IsNullValueOrEmpty())
            {
                return(HttpNotFound());
            }

            using (var uow = Hive.Create <IContentStore>())
            {
                var exists = uow.Repositories.Exists <TypedEntity>(id.Value);
                if (!exists)
                {
                    throw new ArgumentException(string.Format("No entity found for id: {0} on action Sort", id));
                }

                var model = new SortModel {
                    ParentId = id.Value
                };

                var items = uow.Repositories.GetLazyChildRelations(id.Value, FixedRelationTypes.DefaultRelationType);

                model.Items = items.Select(
                    x => new SortItem
                {
                    UtcCreated = x.Destination.UtcCreated,
                    Id         = x.Destination.Id,
                    SortIndex  = x.Ordinal,
                    //TODO: Casting the relation as a TPE here but the item may be related to something else, not a TPE: need a helper method for returning the name
                    Name =
                        ((TypedEntity)x.Destination).Attributes[NodeNameAttributeDefinition.AliasValue].Values[
                            "Name"].ToString()
                })
                              .OrderBy(x => x.SortIndex)
                              .ToArray();

                return(View(model));
            }
        }
Ejemplo n.º 3
0
        //[UmbracoAuthorize(Permissions = new[] { FixedPermissionIds.Sort })]
        public virtual JsonResult SortForm(SortModel model)
        {
            if (!TryValidateModel(model))
            {
                return(ModelState.ToJsonErrors());
            }

            using (var uow = Hive.Create <IContentStore>())
            {
                var found  = uow.Repositories.Get(model.ParentId);
                var exists = uow.Repositories.Exists <TypedEntity>(model.ParentId);
                if (!exists)
                {
                    throw new ArgumentException(string.Format("No entity found for id: {0} on action Sort", model.ParentId));
                }

                var childRelations = uow.Repositories.GetChildRelations(model.ParentId, FixedRelationTypes.DefaultRelationType);

                foreach (var item in model.Items)
                {
                    var relation = childRelations.Single(x => x.DestinationId.EqualsIgnoringProviderId(item.Id));
                    uow.Repositories.ChangeRelation(relation, relation.SourceId, relation.DestinationId, item.SortIndex);
                }

                uow.Complete();
            }

            Notifications.Add(new NotificationMessage(
                                  "Sort.Success.Message".Localize(this),
                                  "Sort.Title".Localize(this), NotificationType.Success));
            return(new CustomJsonResult(new
            {
                success = true,
                notifications = Notifications,
                msg = "Sort.Success.Message".Localize(this)
            }.ToJsonString));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Resets a user's password to a new, automatically generated password.
        /// </summary>
        /// <param name="username">The user to reset the password for.</param>
        /// <param name="answer">The password answer for the specified user.</param>
        /// <returns>
        /// The new password for the specified user.
        /// </returns>
        public override string ResetPassword(string username, string answer)
        {
            using (var uow = Hive.Create())
            {
                var user = GetRebelUser(uow, username, false);

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

                if (Membership.RequiresQuestionAndAnswer && string.IsNullOrWhiteSpace(answer))
                {
                    throw new InvalidOperationException("Invalid answer entered!");
                }

                if (Membership.RequiresQuestionAndAnswer && !string.IsNullOrWhiteSpace(answer) && !user.PasswordAnswer.Equals(answer, StringComparison.OrdinalIgnoreCase))
                {
                    throw new InvalidOperationException("Invalid answer entered!");
                }

                // Generate random password
                var newPassword = new byte[16];
                var rng         = RandomNumberGenerator.Create();
                rng.GetBytes(newPassword);

                var newPasswordString = Convert.ToBase64String(newPassword);
                var salt = string.Empty;
                user.Password     = TransformPassword(newPasswordString, ref salt);
                user.PasswordSalt = salt;

                uow.Repositories.AddOrUpdate(user);
                uow.Complete();

                return(newPasswordString);
            }
        }
Ejemplo n.º 5
0
        public virtual ActionResult Language(HiveId?id)
        {
            if (id.IsNullValueOrEmpty())
            {
                return(HttpNotFound());
            }

            // TODO: Check for a current language
            using (var uow = Hive.Create <IContentStore>())
            {
                //get the typed/content entity for which to assign hostnames
                var entity = uow.Repositories.Get <TypedEntity>(id.Value);
                if (entity == null)
                {
                    throw new ArgumentException("Could not find entity with id " + id);
                }

                //get the assigned hostnames
                var languageRelations = uow.Repositories.GetParentRelations(id.Value, FixedRelationTypes.LanguageRelationType);
                var language          = languageRelations.Any() ? languageRelations.Single().MetaData.SingleOrDefault(x => x.Key == "IsoCode").Value : null;

                return(View(new LanguageModel
                {
                    Id = id.Value,
                    IsoCode = language,
                    InstalledLanguages = BackOfficeRequestContext.Application.Settings.Languages
                                         .Where(x => x.IsoCode != id.Value.ToString())
                                         .OrderBy(x => x.Name)
                                         .Select(x => new SelectListItem
                    {
                        Text = x.Name,
                        Value = x.IsoCode
                    }).ToList()
                }));
            }
        }
        public ActionResult EditForm(HiveId id)
        {
            Mandate.ParameterNotEmpty(id, "id");

            using (var uow = Hive.Create())
            {
                var userEntity = uow.Repositories.Get <UserGroup>(id);

                if (userEntity == null)
                {
                    throw new ArgumentException(string.Format("No entity for id: {0} on action EditForm", id));
                }

                var userGroupViewModel = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map <UserGroup, UserGroupEditorModel>(userEntity);

                PopulatePermissions(userGroupViewModel);

                //need to ensure that all of the Ids are mapped correctly, when editing existing content the only reason for this
                //is to ensure any new document type properties that have been created are reflected in the new content revision
                ReconstructModelPropertyIds(userGroupViewModel);

                return(ProcessSubmit(userGroupViewModel, userEntity));
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        ///   Gets the password for the specified user name from the data source.
        /// </summary>
        /// <param name = "username">The user to retrieve the password for.</param>
        /// <param name = "answer">The password answer for the user.</param>
        /// <returns>The password for the specified user name.</returns>
        /// <remarks>
        /// </remarks>
        public override string GetPassword(string username, string answer)
        {
            if (!EnablePasswordRetrieval)
            {
                throw new InvalidOperationException("Password retrieval is not enabled!");
            }

            using (var uow = Hive.Create())
            {
                var user = GetRebelUser(uow, username, false);

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

                if ((RequiresQuestionAndAnswer && answer.Equals(user.PasswordAnswer, StringComparison.OrdinalIgnoreCase)) || !RequiresQuestionAndAnswer)
                {
                    return(UnEncodePassword(user.Password));
                }

                throw new MembershipPasswordException();
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Returns the ActionResult for the CreateNew wizard view
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        protected virtual ActionResult CreateNewView(CreateContentModel model)
        {
            Mandate.ParameterNotNull(model, "model");

            //lookup the doc type for the node id, find out which doc type children are allowed

            using (var uow = Hive.Create <IContentStore>())
            {
                var allSchemaTypeIds = uow.Repositories.Schemas.GetDescendentRelations(RootSchemaNodeId, FixedRelationTypes.DefaultRelationType)
                                       .DistinctBy(x => x.DestinationId)
                                       .Select(x => x.DestinationId).ToArray();

                var schemas = uow.Repositories.Schemas.Get <EntitySchema>(true, allSchemaTypeIds);

                //the filtered doc types to choose from based on the parent node (default is all of them)
                var filteredSchemas = schemas;

                //get the parent content if it's not the root
                if (model.ParentId != VirtualRootNodeId)
                {
                    //ensure the parent exists!
                    var parentEntity = uow.Repositories.Get <TypedEntity>(model.ParentId);
                    if (parentEntity == null)
                    {
                        throw new ArgumentException(string.Format("No content found for id: {0} on action CreateNew", model.ParentId));
                    }

                    //ensure the doc type exists!
                    //TODO: We reload the EntitySchema here so it has the right providerid, but as soon as TypedEntity.EntitySchema.Id gets mapped properly
                    //when loading TypedEntity we won't have to
                    var parentSc = uow.Repositories.Schemas.Get <EntitySchema>(parentEntity.EntitySchema.Id);
                    if (parentSc == null)
                    {
                        throw new ArgumentException(string.Format("No doc type found for id: {0} on action CreateNew",
                                                                  parentEntity.EntitySchema.Id));
                    }
                    var parentDocType = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map <EntitySchema, DocumentTypeEditorModel>(parentSc);

                    //filter the doc types to the allowed ones
                    filteredSchemas = schemas
                                      .Where(x => parentDocType.AllowedChildIds.Contains(x.Id, new HiveIdComparer(true)))
                                      .ToArray();
                }

                //validate the the selected doc type in the model is in fact one of the child doc types
                if (!model.SelectedDocumentTypeId.IsNullValueOrEmpty())
                {
                    if (!filteredSchemas.Select(x => x.Id)
                        .Contains(model.SelectedDocumentTypeId, new HiveIdComparer(true)))
                    {
                        ModelState.AddModelError("SelectedDocumentTypeId", "The selected document type id specified was not found in the allowed document types collection for the current node");
                    }
                }

                EnsureCreateWizardViewBagData(filteredSchemas);

                if (!filteredSchemas.Any())
                {
                    model.NoticeBoard.Add(new NotificationMessage("Content.NoChildTypesAllowed.Message".Localize(this), NotificationType.Warning));
                }
            }

            return(View("CreateNew", model));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// When editing or creating content, this will bind the model, check the model state errors, add appropriate notifications
        /// return the error view or redirect to the correct place and also persist the data to the repository.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        protected virtual ActionResult ProcessSubmit(TEditorModel model, Revision <TypedEntity> entity, bool isRevisional)
        {
            Mandate.ParameterNotNull(model, "model");

            //bind it's data
            model.BindModel(this);

            //if there's model errors, return the view
            if (!ModelState.IsValid)
            {
                AddValidationErrorsNotification();
                return(View("Edit", model));
            }

            //persist the data
            var success = false;

            using (var uow = Hive.Create <IContentStore>())
            {
                //EnsureUniqueName(model);

                if (entity == null)
                {
                    //map to new entity
                    entity = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map <TEditorModel, Revision <TypedEntity> >(model);
                }
                else
                {
                    //map to existing entity
                    BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map(model, entity.Item);

                    //then create a new revision
                    entity = entity.CopyToNewRevision();
                }


                // Try publish
                if (ValueProvider.GetValue("submit.Publish") != null)
                {
                    success = this.TryExecuteSecuredMethod(x => x.ProcessPublish(model, entity), model.Id).Success;
                    if (!success)
                    {
                        // Report unathorized
                        NotifyForProcess(NotificationState.PublishUnathorized, model);
                    }
                }
                // Try unpublish
                else if (ValueProvider.GetValue("submit.Unpublish") != null)
                {
                    success = this.TryExecuteSecuredMethod(x => x.ProcessUnpublish(model, entity), model.Id).Success;
                    if (!success)
                    {
                        // Report unathorized
                        NotifyForProcess(NotificationState.UnpublishedUnauthorized, model);
                    }
                }
                // Try save
                else
                {
                    success = this.TryExecuteSecuredMethod(x => x.ProcessSave(model, entity), model.Id).Success;
                    if (!success)
                    {
                        // Report unathorized
                        NotifyForProcess(NotificationState.SaveUnauthorized, model);
                    }
                }

                if (success)
                {
                    if (isRevisional)
                    {
                        uow.Repositories.Revisions.AddOrUpdate(entity);
                    }
                    else
                    {
                        uow.Repositories.AddOrUpdate(entity.Item);
                    }
                    uow.Complete();
                }
                else
                {
                    uow.Abandon();
                }
            }

            if (success)
            {
                // Perf: use a readonly unit here rather than delaying the writer
                using (var uow = ReadonlyHive.CreateReadonly <IContentStore>())
                {
                    //need to clear the URL cache for this entry
                    BackOfficeRequestContext.RoutingEngine.ClearCache(clearGeneratedUrls: true, clearMappedUrls: true);

                    //add path for entity for SupportsPathGeneration (tree syncing) to work
                    GeneratePathsForCurrentEntity(uow.Repositories.GetEntityPaths <TypedEntity>(entity.Item.Id, FixedRelationTypes.DefaultRelationType));

                    return(RedirectToAction("Edit", new { id = entity.Item.Id }));
                }
            }
            return(View("Edit", model));
        }
Ejemplo n.º 10
0
        //[RebelAuthorize(Permissions = new[] { FixedPermissionIds.Hostnames })]
        public virtual JsonResult HostnameForm(HostnamesModel model)
        {
            Mandate.ParameterNotEmpty(model.Id, "Id");

            //need to validate the hostnames, first need to remove the invalid required field of the main host name field as this is only required for client side validation
            ModelState.RemoveAll(x => x.Key == "NewHostname");
            foreach (var h in model.AssignedHostnames)
            {
                if (!Regex.IsMatch(h.Hostname, @"^([\w-\.:]+)$", RegexOptions.IgnoreCase))
                {
                    ModelState.AddDataValidationError(string.Format("{0} is an invalid host name", h));
                }
                else if (h.Hostname.Contains(":") && !Regex.IsMatch(h.Hostname.Split(':')[1], @"^\d+$"))
                {
                    ModelState.AddDataValidationError(string.Format("{0} is an invalid port number", h.Hostname.Split(':')[1]));
                }
                //check if the hostname already exists in the collection
                if (BackOfficeRequestContext.RoutingEngine.DomainList.ContainsHostname(h.Hostname))
                {
                    //check if that hostname is assigned to a different node
                    if (BackOfficeRequestContext.RoutingEngine.DomainList[h.Hostname].ContentId != model.Id)
                    {
                        ModelState.AddDataValidationError(string.Format("{0} is already assigned to node id {1}", h.Hostname, BackOfficeRequestContext.RoutingEngine.DomainList[h.Hostname].ContentId));
                    }
                }
                if (model.AssignedHostnames.Count(x => x.Hostname == h.Hostname) > 1)
                {
                    ModelState.AddDataValidationError(string.Format("{0} is a duplicate entry in the submitted list", h));
                }
                if (!ModelState.IsValid)
                {
                    return(ModelState.ToJsonErrors());
                }
            }

            using (var uow = Hive.Create <IContentStore>())
            {
                //get the content entity for the hostname assignment
                var entity = uow.Repositories.Get <TypedEntity>(model.Id);
                if (entity == null)
                {
                    throw new NullReferenceException("Could not find entity with id " + model.Id);
                }

                //map the hostname entities from the model
                var hostnames = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map <IEnumerable <Hostname> >(model);
                //need to remove the hostnames that no longer exist
                var assignedHostnames = uow.Repositories.GetChildren <Hostname>(FixedRelationTypes.HostnameRelationType, model.Id);
                foreach (var a in assignedHostnames.Where(x => !hostnames.Select(h => h.Id).Contains(x.Id)))
                {
                    uow.Repositories.Delete <Hostname>(a.Id);
                }

                uow.Repositories.AddOrUpdate(hostnames);
                uow.Complete();

                //clears the domain cache
                BackOfficeRequestContext.RoutingEngine.ClearCache(clearDomains: true, clearGeneratedUrls: true);

                var successMsg = "Hostname.Success.Message".Localize(this, new
                {
                    Count = model.AssignedHostnames.Count,
                    Name  = entity.GetAttributeValue(NodeNameAttributeDefinition.AliasValue, "Name")
                });
                Notifications.Add(new NotificationMessage(successMsg, "Hostname.Title".Localize(this), NotificationType.Success));

                return(new CustomJsonResult(new
                {
                    success = true,
                    notifications = Notifications,
                    msg = successMsg
                }.ToJsonString));
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Ensures the select lists are built for the model
        /// </summary>
        /// <param name="model"></param>
        protected virtual void EnsureSelectListData(TEditorModel model)
        {
            //set the icons/thumbnails select list
            model.AvailableIcons = new List <SelectListItem>(BackOfficeRequestContext.DocumentTypeIconResolver
                                                             .Resolve()
                                                             .Select(f =>
            {
                if (f.IconType == IconType.Image)
                {
                    return(new SelectListItem {
                        Text = f.Name, Value = f.Url
                    });
                }
                return(new SelectListItem {
                    Text = "." + f.Name, Value = DocumentTypeIconFileResolver.SpriteNamePrefixValue + f.Name
                });
            })).OrderBy(x => x.Text).ToArray();

            model.AvailableThumbnails = new List <SelectListItem>(BackOfficeRequestContext.DocumentTypeThumbnailResolver
                                                                  .Resolve()
                                                                  .Select(f =>
            {
                if (f.IconType == IconType.Image)
                {
                    return(new SelectListItem {
                        Text = f.Name, Value = VirtualPathUtility.GetFileName(f.Url)
                    });
                }
                return(new SelectListItem {
                    Text = "." + f.Name, Value = DocumentTypeThumbnailFileResolver.SpriteNamePrefixValue + f.Name
                });
            })).OrderBy(x => x.Text).ToArray();

            model.IconsBaseUrl      = BackOfficeRequestContext.Application.Settings.UmbracoFolders.DocTypeIconFolder;
            model.ThumbnailsBaseUrl = BackOfficeRequestContext.Application.Settings.UmbracoFolders.DocTypeThumbnailFolder;

            model.SpriteFileUrls = BackOfficeRequestContext.DocumentTypeIconResolver.Sprites.Select(x =>
                                                                                                    BackOfficeRequestContext.Application.Settings.UmbracoFolders.DocTypeIconFolder + "/" + x.Value.Name);

            using (var uow = Hive.Create <IContentStore>())
            {
                //get the children for the current virtual root
                //var children = uow.Repositories.Schemas.GetEntityByRelationType<EntitySchema>(FixedRelationTypes.DefaultRelationType, RootSchema).ToArray();

                var allSchemaTypeIds = uow.Repositories.Schemas.GetDescendentRelations(RootSchema, FixedRelationTypes.DefaultRelationType)
                                       .DistinctBy(x => x.DestinationId)
                                       .Select(x => x.DestinationId).ToArray();
                var allSchemaTypes = uow.Repositories.Schemas.Get <EntitySchema>(true, allSchemaTypeIds);

                var entityDesendentSchemaTypeIds = uow.Repositories.Schemas.GetDescendentRelations(model.Id, FixedRelationTypes.DefaultRelationType)
                                                   .DistinctBy(x => x.DestinationId)
                                                   .Select(x => x.DestinationId).ToArray();


                //get the allowed child document types select list
                model.AllowedChildren = new List <SelectListItem>(
                    allSchemaTypes.Where(x => !x.IsAbstract)
                    .Select(x =>
                            new SelectListItem
                {
                    Text     = x.Name,
                    Value    = x.Id.ToString(),
                    Selected = model.AllowedChildIds.Contains(x.Id, new HiveIdComparer(true))
                })).OrderBy(x => x.Text).ToArray();

                model.InheritFrom = new List <HierarchicalSelectListItem>(
                    allSchemaTypes.Where(x => x.Id != model.Id && !entityDesendentSchemaTypeIds.Contains(x.Id)).Select(x =>
                                                                                                                       new HierarchicalSelectListItem
                {
                    Text         = x.Name,
                    Value        = x.Id.ToString(),
                    ParentValues = x.RelationProxies.GetParentRelations(FixedRelationTypes.DefaultRelationType).Where(y => y.Item.SourceId.Value != RootSchema.Value).Select(y => y.Item.SourceId.ToString()).ToArray(),
                    Selected     = model.InheritFromIds.Contains(x.Id, new HiveIdComparer(true))
                })).OrderBy(x => x.Text).ToArray();

                //get the data type list
                model.AvailableDataTypes = uow.Repositories.Schemas.GetAll <AttributeType>()
                                           .Where(x => !x.Id.IsSystem())
                                           .Select(x =>
                                                   new SelectListItem
                {
                    Text  = x.Name,
                    Value = x.Id.ToString()
                }).OrderBy(x => x.Text).ToArray();
            }
        }
        protected ActionResult ProcessSubmit(UserGroupEditorModel model, UserGroup entity)
        {
            Mandate.ParameterNotNull(model, "model");

            //bind it's data
            model.BindModel(this);

            //if there's model errors, return the view
            if (!ModelState.IsValid)
            {
                AddValidationErrorsNotification();
                return(View("Edit", model));
            }

            //persist the data
            using (var uow = Hive.Create())
            {
                if (entity == null)
                {
                    //map to new entity
                    entity =
                        BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map
                        <UserGroupEditorModel, UserGroup>(model);

                    //entity.RelationProxies.EnlistParentById(VirtualRoot, FixedRelationTypes.DefaultRelationType);
                }
                else
                {
                    //map to existing entity
                    BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map(model, entity);
                }

                uow.Repositories.AddOrUpdate(entity);

                // Save permissions
                var metaDataumList = new List <RelationMetaDatum>();
                foreach (var permissionModel in model.Permissions)
                {
                    var permission = BackOfficeRequestContext.RegisteredComponents.Permissions.SingleOrDefault(x => x.Metadata.Id == permissionModel.PermissionId);
                    if (permission == null)
                    {
                        throw new NullReferenceException("Could not find permission with id " + permissionModel.PermissionId);
                    }

                    metaDataumList.Add(BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map <RelationMetaDatum>(permissionModel));
                }

                // Change permissions relation
                uow.Repositories.ChangeOrCreateRelationMetadata(entity.Id, FixedHiveIds.SystemRoot, FixedRelationTypes.PermissionRelationType, metaDataumList.ToArray());

                uow.Complete();

                Notifications.Add(new NotificationMessage(
                                      "UserGroup.Save.Message".Localize(this),
                                      "UserGroup.Save.Title".Localize(this),
                                      NotificationType.Success));

                //add path for entity for SupportsPathGeneration (tree syncing) to work
                GeneratePathsForCurrentEntity(uow.Repositories.GetEntityPaths <TypedEntity>(entity.Id, FixedRelationTypes.DefaultRelationType, VirtualRoot));

                return(RedirectToAction("Edit", new { id = entity.Id }));
            }
        }
Ejemplo n.º 13
0
        public virtual ActionResult CreateNewForm(CreateFileModel createModel)
        {
            Mandate.ParameterNotNull(createModel, "createModel");
            Mandate.That <NullReferenceException>(createModel.Name != null);
            Mandate.That <NullReferenceException>(!createModel.ParentId.IsNullValueOrEmpty());

            EnsureViewData(createModel);

            //validate the model
            if (!TryUpdateModel(createModel))
            {
                return(View(createModel));
            }

            using (var uow = Hive.Create())
            {
                if (createModel.ParentId != FixedHiveIds.SystemRoot)
                {
                    //validate the parent
                    var parentFile = uow.Repositories.Get <File>(createModel.ParentId);
                    if (parentFile == null)
                    {
                        throw new ArgumentException("No folder could be found for the parent id specified");
                    }
                }


                //if its a folder, then we just create it and return success.
                if (createModel.CreateType == CreateFileType.Folder)
                {
                    var folder = new File()
                    {
                        IsContainer = true,
                        RootedPath  = createModel.ParentId == FixedHiveIds.SystemRoot
                                ? createModel.Name.ToUmbracoAlias(removeSpaces: true)
                                : (string)createModel.ParentId.Value + "/" + createModel.Name.ToUmbracoAlias(removeSpaces: true)
                    };
                    uow.Repositories.AddOrUpdate(folder);
                    uow.Complete();

                    //add notification
                    Notifications.Add(new NotificationMessage("Folder.Save.Message".Localize(this), "Folder.Save.Title".Localize(this), NotificationType.Success));

                    //add path for entity for SupportsPathGeneration (tree syncing) to work
                    GeneratePathsForCurrentEntity(CreatePaths(folder));

                    return(RedirectToAction("CreateNew", new { id = folder.Id }));
                }

                var model = FileEditorModel.CreateNew();
                model.Name     = createModel.Name.ToUmbracoAlias(removeSpaces: true) + createModel.FileExtension;
                model.ParentId = createModel.ParentId;

                if (!createModel.Stub.IsNullValueOrEmpty())
                {
                    PopulateFileContentFromStub(model, createModel.Stub.Value);
                }

                EnsureViewData(model, null);

                OnBeforeCreate(createModel, model);

                var file = PerformSave(model);

                OnAfterCreate(file);

                //add notification
                Notifications.Add(new NotificationMessage(SaveSuccessfulMessage, SaveSuccessfulTitle, NotificationType.Success));

                //add path for entity for SupportsPathGeneration (tree syncing) to work
                GeneratePathsForCurrentEntity(CreatePaths(file));

                return(RedirectToAction("Edit", new { id = file.Id }));
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Adds a new membership user to the data source.
        /// </summary>
        /// <param name="username">The user name for the new user.</param>
        /// <param name="password">The password for the new user.</param>
        /// <param name="email">The e-mail address for the new user.</param>
        /// <param name="passwordQuestion">The password question for the new user.</param>
        /// <param name="passwordAnswer">The password answer for the new user</param>
        /// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
        /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
        /// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"/> enumeration value indicating whether the user was created successfully.</param>
        /// <returns>
        /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the information for the newly created user.
        /// </returns>
        public override MembershipUser CreateUser(string username, string password, string email,
                                                  string passwordQuestion, string passwordAnswer, bool isApproved,
                                                  object providerUserKey, out MembershipCreateStatus status)
        {
            try
            {
                // Validate the username
                if (UserNameExists(username))
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                    return(null);
                }

                // Validate the email address
                if (RequiresUniqueEmail && !ValidateEmail(email, HiveId.Empty))
                {
                    status = MembershipCreateStatus.DuplicateEmail;
                    return(null);
                }

                // Validate the password
                var e = new ValidatePasswordEventArgs(username, password, true);

                base.OnValidatingPassword(e);

                if (e.Cancel || !ValidatePassword(password))
                {
                    status = MembershipCreateStatus.InvalidPassword;
                    return(null);
                }

                using (var uow = Hive.Create())
                {
                    var salt = "";
                    var transformedPassword = TransformPassword(password, ref salt);

                    var user = new RebelMembershipUser
                    {
                        Username               = username,
                        Password               = transformedPassword,
                        PasswordSalt           = salt,
                        Email                  = email,
                        PasswordQuestion       = passwordQuestion,
                        PasswordAnswer         = passwordAnswer,
                        IsApproved             = isApproved,
                        LastActivityDate       = DateTime.UtcNow,
                        LastPasswordChangeDate = DateTime.UtcNow,
                        LastLoginDate          = DateTime.UtcNow
                    };

                    user.RelationProxies.EnlistParentById(VirtualRootId, FixedRelationTypes.DefaultRelationType);

                    uow.Repositories.AddOrUpdate(user);
                    uow.Complete();

                    status = MembershipCreateStatus.Success;

                    return(ConvertUserToMembershipUser(user));
                }
            }
            catch (Exception e)
            {
                status = MembershipCreateStatus.ProviderError;
            }

            return(null);
        }
Ejemplo n.º 15
0
        //[RebelAuthorize(Permissions = new[] { FixedPermissionIds.Publish })]
        public JsonResult PublishForm(PublishModel model)
        {
            if (!TryValidateModel(model))
            {
                return(ModelState.ToJsonErrors());
            }

            using (var uow = Hive.Create <IContentStore>())
            {
                var cacheRecycler = new CacheRecycler(Request.Url.GetLeftPart(UriPartial.Authority),
                                                      BackOfficeRequestContext.Application.FrameworkContext);


                var contentEntity = uow.Repositories.Revisions.GetLatestRevision <TypedEntity>(model.Id);
                if (contentEntity == null)
                {
                    throw new ArgumentException(string.Format("No entity found for id: {0} on action PublishForm", model.Id));
                }

                //get its children recursively
                if (model.IncludeChildren)
                {
                    // Get all descendents
                    var descendents = uow.Repositories.GetDescendentRelations(model.Id, FixedRelationTypes.DefaultRelationType);

                    foreach (var descendent in descendents)
                    {
                        //get the revision
                        var revisionEntity = uow.Repositories.Revisions.GetLatestRevision <TypedEntity>(descendent.DestinationId);

                        //publish it if it's already published or if the user has specified to publish unpublished content
                        if (revisionEntity != null && (revisionEntity.MetaData.StatusType.Alias == FixedStatusTypes.Published.Alias) || model.IncludeUnpublishedChildren)
                        {
                            var publishRevision = revisionEntity.CopyToNewRevision(FixedStatusTypes.Published);
                            uow.Repositories.Revisions.AddOrUpdate(publishRevision);

                            cacheRecycler.RecycleCacheFor(revisionEntity.Item);
                        }
                    }
                }

                //publish this node
                var toPublish = contentEntity.CopyToNewRevision(FixedStatusTypes.Published);
                uow.Repositories.Revisions.AddOrUpdate(toPublish);

                var path = uow.Repositories.GetEntityPaths(model.Id, FixedRelationTypes.DefaultRelationType);

                //save
                uow.Complete();

                cacheRecycler.RecycleCacheFor(toPublish.Item);

                var contentViewModel = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map <Revision <TypedEntity>, ContentEditorModel>(toPublish);

                Notifications.Add(new NotificationMessage(
                                      model.IncludeChildren
                                          ? "Publish.ChildrenSuccess.Message".Localize(this, new { contentViewModel.Name }, encode: false)
                                          : "Publish.SingleSuccess.Message".Localize(this, new { contentViewModel.Name }, encode: false),
                                      "Publish.Title".Localize(this), NotificationType.Success));
                return(new CustomJsonResult(new
                {
                    success = true,
                    notifications = Notifications,
                    path = path.ToJson(),
                    msg = model.IncludeChildren
                                  ? "Publish.ChildrenSuccess.Message".Localize(this, new { contentViewModel.Name }, encode: false)
                                  : "Publish.SingleSuccess.Message".Localize(this, new { contentViewModel.Name }, encode: false)
                }.ToJsonString));
            }
        }