protected override DriverResult Editor(ProjectItemPermissionsPart part, dynamic shapeHelper)
        {
            // only visible in the Create mode
            if (part.Id != default(int))
            {
                return(null);
            }

            var projectId = this.projectService.GetProjectIdFromQueryString();

            var model = this.contentOwnershipHelper.CreateModel();

            List <IUser> customers = new List <IUser>();

            if (projectId != null)
            {
                var project = this.projectService.GetProject(projectId.Value);
                var temp    = this.contentOwnershipHelper.GetCustomersWhoHaveAccessToThisContent(project);
                customers = customers.Union(temp.Where(c => !customers.Any(d => d.Id == c.Id)).ToList()).ToList();
                this.contentOwnershipHelper.RestrictToPeopleWhoHavePermissionInGivenItem(model, project.ContentItem);
            }

            model.Customers.AddRange(customers.Select(c => new SelectListItem {
                Text = CRMHelper.GetFullNameOfUser(c), Value = c.Id.ToString(CultureInfo.InvariantCulture)
            }));

            model.Tag = projectId;
            return(ContentShape("Parts_ProjectItemPermissions_Edit",
                                () => shapeHelper.EditorTemplate(
                                    TemplateName: "Parts/ProjectItemPermissions",
                                    Model: model,
                                    Prefix: Prefix)));
        }
        private ContentItemSetPermissionsViewModel CreateEditPermissionsModel(IEnumerable <int> ids)
        {
            var contentManager = this.orchardServices.ContentManager;
            var contentItems   = contentManager.GetMany <ContentItem>(ids, VersionOptions.Published, QueryHints.Empty).ToList();

            if (contentItems.Count() == 0)
            {
                throw new OrchardCoreException(T("There is no item with the given Id"));
            }

            if (contentItems.Any(c => !this.contentOwnershipService.CurrentUserCanChangePermission(c)))
            {
                throw new OrchardSecurityException(T("You do not have permission to do the operation"));
            }

            var model = this.contentOwnershipHelper.CreateModel();

            this.contentOwnershipHelper.FillPermissions(model, contentItems);

            if (this.ShowCustomers)
            {
                List <IUser> customers = new List <IUser>();
                foreach (var contentItem in contentItems)
                {
                    AttachToProjectPart attachToProjectPart = contentItem.As <AttachToProjectPart>();
                    if (attachToProjectPart != null && attachToProjectPart.Record.Project != null)
                    {
                        var project = contentManager.Get(attachToProjectPart.Record.Project.Id);

                        var temp = this.contentOwnershipHelper.GetCustomersWhoHaveAccessToThisContent(project);
                        customers = customers.Union(temp.Where(c => !customers.Any(d => d.Id == c.Id)).ToList()).ToList();

                        this.contentOwnershipHelper.RestrictToPeopleWhoHavePermissionInGivenItem(model, project);
                    }
                }

                model.Customers.AddRange(customers.Select(c => new SelectListItem {
                    Text = CRMHelper.GetFullNameOfUser(c), Value = c.Id.ToString(CultureInfo.InvariantCulture)
                }));
            }

            foreach (var item in model.ContentItems)
            {
                if (this.masterDetailPermissionManager.HasChildItems(item.ContentItem))
                {
                    model.HasChildren = true;
                }

                if (!item.CurrentUserHasRightToChangePermissions)
                {
                    throw new Security.OrchardSecurityException(T("You don't have permission to change access to the contentItem"));
                }

                item.ContentItemShape = this.orchardServices.ContentManager.BuildDisplay(item.ContentItem, displayType: this.DefaultDisplayType);
            }

            return(model);
        }
Beispiel #3
0
        public void UserThumbnail(
            dynamic Shape,
            dynamic Display,
            TextWriter Output,
            int userId,
            string source,
            int width             = 48,
            int height            = 48,
            string cssClasses     = "",
            string userProfileUrl = "")
        {
            var user     = this.basicDataService.GetOperatorOrCustomerUser(userId);
            var imageTag = new TagBuilder("img");

            imageTag.Attributes.Add("width", width.ToString(CultureInfo.InvariantCulture));
            imageTag.Attributes.Add("height", height.ToString(CultureInfo.InvariantCulture));
            string fullName = CRMHelper.GetFullNameOfUser(user);

            imageTag.Attributes.Add("title", fullName);

            if (string.IsNullOrEmpty(cssClasses))
            {
                imageTag.Attributes.Add("class", cssClasses);
            }

            if (user != null)
            {
                string temp = ProjectHelper.GetThumbnailImageOfUser(user);

                if (!string.IsNullOrEmpty(temp))
                {
                    source = temp;
                }
            }

            imageTag.Attributes.Add("src", source);

            TagBuilder linkTag = null;

            if (!string.IsNullOrEmpty(userProfileUrl))
            {
                linkTag = new TagBuilder("a");
                linkTag.Attributes.Add("href", userProfileUrl);
                Output.Write(linkTag.ToString(TagRenderMode.StartTag));
            }

            Output.Write(imageTag.ToString(TagRenderMode.StartTag));
            Output.Write(imageTag.ToString(TagRenderMode.EndTag));


            if (!string.IsNullOrEmpty(userProfileUrl))
            {
                Output.Write(linkTag.ToString(TagRenderMode.EndTag));
            }
        }
Beispiel #4
0
        public void Evaluate(EvaluateContext context)
        {
            // User
            context.For(UserTokenProvider.LoginedUser, () => context.Data)
            .Token("Email", c =>
            {
                var user = services.WorkContext.CurrentUser;
                if (user == null)
                {
                    return(string.Empty);
                }
                else
                {
                    return(user.Email);
                }
            })
            .Token("Id", c =>
            {
                var user = services.WorkContext.CurrentUser;
                if (user == null)
                {
                    return(string.Empty);
                }
                else
                {
                    return(user.Id);
                }
            })
            .Token("Username", c =>
            {
                var user = services.WorkContext.CurrentUser;
                if (user == null)
                {
                    return(string.Empty);
                }
                else
                {
                    return(user.UserName);
                }
            })
            .Token("FullName", contextParameter =>
            {
                var user = services.WorkContext.CurrentUser;
                if (user == null)
                {
                    return(string.Empty);
                }

                return(CRMHelper.GetFullNameOfUser(user.As <UserPart>()));
            });
        }
Beispiel #5
0
        /// <summary>
        /// Fills the model with the businessUnits that the user has granted to view them
        /// </summary>
        private void FillBusinessUnitsAndUsers(SearchTicketsViewModel model, PostedTicketSearchViewModel postedSearchModel)
        {
            bool restrictToUserPermissions = !this.services.Authorizer.Authorize(Permissions.AdvancedOperatorPermission);

            this.businessUnitService.Fill(model.BusinessUnits, restrictToUserPermissions);

            var selectedBusinessUnits = postedSearchModel.BusinessUnits.ToList();

            // TeamIds of the search
            var teams = new List <int>();

            // set checkes of businessUnits
            model.BusinessUnits
            .ToList()
            .ForEach(c => c.Checked = selectedBusinessUnits.Count(d => d == c.BusinessUnitId) > 0);

            // set checks of teams
            model.BusinessUnits
            .SelectMany(c => c.Teams)
            .ToList()
            .ForEach(c => c.Checked = teams.Count(d => d == c.TeamId) > 0);

            IEnumerable <IUser> users = null;

            if (restrictToUserPermissions)
            {
                users = new[] { this.services.WorkContext.CurrentUser };
            }
            else
            {
                users = this.basicDataService.GetOperators().ToList();
            }

            foreach (var user in users)
            {
                SearchTicketsViewModel.UserViewModel userViewModel = new SearchTicketsViewModel.UserViewModel
                {
                    Id                = user.Id,
                    Username          = CRMHelper.GetFullNameOfUser(user.As <UserPart>()),
                    Checked           = postedSearchModel.Users.Count(c => c == user.Id) > 0,
                    IsAdminOrOperator = true
                };

                model.Users.Add(userViewModel);
            }
        }
        public static T Convert <T>(IUser user)
            where T : UserViewModel, new()
        {
            UserPart userPart = user.As <UserPart>();

            var userModel = new T
            {
                UserId    = user.Id,
                Username  = user.UserName,
                Email     = user.Email,
                Fullname  = CRMHelper.GetFullNameOfUser(user),
                Thumbnail = ProjectHelper.GetThumbnailImageOfUser(user),
                SkypeId   = GetUserField(userPart, FieldNames.UserSkypeIdField),
                Tel       = GetUserField(userPart, FieldNames.UserTelField),
                Tags      = GetUserField(userPart, FieldNames.UserTags),
                Mobile    = GetUserField(userPart, FieldNames.UserMobileField)
            };

            return(userModel);
        }
        private string GetContentItemPermissionChangeDescription(ContentItemPermissionDetailRecord record, string format, string accessType, ContentItem targetContentItem)
        {
            IUser user = record.User != null?
                         this.basicDataService.GetOperatorOrCustomerUser(record.User.Id) :
                             null;

            BusinessUnitPart businessUnit = record.BusinessUnit != null?
                                            this.basicDataService.GetBusinessUnits()
                                            .Select(c => c.As <BusinessUnitPart>())
                                            .FirstOrDefault(c => c.Record.Id == record.BusinessUnit.Id)
                                                : null;

            string contentItemDescription = this.contentItemDescriptorManager.GetDescription(targetContentItem);

            if (user != null)
            {
                string fullName = CRMHelper.GetFullNameOfUser(user);
                return(string.Format(
                           CultureInfo.CurrentUICulture,
                           T(format).Text,
                           accessType,
                           fullName,
                           contentItemDescription));
            }

            if (businessUnit != null)
            {
                return(string.Format(
                           CultureInfo.CurrentUICulture,
                           T(format).Text,
                           accessType,
                           businessUnit.Name + T(" group").Text,
                           contentItemDescription));
            }

            return(string.Empty);
        }
        private void SubstituteTicketProperties(EvaluateContext context)
        {
            context.For(ActivityTokenProvider.TicketKey, () => this.GetTicketPart(context))
            .Token("Status", contextParameter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.StatusRecord == null)
                {
                    return(string.Empty);
                }

                var statusRecords = this.basicDataService.GetStatusRecords().ToList().Select(d => new BasicDataRecordViewModel {
                    Id = d.Id, Name = d.Name
                }).ToList();
                return(this.GetBasicDataRecordName(c.StatusRecord.Id, statusRecords));
            })
            .Token("Service", contextParameter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.Record.Service == null)
                {
                    return(string.Empty);
                }

                var records = this.basicDataService.GetServices().ToList();
                return(this.GetBasicDataRecordName(c.Record.Service.Id, records));
            })
            .Token("RequestingUserEmail", contextParameter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.Record.RequestingUser == null)
                {
                    return(string.Empty);
                }

                return(c.Record.RequestingUser.Email);
            })
            .Token("RequestingUserName", contextParameter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.Record.RequestingUser == null)
                {
                    return(string.Empty);
                }

                return(c.Record.RequestingUser.UserName);
            })
            .Token("RequestingUserFullName", contextParameter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.Record.RequestingUser == null)
                {
                    return(string.Empty);
                }

                var userContentItem = contentManager.Get(c.Record.RequestingUser.Id);

                string fieldValue = CRMHelper.GetFullNameOfUser(userContentItem.As <UserPart>());

                return(fieldValue);
            })
            .Token("Priority", contextParamter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.PriorityRecord == null)
                {
                    return(string.Empty);
                }

                var records = this.basicDataService.GetPriorities().ToList();
                return(this.GetBasicDataRecordName(c.PriorityRecord.Id, records));
            })
            .Token("TicketType", contextParamter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null)
                {
                    return(string.Empty);
                }

                var records = this.basicDataService.GetTicketTypes().ToList();
                return(this.GetBasicDataRecordName(c.Record.TicketType.Id, records));
            })
            .Token("Number", contextParamter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.Record.Identity == null)
                {
                    return(string.Empty);
                }

                return(c.Record.Identity.Id.ToString(CultureInfo.InvariantCulture));
            })
            .Token("Title", contextParsmeter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null)
                {
                    return(string.Empty);
                }

                return(c.Record.Title);
            })
            .Token("Id", contextParsmeter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null)
                {
                    return(string.Empty);
                }

                return(c.Record.Id);
            });
        }
        public void Evaluate(EvaluateContext context)
        {
            // Title
            context.For(ActivityTokenProvider.TitkeKey, () => this.GetPart <TitlePart>(context))
            .Token("Title", c =>
            {
                TitlePart titlePart = this.GetPart <TitlePart>(context);

                if (titlePart == null)
                {
                    return(string.Empty);
                }
                else
                {
                    return(titlePart.Title);
                }
            });

            // User
            context.For(ActivityTokenProvider.UserKey, () => (UserPartRecord)context.Data[UserKey])
            .Token("Email", c =>
            {
                var part = (UserPartRecord)context.Data[UserKey];
                if (part == null)
                {
                    return(string.Empty);
                }
                else
                {
                    return(part.Email);
                }
            })
            .Token("Username", c =>
            {
                var part = (UserPartRecord)context.Data[UserKey];
                if (part == null)
                {
                    return(string.Empty);
                }
                else
                {
                    return(part.Email);
                }
            })
            .Token("FullName", contextParameter =>
            {
                var part = (UserPartRecord)context.Data[UserKey];
                if (part == null)
                {
                    return(string.Empty);
                }

                var userContentItem = contentManager.Get(part.Id);

                // Sometimes the passed UserRecord is not persisted in the database or it is a faked object,
                // so we have to check for nullability
                if (userContentItem != null)
                {
                    return(CRMHelper.GetFullNameOfUser(userContentItem.As <UserPart>()));
                }
                else
                {
                    return(part.UserName);
                }
            });

            // Ticket
            this.SubstituteTicketProperties(context);

            // Email
            this.SubstituteEmailProperties(context);

            // Team
            this.CheckForContentPartId <TeamPart>(context, TeamKey);

            // BusinessUnit
            this.CheckForContentPartId <BusinessUnitPart>(context, BusinessUnitKey);

            // CRMComment
            context.For(ActivityTokenProvider.CRMCommentKey, () => this.GetPart <CRMCommentPart>(context))
            .Token("CommentText", c =>
            {
                var part = this.GetPart <CRMCommentPart>(context);
                if (part == null)
                {
                    return(string.Empty);
                }
                else
                {
                    return(part.Record.CommentText);
                }
            });
        }
Beispiel #10
0
        public ActionResult Operators(UserIndexOptionsViewModel options)
        {
            if (!this.contentOwnershipService.IsCurrentUserOperator())
            {
                return(new HttpUnauthorizedResult());
            }

            options = options ?? new UserIndexOptionsViewModel();
            var operators = this.basicDataService.GetOperators();

            string searchPhrase = string.IsNullOrEmpty(options.Search)? string.Empty: options.Search.ToLower();

            if (!String.IsNullOrWhiteSpace(options.Search))
            {
                operators = operators.Where(u =>
                                            u.UserName.ToLower().Contains(searchPhrase) ||
                                            u.Email.ToLower().Contains(searchPhrase) ||
                                            (CRMHelper.GetFullNameOfUser(u) != null && CRMHelper.GetFullNameOfUser(u).ToLower().Contains(searchPhrase)))
                            .ToList();
            }

            switch (options.Order)
            {
            case UsersOrderViewModel.Username:
                operators = operators.OrderBy(u => u.UserName);
                break;

            case UsersOrderViewModel.Email:
                operators = operators.OrderBy(u => u.Email);
                break;
            }

            var pager      = this.helperService.ReterivePagerFromQueryString();
            var pagerShape = Shape.Pager(pager).PagerId("page");

            pagerShape.TotalItemCount(operators.Count());

            UserListViewModel model = new UserListViewModel
            {
                Pager             = pagerShape,
                Search            = searchPhrase,
                OrderBy           = options.Order,
                OrderByDescending = options.OrderByDescending
            };

            operators = operators.Skip(Math.Min(0, pager.Page - 1) * pager.PageSize).Take(pager.PageSize);

            model.Users.AddRange(operators.Select(c => ProjectHelper.Convert <UserViewModel>(c)));

            var userProjects = this.projectService.GetUsersProjects(operators.Select(c => c.Id));

            foreach (var user in model.Users)
            {
                if (userProjects.ContainsKey(user.UserId))
                {
                    user.UserProjects.AddRange(userProjects[user.UserId].Select(c => new SelectListItem
                    {
                        Value = c.Record.Id.ToString(CultureInfo.InvariantCulture),
                        Text  = c.Record.Title
                    }));
                }
            }

            return(View(model));
        }
Beispiel #11
0
        protected override DriverResult Display(TicketPart part, string displayType, dynamic shapeHelper)
        {
            if (!this.contentOwnershipService.CurrentUserCanViewContent(part))
            {
                throw new Security.OrchardSecurityException(T("You don't have permission to view the item"));
            }

            var priorities    = this.basicDataService.GetPriorities().ToList();
            var statusRecords = this.basicDataService.GetStatusRecords()
                                .Select(c => new StatusRecordViewModel {
                Id = c.Id, Name = c.Name, OrderId = c.OrderId, StatusTypeId = c.StatusTypeId
            })
                                .Cast <BasicDataRecordViewModel>()
                                .ToList();
            var serviceRecords = this.basicDataService.GetServices().ToList();
            var ticketTypes    = this.basicDataService.GetTicketTypes().ToList();

            TicketViewModel model = this.Convert(part.Record, serviceRecords, priorities, statusRecords, ticketTypes);

            // Fill Priorities
            Converter.Fill(model.Priorities, model.PriorityId, priorities);

            // Fill ticketTypes
            Converter.Fill(model.Types, model.TypeId, ticketTypes);

            // Fill Status Records
            Converter.Fill(model.StatusItems, model.StatusId, statusRecords);

            // Fill Service Records
            Converter.Fill(model.Services, model.ServiceId, serviceRecords);

            model.CurrentUserCanEditItem         = this.contentOwnershipService.CurrentUserCanEditContent(part.ContentItem);
            model.CurrentUserIsCustomer          = this.contentOwnershipService.IsCurrentUserCustomer();
            model.CurrentUserCanChangePermission = this.contentOwnershipService.CurrentUserCanChangePermission(part.ContentItem);

            switch (displayType)
            {
            case "GanttChart":
                this.FillStatusTimes(model, part, statusRecords.Cast <StatusRecordViewModel>());
                return(ContentShape("Parts_Ticket_GanttChart",
                                    () => shapeHelper.Parts_Ticket_GanttChart(
                                        Model: model)));

            case "TableRow":
                return(ContentShape("Parts_Ticket_TableRow",
                                    () => shapeHelper.Parts_Ticket_TableRow(
                                        Model: model)));

            case "SummaryAdmin":
                return(ContentShape("Parts_Ticket_SummaryAdmin",
                                    () => shapeHelper.Parts_Ticket_SummaryAdmin(
                                        Model: model)));

            case "Summary":
                return(ContentShape("Parts_Ticket_Summary",
                                    () => shapeHelper.Parts_Ticket_Summary(
                                        Model: model)));

            case "Pinboard":
                return(ContentShape("Parts_Ticket_Pinboard",
                                    () => shapeHelper.Parts_Ticket_Pinboard(
                                        Model: model)));

            case "TitleOnly":
                return(ContentShape("Parts_Ticket_TitleOnly",
                                    () => shapeHelper.Parts_Ticket_TitleOnly(
                                        Model: model)));

            default:

                // Sub tickets. Customer users can not see the sub-tickets
                if (!this.contentOwnershipService.IsCurrentUserCustomer())
                {
                    foreach (var subTicket in part.Record.SubTickets)
                    {
                        model.SubTickets.Add(this.Convert(subTicket, serviceRecords, priorities, statusRecords, ticketTypes));
                    }
                }

                // get requesting user
                if (part.Record.RequestingUser != null)
                {
                    var userContentItem = this.orchardServices.ContentManager.Get(part.Record.RequestingUser.Id);
                    var userPart        = userContentItem.As <UserPart>();

                    model.RequestingUserFullName = CRMHelper.GetFullNameOfUser(userPart);
                    model.RequestingUserEmail    = userPart.Email;
                    model.RequestingUsername     = userPart.UserName;
                }

                List <DriverResult> shapes = new List <DriverResult>();
                shapes.Add(ContentShape("Parts_Ticket", () => shapeHelper.Parts_Ticket(Model: model)));

                shapes.Add(ContentShape("Parts_Ticket_HeaderTitle", () => shapeHelper.Parts_Ticket_HeaderTitle(
                                            Model: model,
                                            Title: model.Title,
                                            TicketId: model.ContentItemId,
                                            TicketNumber: model.TicketNumber,
                                            ParentTicketNumber: model.ParentTicketNumber,
                                            ParentTitle: model.ParentTicketTitle,
                                            ParentTicketId: model.ParentTicketId)));

                if (part.Record.RelatedContentItem != null)
                {
                    shapes.Add(this.RenderRelatedContentItem(part, shapeHelper, "Parts_Ticket_RelatedContentItem"));
                }

                shapes.Add(this.ContentShape("Parts_Ticket_Properties", () => shapeHelper.Parts_Ticket_Properties(Model: model)));
                shapes.Add(this.ContentShape("Parts_Ticket_SubTickets", () => shapeHelper.Parts_Ticket_SubTickets(Model: model)));
                shapes.Add(this.ContentShape("Parts_Ticket_Dates", () => shapeHelper.Parts_Ticket_Dates(Model: model)));
                shapes.Add(this.ContentShape("Parts_Ticket_People", () => shapeHelper.Parts_Ticket_People(Model: model)));

                return(Combined(shapes.ToArray()));
            }
        }
Beispiel #12
0
        public ActionResult Delete(int id)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
            {
                return(new HttpUnauthorizedResult());
            }

            var user = Services.ContentManager.Get <IUser>(id);

            if (user != null)
            {
                var shellSettings = this.Services.WorkContext.Resolve <ShellSettings>();
                var siteSettings  = _siteService.GetSiteSettings();
                if (!string.IsNullOrEmpty(shellSettings.RequestUrlPrefix) && string.Equals(user.UserName, siteSettings.SuperUser, StringComparison.Ordinal))
                {
                    throw new OrchardSecurityException(T("You don't have permission to moderate the user"));
                }

                if (String.Equals(Services.WorkContext.CurrentSite.SuperUser, user.UserName, StringComparison.Ordinal))
                {
                    Services.Notifier.Error(T("The Super user can't be removed. Please disable this account or specify another Super user account."));
                }
                else if (String.Equals(Services.WorkContext.CurrentUser.UserName, user.UserName, StringComparison.Ordinal))
                {
                    Services.Notifier.Error(T("You can't remove your own account. Please log in with another account."));
                }
                else
                {
                    Services.ContentManager.Remove(user.ContentItem);
                    string changeDescription = string.Format(CultureInfo.CurrentUICulture, "Delete the user '{0}'", CRMHelper.GetFullNameOfUser(user));
                    this.activityStreamService.WriteChangesToStreamActivity(Services.WorkContext.CurrentUser.Id, user.Id, user.ContentItem.VersionRecord.Id, new ActivityStreamChangeItem[] { }, changeDescription, null);
                }
            }

            string actionName = this.crmContentOwnershipService.IsOperator(user.Id) ? "Operators" : "Customers";

            return(RedirectToAction(actionName, new { Controller = "User", area = "Orchard.CRM.Project" }));
        }
Beispiel #13
0
        public ActionResult EditPOST(int id)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
            {
                return(new HttpUnauthorizedResult());
            }

            var    user         = Services.ContentManager.Get <UserPart>(id, VersionOptions.DraftRequired);
            string previousName = user.UserName;

            var shellSettings = this.Services.WorkContext.Resolve <ShellSettings>();
            var siteSettings  = _siteService.GetSiteSettings();

            if (!string.IsNullOrEmpty(shellSettings.RequestUrlPrefix) && string.Equals(user.UserName, siteSettings.SuperUser, StringComparison.Ordinal))
            {
                throw new OrchardSecurityException(T("You don't have permission to moderate the user"));
            }

            var model = Services.ContentManager.UpdateEditor(user, this);

            var editModel = new UserEditViewModel {
                User = user
            };

            if (TryUpdateModel(editModel))
            {
                if (!_userService.VerifyUserUnicity(id, editModel.UserName, editModel.Email))
                {
                    AddModelError("NotUniqueUserName", T("User with that username and/or email already exists."));
                }
                else if (!Regex.IsMatch(editModel.Email ?? "", UserPart.EmailPattern, RegexOptions.IgnoreCase))
                {
                    // http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
                    ModelState.AddModelError("Email", T("You must specify a valid email address."));
                }
                else
                {
                    // also update the Super user if this is the renamed account
                    if (String.Equals(Services.WorkContext.CurrentSite.SuperUser, previousName, StringComparison.Ordinal))
                    {
                        _siteService.GetSiteSettings().As <SiteSettingsPart>().SuperUser = editModel.UserName;
                    }

                    user.NormalizedUserName = editModel.UserName.ToLowerInvariant();
                }
            }

            if (!ModelState.IsValid)
            {
                Services.TransactionManager.Cancel();

                var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Edit", Model: editModel, Prefix: null);
                editor.Metadata.Position = "2";
                model.Content.Add(editor);

                return(View(model));
            }

            Services.ContentManager.Publish(user.ContentItem);

            RouteValueDictionary activityStreamRouteValues = new RouteValueDictionary();

            activityStreamRouteValues.Add("action", "Display");
            activityStreamRouteValues.Add("controller", "User");
            activityStreamRouteValues.Add("area", "orchard.crm.Project");
            activityStreamRouteValues.Add("userId", user.Id);

            string changeDescription = string.Format(CultureInfo.CurrentUICulture, "Update user '{0}'", CRMHelper.GetFullNameOfUser(user));

            this.activityStreamService.WriteChangesToStreamActivity(Services.WorkContext.CurrentUser.Id, user.Id, user.ContentItem.VersionRecord.Id, new ActivityStreamChangeItem[] { }, changeDescription, activityStreamRouteValues);

            return(RedirectToAction("Display", new { Controller = "User", area = "Orchard.CRM.Project", userId = user.Id }));
        }
Beispiel #14
0
        public ActionResult CreatePOST(UserCreateViewModel createModel)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
            {
                return(new HttpUnauthorizedResult());
            }

            if (!string.IsNullOrEmpty(createModel.UserName))
            {
                if (!_userService.VerifyUserUnicity(createModel.UserName, createModel.Email))
                {
                    AddModelError("NotUniqueUserName", T("User with that username and/or email already exists."));
                }
            }

            if (!Regex.IsMatch(createModel.Email ?? "", UserPart.EmailPattern, RegexOptions.IgnoreCase))
            {
                // http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
                ModelState.AddModelError("Email", T("You must specify a valid email address."));
            }

            if (createModel.Password != createModel.ConfirmPassword)
            {
                AddModelError("ConfirmPassword", T("Password confirmation must match"));
            }

            var user = Services.ContentManager.New <IUser>("User");

            if (ModelState.IsValid)
            {
                user = _membershipService.CreateUser(new CreateUserParams(
                                                         createModel.UserName,
                                                         createModel.Password,
                                                         createModel.Email,
                                                         null, null, true));
            }

            var model = Services.ContentManager.UpdateEditor(user, this);

            if (!ModelState.IsValid)
            {
                Services.TransactionManager.Cancel();

                var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Create", Model: createModel, Prefix: null);
                editor.Metadata.Position = "2";
                model.Content.Add(editor);

                return(View(model));
            }

            RouteValueDictionary activityStreamRouteValues = new RouteValueDictionary();

            activityStreamRouteValues.Add("action", "Display");
            activityStreamRouteValues.Add("controller", "User");
            activityStreamRouteValues.Add("area", "orchard.crm.Project");
            activityStreamRouteValues.Add("userId", user.Id);

            string changeDescription = string.Format(CultureInfo.CurrentUICulture, "Creates new user '{0}'", CRMHelper.GetFullNameOfUser(user));

            this.activityStreamService.WriteChangesToStreamActivity(Services.WorkContext.CurrentUser.Id, user.Id, user.ContentItem.VersionRecord.Id, new ActivityStreamChangeItem[] { }, changeDescription, activityStreamRouteValues);

            string actionName = this.crmContentOwnershipService.IsOperator(user.Id) ? "Operators" : "Customers";

            return(RedirectToAction(actionName, new { Controller = "User", area = "Orchard.CRM.Project" }));
        }