Layer Rule for user Role?

Topics: General
Feb 18, 2011 at 5:58 PM

If I add roles to a user is there a way to use those roles in a Layer Rule?

i.e. instead of "authenticated", is there a way to say role(customer)?


Feb 18, 2011 at 9:06 PM

If you build your own rule, then yes.

Feb 23, 2011 at 4:06 AM

This appears to work ... but is it the right/best way to achieve this in Orchard?

    /// <summary>
    /// The Role Rule Provider adds a new Rule that can be applied to Layers on the Widgets page
    /// Using a rule like role('rolename') you can enable content to appear only for users having a specific role
    /// </summary>
    public class RoleRuleProvider : IRuleProvider
        private readonly IAuthenticationService _authenticationService;

        public RoleRuleProvider(IAuthenticationService authenticationService)
            _authenticationService = authenticationService;

        public void Process(RuleContext ruleContext)
            if (!String.Equals(ruleContext.FunctionName, "role", StringComparison.OrdinalIgnoreCase))

            var user = _authenticationService.GetAuthenticatedUser();

            // If not authenticated you have no role so you cannot satisfy any role(...) rule
            if (user == null)
                ruleContext.Result = false;

            var userRoles = user.As<UserRolesPart>().Roles;
            var ruleRoles = ruleContext.Arguments.Select(arg => Convert.ToString(arg));

            // If more than one role is specified (e.g. role(partner,customer) we treat that as an OR))
            // So we enable this content IF any ruleRole matches and userRole
            bool allowed = ruleRoles.Any(ruleRole => userRoles.Any(userRole => string.Equals(ruleRole, userRole, StringComparison.OrdinalIgnoreCase)));

            ruleContext.Result = allowed;

Feb 23, 2011 at 4:11 AM

It looks fine, yes.

Feb 23, 2012 at 3:12 PM

how do i use this piece of code?

where do i have to put this code??

Feb 23, 2012 at 9:08 PM