How to assign default role(s) to new user in Orchard

Tags: orchard, user, roles, english

This is a commonly asked question. Orchard, by default, assigns no explicit roles to the newly created userSmutek.

Every authenticated user has the Authenticated role, which is attached to the user object at runtime (it’s hardcoded, so you won’t find the user role in DB). Although adding necessary permissions to this role can suit most needs, sometimes you may need to explicitly add some other roles, possibly different, based on some set of rules, etc. In other words – sometimes there is some custom logic involved, which makes the default behavior unsuitable.

In such case the admin action is needed after user creation… It’s not the preferred option, though, especially when you have lots of usersIrytacja. The best way would be to do this automatically, so the user gets assigned one (or more) defined roles after registration. How to do that?

This can be achieved in two ways:

  1. By implementing the IUserEventHandler interface (from Orchard.Users.Events) and handling the role-adding logic in Created method
  2. By hooking to OnCreated<UserPart>() event in one of your ContentHandlers, and handling the role-adding logic inside.

Assigning the role to the user is a bit tricky, as there is no such thing as RolePart, which you can easily query for. Also, there is neither any collection property on User object which you could add your role to, nor any method for assigning roles in IAuthorizationServiceIrytacja

Assigning role via IUserEventHandler

In this example we’re assigning the Administrator role to created user (not necessarily the best option thoughPuszczam oczko):

public class DefaultRolesHandler : IUserEventHandler {
    private readonly IRepository<UserRolesPartRecord> _userRolesRepository;
    private readonly IRoleService _roleService;
    private readonly IOrchardServices _services;

    public DefaultRolesHandler(
        IRepository<UserRolesPartRecord> userRolesRepository,
        IRoleService roleService,
        IOrchardServices services)
    {
        _userRolesRepository = userRolesRepository;
        _roleService = roleService;
        _services = services;
    }

    #region Implementation of IUserEventHandler

    /// <summary> /// Called before a User is created /// </summary> public void Creating(UserContext context)
    {
    }

    /// <summary> /// Called once a user has been created /// </summary> public void Created(UserContext context)
    {
        var role = _roleService.GetRoleByName("Administrator");
        if (role != null)
        {
            _userRolesRepository.Create(
                new UserRolesPartRecord {
                    UserId = context.User.As<IUser>().Id,
                    Role = role
                });
        }
    }
    #endregion }

As shown above, we have to use the repository of UserRolePartRecord directly to create an appropriate User-Role relation record.

IRoleService is a wrapper around the Role repository for CRUD operations on roles. It comes with some useful methods (e.g.. GetRoleByName for fetching roles by name, used above).

We’re done!UĊ›miech Now, if a user account gets created in our Orchard app, it will be assigned the Administrator role instantly.

Assigning role via ContentHandler’s OnCreated method

For the sake of brevity, I’ll omit the code for achieving this, as it’s almost identical to shown above.

The only difference is, that we place the code for attaching the role inside OnCreated<UserPart>((ctx, part) => { <code_goes_here> }) method in one of your content handlers instead of the Created method of IUserEventHandler.

Hope you found this useful!

Cheers!

2 Comments

  • pszmyd said

    IUserEventHandler can be also used to do some other setup stuff on user creation, so I encourage you to check it out yourself, hands-on!