请注意,本站并不支持低于IE8的浏览器,为了获得最佳效果,请下载最新的浏览器,推荐下载 Chrome浏览器
欢迎光临。交流群:166852192

如何向您的Orchard CMS安装程序添加自定义用户类型


Oftentimes, basic web development requirements include custom user profile logic and information to be stored, along with basic user functionality. Yet, registration and configuration of users who access your website do not directly match up with the core Orchard user functionality; as a web development agency, we’ve learned to extend it. In this blog post, we’ll show you how to add custom user types to your Orchard CMS setup.
Orchard CMS is great because the core includes user registration methods, user moderation functionality, and security around these functions as well. Orchard comes with the Orchard.Users module and the Orchard.Roles module as well. These are great extension points for the development of any new website requiring a bit more flexibility.

通常,基本的web开发需求包括自定义用户配置文件逻辑和要存储的信息,以及基本用户功能。 然而,访问您的网站的用户的注册和配置不直接与核心的Orchard用户功能匹配; 作为一个Web开发代理,我们已经学会了扩展它。 在本博文中,我们将向您展示如何向您的Orchard CMS设置添加自定义用户类型。


Orchard CMS是伟大的,因为核心包括用户注册方法,用户审核功能,以及这些功能的安全。 Orchard自带了Orchard.Users模块和Orchard.Roles模块。 这些都是开发任何需要更多灵活性的新网站的重要延伸点。

The Broker User Type

Assigning a new user type will require you to create a custom module. This will allow you to respond to actions for Brokers and build out your new content part. 
代理用户类型
分配新用户类型将需要您创建自定义模块。 这将允许您响应Brokers的操作并构建您的新内容部分。

1. Adding the User Part to Your Broker Content Part

After creating your new module, you will need to begin laying out scaffolding in the Migration.cs in order to wire things up. The migrations run on module install and are needed for updates to them. Add the following code to the Migrations.cs file:
1.将用户部件添加到您的代理内容部件
创建新模块后,您需要在Migration.cs中开始布置脚手架,以便连接。 迁移在模块安装上运行,并且需要对其进行更新。 将以下代码添加到Migrations.cs文件:
public int Create()
        {
SchemaBuilder.CreateTable("BrokerPartRecord",
                table => table
                    .ContentPartRecord()
                    .Column<string>("FullName", w => w.WithLength(150))
                    .Column<string>("CurrentLicenseNumber", w => w.WithLength(100))
                    .Column<string>("PhoneNumber", w => w.WithLength(100))
                );
            ContentDefinitionManager.AlterPartDefinition("BrokerPart", part => part
               .Attachable(false)
               );
            ContentDefinitionManager
                .AlterTypeDefinition("Broker",
                cfg => cfg.Creatable(false)
                .WithPart("UserPart")
.WithPart("UserRolesPart")
                .WithPart("BrokerPart"));
_roleService.CreateRole("Broker");
_roleService.CreatePermissionForRole("Broker", Permissions.Broker.Name);
}
So what is all this doing? First, we are creating our new content part record for storage. Creating this record allows us to persist Broker information to the database and give it the characteristics of a content item. Next, we declare our new content item as a part that is not attachable via the UI. This restricts people from attaching it to other content items. Next, we create a new content item called "Broker," which is not able to be created via the UI and has the three content parts web development teams require for functionality. The UserPart gives us all the functionality and storage required for any user in the site. Secondly, the UserRolesPart gives us the ability to assign/retrieve roles associated with this user. Lastly, we assign our new BrokerPart so we can store information required for our users.
The last two lines of this code block create a role in the system for our new user of Broker and assign permissions to it. We do this by injecting a dependency into the Migrations class (IRoleService roleService). This will give you access to the functionality you need from the RoleService. You can learn about how to create a Permissions.cs file in the module here: http://docs.orchardproject.net/Documentation/custom-permissions. You don't need to create permissions or a separate role, but it will be nice to distinguish these users versus other users in the system. Especially if you intend to expand the user base types.

那么这是做什么的?首先,我们正在创建我们的新内容部分记录进行存储。创建此记录允许我们将Broker信息保存到数据库,并为其提供内容项的特性。接下来,我们将我们的新内容项声明为不能通过UI附加的部分。这限制了人们将其附加到其他内容项。接下来,我们创建一个名为“Broker”的新内容项,它不能通过UI创建,并且Web开发团队需要三个内容部分来实现功能。 UserPart提供了网站中任何用户所需的所有功能和存储。其次,UserRolesPart使我们能够分配/检索与此用户关联的角色。最后,我们分配新的BrokerPart,这样我们可以存储用户所需的信息。


此代码块的最后两行在系统中为我们的新Broker用户创建角色,并为其分配权限。我们通过向Migrations类(IRoleService roleService)注入一个依赖关系来实现。这将使您可以从RoleService访问所需的功能。您可以在此处的模块中了解如何创建Permissions.cs文件:http://docs.orchardproject.net/Documentation/custom-permissions。您不需要创建权限或单独的角色,但很容易区分这些用户与系统中的其他用户。特别是如果你打算扩展用户库类型。



2. Configuring a Custom Registration For Your Brokers

Now that we have our new broker content type created, we want new brokers to be able to sign-up via the website. We created our own registration page that directs to a custom controller in our module to process the registration. We did this for flexibility. We could have just processed the Editor templates of our BrokerPart as normal, but we wanted to takeover the process of registering a user on the site completely. We mainly ported much of the code from the Orchard.Users AccountController.cs in order to do this and then added our own custom code as well. Having a custom page with a custom controller is just easier, in my opinion, than overriding all the specific Broker templates in the theme and adding any other custom hooks for backend processing we wanted to add. (We had a bunch of other things needing to be processed.)
If you look at some of our code for the Register Action on the ProfileController in our module, you will see the general idea of what we are doing. 
2.为您的经纪人配置自定义注册
现在我们已经创建了新的代理内容类型,我们希望新的代理能够通过网站注册。我们创建了自己的注册页面,指向我们模块中的自定义控制器来处理注册。我们这样做是为了灵活性。我们可以正常处理BrokerPart的编辑器模板,但我们想要接管在网站上完全注册用户的过程。我们主要移植了很多来自Orchard.Users AccountController.cs的代码,为了做到这一点,然后添加了我们自己的自定义代码。拥有一个自定义页面与自定义控制器更容易,在我看来,覆盖主题中的所有特定的Broker模板,并添加任何其他自定义钩子用于后端处理我们想添加。 (我们有一大堆其他需要处理的东西。)


如果你看看我们的模块中的ProfileController的Register Action的一些代码,你会看到我们正在做什么的一般想法。
public ActionResult RegisterBroker(BrokerViewModel viewModel) {
//code omitted here
if (ValidateRegistration(viewModel.UserName, viewModel.Email, viewModel.Password, viewModel.ConfirmPassword))
            {
                var broker = _brokerService.CreateBroker(viewModel);
                return ChallengeRegistration(broker, viewModel.ReturnUrl);
            }
//code omitted here
}
We are validating the user information just like in the Orchard.Users module but then running some custom code in our service layer to create our Broker. Lastly, we return the Email Address Challenge to the user. This code is very similar to the code in the Register method inside Orchard.Users as well. Let's look at the code to create a broker:
我们正在验证用户信息就像在Orchard.Users模块,但然后在我们的服务层运行一些自定义代码来创建我们的代理。 最后,我们向用户返回电子邮件地址验证。 此代码与Orchard.Users中的Register方法中的代码非常相似。 让我们看看创建代理的代码:
public UserPart CreateBroker(BrokerViewModel viewModel)
        {
            var broker = _orchardServices.ContentManager.New("Broker");
            var brokerPart = broker.As<BrokerPart>();
            brokerPart.CurrentLicenseNumber = viewModel.CurrentLicenseNumber;
            brokerPart.PhoneNumber = viewModel.PhoneNumber;
            brokerPart.FullName = viewModel.FullName;
            var userPart = broker.As<UserPart>();
            userPart.UserName = viewModel.UserName;
            userPart.Email = viewModel.Email;
            userPart.NormalizedUserName = viewModel.UserName.ToLowerInvariant();
            userPart.Record.HashAlgorithm = "SHA1";
            var registrationSettings = _orchardServices.WorkContext.CurrentSite.As<RegistrationSettingsPart>();
            if (registrationSettings != null)
            {
                userPart.RegistrationStatus = registrationSettings.UsersAreModerated ? UserStatus.Pending : UserStatus.Approved;
                userPart.EmailStatus = registrationSettings.UsersMustValidateEmail ? UserStatus.Pending : UserStatus.Approved;
            }
            userPart.Record.RegistrationStatus = UserStatus.Pending;
            userPart.Record.EmailStatus = UserStatus.Pending;
            _membershipService.SetPassword(userPart, viewModel.Password);
            _orchardServices.ContentManager.Create(broker);
   
            var role = _roleService.GetRoleByName("Broker");
            if (role != null)
            {
                _userRoleRepository.Create(new UserRolesPartRecord
                {
                    UserId = userPart.Id,
                    Role = role
                });
            }
}
So, this is the guts of the user creation process. We basically extract our values from our view model and set the UserPart and BrokerPart information. Lastly, we assign
the Broker role to the new Broker. This code shows some of the logic behind how Orchard manages content. As you can see, it is not as scary as you might think and is a pretty straightforward web development process. 
所以,这是用户创建过程的勇气。 我们基本上从我们的视图模型中提取我们的值,并设置UserPart和BrokerPart信息。 最后,我们分配
Broker角色到新的Broker。 这段代码显示了Orchard如何管理内容的一些逻辑。 正如你所看到的,它不像你想象的那么可怕,是一个非常简单的Web开发过程。

3. Allowing The Broker to View/Edit Information

Now that we have our Broker added to our system, how do we enable the user to manage their information? The same way we do it in MVC/Orchard in any other situation. By simply adding a controller with an action that will return the broker information when they arrive to the webpage. You can retrieve the currently logged-in broker's information like this:

3.允许代理查看/编辑信息
现在我们将我们的代理添加到我们的系统中,我们如何使用户管理他们的信息? 同样的方式,我们在任何其他情况下在MVC / Orchard。 通过简单地添加一个控制器,该控制器具有在到达网页时将返回代理信息的操作。 您可以检索当前登录的代理的信息,如下所示:
BrokerPart brokerPart = _orchardServices.WorkContext.CurrentUser.As<BrokerPart>();

4. Conclusion: More Flexibility & Functionality for Web Development Projects

The good news: it is relatively easy to add more flexibility and functionality to the core Orchard user system. This example is meant to lay out the various pieces required to do this. There are some items left out, but it should take some of the mystery out of it. You can extend the default Editor templates for the Broker so you can view and add this custom logic in the Admin dashboard as well by adding templates to \Editor Templates\Parts\Broker.cshtml. This will let administrators add and update Broker information as well. As you saw in step 3 above, we preferred to just let users modify their own broker information for now.

4.结论:更多的灵活性和功能的Web开发项目
好消息:向核心的Orchard用户系统添加更多的灵活性和功能相对容易。 这个例子是为了展示所需要的各种零件。 有一些项目遗漏了,但它应该采取一些神秘的出来。 您可以扩展Broker的默认编辑器模板,以便您可以在“管理”控制面板中查看和添加此自定义逻辑,并将模板添加到\ Editor Templates \ Parts \ Broker.cshtml。 这将允许管理员添加和更新Broker信息。 正如您在上面的步骤3中看到的,我们倾向于只让用户修改自己的代理信息。



I hope this sheds some light on ways to customize Orchard for your website! If you have any questions, just comment below or contact us for help with web development and design.

Other files you will want to add/update as well:

我希望这给了一些关于如何为您的网站自定义Orchard的方法! 如果您有任何问题,只需在下面评论或联系我们,以获得有关网络开发和设计的帮助。


您还将要添加/更新的其他文件:
1. Handlers/BrokerPartHandler.cs
public BrokerPartHandler(IRepository<BrokerPartRecord> repository)
        {
            Filters.Add(StorageFilter.For(repository));
        }
2. Drivers/BrokerPartDriver.cs
protected override DriverResult Editor(BrokerPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(part, Prefix, null, null);
            return Editor(part, shapeHelper);
        }

3. Models/BrokerPart.cs

public class BrokerPart : ContentPart<BrokerPartRecord> { 
public string PhoneNumber { 
get { return Retrieve(x => x.PhoneNumber); } 
set { Store(x => x.PhoneNumber, value); }
 } 
public string CurrentLicenseNumber { 
get { return Retrieve(x => x.CurrentLicenseNumber); }
 set { Store(x => x.CurrentLicenseNumber, value); } 

public string FullName { 
get { return Retrieve(x => x.FullName); } 
set { Store(x => x.FullName, value); }
 }
}

4. Models/BrokerPartRecord.cs

public class BrokerPartRecord : ContentPartRecord { 
public virtual string PhoneNumber { get; set; } 
public virtual string CurrentLicenseNumber { get; set; }
 public virtual string FullName { get; set; }
}

5. ViewModels/BrokerViewModel.cs
public class BrokerViewModel : UserViewModel {
[DisplayName("Current License Number")] 
[Required] 
public string CurrentLicenseNumber { get; set; } 
[DisplayName("Phone Number")] 
[Required] 
public string PhoneNumber { get; set; }
}
6. UserViewModels/UserViewModel.cs
    public class UserViewModel {
        [LocalizedDisplayName("Choose User Name")]
        [Required]
        public string UserName { get; set; }
        [Required]
        [LocalizedDisplayName("Email Address")]
        public string Email { get; set; }
        public string ReturnUrl { get; set; }
        [Required]
        [LocalizedDisplayName("Create a Password")]
        public string Password { get; set; }
        [Required]
        [LocalizedDisplayName("Confirm Password")]
        public string ConfirmPassword { get; set; }
        [Required]
        [LocalizedDisplayName("First Name / Last Name")]
        public string FullName { get; set; }
    }
7. Routes.cs
You will want to edit this as new routes are needed to provide functionality.
您将需要编辑它,因为需要新的路由来提供功能。
原文:https://www.cloudconstruct.com/blog/adding-custom-user-types-to-your-orchard-cms-setup 

作者原创内容不容易,如果觉得内容不错,请点击右侧“打赏”,赏俩给作者花花,也算是对作者付出的肯定,也可以鼓励作者原创更多更好内容。
更多详情欢迎到QQ群 166852192 交流。