logo
down
shadow

How to create a class name with current users roles?


How to create a class name with current users roles?

Content Index :

How to create a class name with current users roles?
Tag : css , By : Heals1ic
Date : January 11 2021, 05:14 PM

To fix this issue My site have 15 users roles. How to create a class name with current users roles ? , Try this code..
    if(is_user_logged_in()){
        $user_id = get_current_user_id();
      $user = new WP_User( $user_id );

      if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
          foreach ( $user->roles as $role )
              $user_role = $role;
      }
    }
    else{
        $user_role = "your default class";
    }
<span class="<?php echo $user_role; ?>" </span>

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Administer asp.net website (create new users, assign users to roles, etc.) from a windows app


Tag : chash , By : Ryan Adriano
Date : March 29 2020, 07:55 AM
around this issue I've come up with a solution, based on the other answers (who both got +1), and some other sites out there.
First, I created Application Config file (app.config). It mirrors exactly what is found in web.config from the web app, with the exception of how the connection string was handled:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <section name="connectionStrings" type="System.Configuration.ConnectionStringsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" requirePermission="false" />
  </configSections>

  <connectionStrings>
    <add name="MyConnectionString"
         connectionString ="SERVER=abc;UID=def;PWD=hij;Initial Catalog=klm;MultipleActiveResultsets=True"/>
  </connectionStrings>

  <system.web>

    <membership defaultProvider="MySqlMembershipProvider">
      <providers>
        <add name="MySqlMembershipProvider"
             type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
             connectionStringName="MyConnectionString"
             enablePasswordRetrieval="false"
             enablePasswordReset="true"
             requiresQuestionAndAnswer="true"
             applicationName="/MyWebApp"
             requiresUniqueEmail="true"
             passwordFormat="Encrypted"
             maxInvalidPasswordAttempts="5"
             minRequiredPasswordLength="7"
             minRequiredNonalphanumericCharacters="1"
             passwordAttemptWindow="10"
             passwordStrengthRegularExpression=""/>
      </providers>
    </membership>

    <roleManager enabled="true" defaultProvider="MySqlRoleManager">
      <providers>
        <add name="MySqlRoleManager"
             type="System.Web.Security.SqlRoleProvider"
             connectionStringName="MyConnectionString"
             applicationName="/MyWebApp" />
      </providers>
    </roleManager>

    <machineKey
      validationKey="BC50A82A6AF6A015C34C7946D29B817C00F04D2AB10BC2128D1E2433D0E365E426E57337CECAE9A0681A2C736B9779B42F75D60F09F142C60E9E0E8F9840DB46"
      decryptionKey="122035576C5476DCD8F3611954C837CDA5FE33BCDBBF23F7"
      validation="SHA1"
      decryption="AES"/>
  </system.web>

</configuration>
using System.Configuration;
using System.Reflection;
using System.Web.Security;

namespace WebAdminViaWindows
{
    internal static class Provider
    {
        private static readonly string assemblyFilePath = Assembly.GetExecutingAssembly().Location;

        static Provider()
        {
            Membership = CreateMembershipProvider();
            Role = CreateRoleProvider();
        }

        public static MembershipProvider Membership { get; private set; }
        public static RoleProvider Role { get; private set; }

        private static MembershipProvider CreateMembershipProvider()
        {
            var config = ConfigurationManager.OpenExeConfiguration(assemblyFilePath);

            var systemWebGroup = config.SectionGroups["system.web"];
            if (systemWebGroup == null)
            {
                throw new ConfigurationErrorsException("system.web group not found in configuration");
            }

            var membershipSection = systemWebGroup.Sections["membership"];
            if (membershipSection == null)
            {
                throw new ConfigurationErrorsException("membership section not found in system.web group");
            }

            var defaultProviderProperty = membershipSection.ElementInformation.Properties["defaultProvider"];
            if (defaultProviderProperty == null)
            {
                throw new ConfigurationErrorsException("defaultProvider property not found in membership section");
            }

            var defaultProviderName = defaultProviderProperty.Value as string;
            if (defaultProviderName == null)
            {
                throw new ConfigurationErrorsException("defaultProvider property is not a string value");
            }

            var providersProperty = membershipSection.ElementInformation.Properties["providers"];
            if (providersProperty == null)
            {
                throw new ConfigurationErrorsException("providers property not found in membership section");
            }

            var providerCollection = providersProperty.Value as ProviderSettingsCollection;
            if (providerCollection == null)
            {
                throw new ConfigurationErrorsException("providers property is not an instance of ProviderSettingsCollection");
            }

            ProviderSettings membershipProviderSettings = null;

            foreach (ProviderSettings providerSetting in providerCollection)
            {
                if (providerSetting.Name == defaultProviderName)
                {
                    membershipProviderSettings = providerSetting;
                }
            }

            if (membershipProviderSettings == null)
            {
                if (providerCollection.Count > 0)
                {
                    membershipProviderSettings = providerCollection[0];
                }
                else
                {
                    throw new ConfigurationErrorsException("No providers found in configuration");
                }
            }

            var provider = new SqlMembershipProvider();
            provider.Initialize("MySqlMembershipProvider", membershipProviderSettings.Parameters);
            return provider;
        }

        private static RoleProvider CreateRoleProvider()
        {
            var config = ConfigurationManager.OpenExeConfiguration(assemblyFilePath);

            var systemWebGroup = config.SectionGroups["system.web"];
            if (systemWebGroup == null)
            {
                throw new ConfigurationErrorsException("system.web group not found in configuration");
            }

            var roleManagerSection = systemWebGroup.Sections["roleManager"];
            if (roleManagerSection == null)
            {
                throw new ConfigurationErrorsException("roleManager section not found in system.web group");
            }

            var defaultProviderProperty = roleManagerSection.ElementInformation.Properties["defaultProvider"];
            if (defaultProviderProperty == null)
            {
                throw new ConfigurationErrorsException("defaultProvider property not found in roleManager section");
            }

            var defaultProviderName = defaultProviderProperty.Value as string;
            if (defaultProviderName == null)
            {
                throw new ConfigurationErrorsException("defaultProvider property is not a string value");
            }

            var providersProperty = roleManagerSection.ElementInformation.Properties["providers"];
            if (providersProperty == null)
            {
                throw new ConfigurationErrorsException("providers property not found in roleManagerSection section");
            }

            var providerCollection = providersProperty.Value as ProviderSettingsCollection;
            if (providerCollection == null)
            {
                throw new ConfigurationErrorsException("providers property is not an instance of ProviderSettingsCollection");
            }

            ProviderSettings roleProviderSettings = null;

            foreach (ProviderSettings providerSetting in providerCollection)
            {
                if (providerSetting.Name == defaultProviderName)
                {
                    roleProviderSettings = providerSetting;
                }
            }

            if (roleProviderSettings == null)
            {
                if (providerCollection.Count > 0)
                {
                    roleProviderSettings = providerCollection[0];
                }
                else
                {
                    throw new ConfigurationErrorsException("No providers found in configuration");
                }
            }

            var provider = new SqlRoleProvider();
            provider.Initialize("MySqlRoleManager", roleProviderSettings.Parameters);
            return provider;
        }
    }
}
int total;
foreach (MembershipUser user in Provider.Membership.GetAllUsers(0, 10, out total))
{
    var sb = new StringBuilder();
    sb.AppendLine(user.UserName);
    foreach (var role in Provider.Role.GetRolesForUser(user.UserName))
    {
        sb.AppendLine("\t" + role);
    }

    Console.WriteLine(sb.ToString());
}

Get all roles under current users role


Tag : development , By : Jenuel
Date : March 29 2020, 07:55 AM
this will help Unfortunately, there does not appear to be a pre-built way to do this. However, you should be able to write code to do it recursively like so:
public static set<Id> getSubordinateRoles(Id roleId) {
    map<Id, set<Id>> parentAndChildren = new map<Id, set<Id>>();
    set<Id> children;
    for(UserRole ur : [select Id, ParentRoleId from UserRole]) {
        children = parentAndChildren.containsKey(ur.ParentRoleId) ? parentAndChildren.get(ur.ParentRoleId) : new set<Id>();
        children.add(ur.Id);
        parentAndChildren.put(ur.ParentRoleId, children);
    }
    return getSubordinateRoles(role, parentAndChildren);
}

public static set<Id> getSubordinateRoles(Id roleId, map<Id, set<Id>> parentAndChildren) {
    set<Id> subordinateRoles = new set<Id>();
    set<Id> remainingSubordinateRoles = new set<Id>();
    if(parentAndChildren.containsKey(roleId)) {
        subordinateRoles.addAll(parentAndChildren.get(roleId));
        for(Id subRoleId : subordinateRoles) {
            remainingSubordinateRoles.addAll(getSubordinateRoles(subRoleId, parentAndChildren));
        }
    }
    subordinateRoles.addAll(remainingSubordinateRoles);
    return subordinateRoles;
}

Create login with groups (with roles) and users with revoke roles - Symfony2


Tag : authentication , By : user187383
Date : March 29 2020, 07:55 AM
this one helps. is_granted() calls the user's getRoles() method and checks wether the given argument role is inside the returned array of roles. ( simplified - the security provider calls getRoles and adds them to the security-context then is_granted checks the security-context to be more precise )
Now if you want to return the roles inherited from the user's groups you will have to merge those.
public function getRoles()
{
    $groupRoles = array();
    // add all roles provided by groups
    foreach ($this->getGroups() as $group) {
        foreach ($group->getRoles() as $role) {
            $groupRoles[] = $role;
        }
    }
    // - remove dublicates
    // - revoke user's roles
    // - return remaining roles
    return array_unique(array_diff($groupRoles, $this->getRoles()));
}

How to create roles and add users to roles in ASP.NET MVC Web API


Tag : asp.net-web-api , By : AJacques
Date : March 29 2020, 07:55 AM
it fixes the issue I have a .NET Web API project that users the individual accounts. I can register users fine using the standard template AccountController. However, I now want to set up roles and add users to roles depending on the type of user. , You can add roles using the RoleManager...
using (var context = new ApplicationDbContext())
{
    var roleStore = new RoleStore<IdentityRole>(context);
    var roleManager = new RoleManager<IdentityRole>(roleStore);

    await roleManager.CreateAsync(new IdentityRole { Name = "Administrator" });

    var userStore = new UserStore<ApplicationUser>(context);
    var userManager = new UserManager<ApplicationUser>(userStore);

    var user = new ApplicationUser { UserName = "admin" };
    await userManager.CreateAsync(user);
    await userManager.AddToRoleAsync(user.Id, "Administrator");
}

.net MVC add roles and add users and add roles to users + make part of a view only visible for a role


Tag : .net , By : Blight
Date : March 29 2020, 07:55 AM
I wish this help you MVC5 project template doesn't have role manager by default, so we start by creating our role manager classes; (in order to keep the project well structured it is better to add the classes as mentioned below):
1- create ApplicationRole class (add to IdentityModels.cs under Models folder)
public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }

    public ApplicationRole(string name) : base(name) { }
}
public class ApplicationRoleManager : RoleManager<ApplicationRole>, IDisposable
{
    public ApplicationRoleManager(RoleStore<ApplicationRole> store) : base(store) { }

    public static ApplicationRoleManager Create(
        IdentityFactoryOptions<ApplicationRoleManager> options,
        IOwinContext context)
    {
        return new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
    }
}
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
    namespace UsersAndRoles.Controllers
{
using Microsoft.AspNet.Identity.Owin;
using System.Web;
using System.Web.Mvc;

    public class UsersAndRolesController : Controller
    {
        private ApplicationUserManager _userManager;
        private ApplicationRoleManager _roleManager;

        public UsersAndRolesController() { }

        public UsersAndRolesController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
        {
            UserManager = userManager;
            RoleManager = roleManager;
        }

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        public ApplicationRoleManager RoleManager
        {
            get
            {
                return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
            }
            private set
            {
                _roleManager = value;
            }
        }

        // GET: UsersAndRoles
        public ActionResult Index()
        {
            return View();
        }
    }
}
var user = new ApplicationUser
        {
            UserName = "Ziyad",
            Email = "email@domainname.com"
        };

        var password = "P@ssw0rd";
        UserManager.Create(user, password);
var role = new ApplicationRole
        {
            Name = "Students"
        };

        RoleManager.Create(role);
UserManager.AddToRole("user_id", "role_name");
    namespace UsersAndRoles.Controllers
{
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.Owin;
    using System.Web;
    using System.Web.Mvc;
    using Models;
public class UsersAndRolesController : Controller
{
    private ApplicationUserManager _userManager;
    private ApplicationRoleManager _roleManager;

    public UsersAndRolesController() { }

    public UsersAndRolesController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
    {
        UserManager = userManager;
        RoleManager = roleManager;
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

    public string CreateUser()
    {
        var user = new ApplicationUser
        {
            UserName = "Ziyad",
            Email = "email@domainname.com"
        };

        var password = "P@ssw0rd";
        var result = UserManager.Create(user, password);

        if (result.Succeeded)
        {
            return "User created";
        }
        else
        {
            var msg = "Error, user not created";
            foreach (var err in result.Errors)
                msg += err + "<br />";

            return msg;
        }            
    }

    public string CreateRole()
    {
        var role = new ApplicationRole
        {
            Name = "Teachers"
        };

        var result = RoleManager.Create(role);

        if (result.Succeeded)
        {
            return "Role created";
        }
        else
        {
            var msg = "Error, role not created";
            foreach (var err in result.Errors)
                msg += err + "<br />";

            return msg;
        }
    }

    public string AddUserToRole()
    {
        var user = UserManager.FindByEmail("email@domainname.com");

        if (user != null)
        {
            var result = UserManager.AddToRole(user.Id, "Teachers");
            if (result.Succeeded)
            {
                return "User assigned to role";
            }
            else
            {
                var msg = "Error, user not assigned to role <br />";
                foreach (var err in result.Errors)
                    msg += err + "<br />";

                return msg;
            }
        }
        else
        {
            return "User not found!";
        }
    }
}
if (User.IsInRole("Teachers"))
        {
            // role specific options
        }
[Authorize(Roles = "Teachers")]
public ActionResult ActionName()
{
    //teachers specific method
}
Related Posts Related QUESTIONS :
  • CSS: placing absolute positioned element so that it touches its parent from outside
  • How to insert a background image over full page width with a Bootstrap grid?
  • How to make volume shadow css
  • How can I equalize the heights of text input fields?
  • Table cell doesn't obey vertical-align CSS declaration when it contains a floated element
  • CSS - How to prevent the browser from showing scrollbars when a div goes outside of the window?
  • How do I make the footer stretch vertically downward align to footer
  • Margically appearing margin in footer. Could use some fresh eyes on this
  • Overlapping 2 Flash objects and controlling z-index
  • element "iframe" undefined - Errors found while checking this document as XHTML 1.0 Strict!
  • Losing information when using BeautifulSoup
  • How to fit a two View components inside a View component with borderRadius?
  • Background - single diagonal stripe
  • Styling arrow in Select Box
  • How to make css where arrows overlap with eachother?
  • Pure CSS interactive human body
  • Font awesome background color is overflown
  • Transitioning opacity from 0 to .9 works with toggling visibility from hidden to visible, but not the other way around
  • Understanding relative position in css
  • How to hide a rectangle where horizontal and vertical scroll bars converge?
  • Where does filter:invert(1) go in shorthand background image css
  • How to evenly add borders around table?
  • How do I get this element in css
  • How to refactor common css rules in media queries?
  • Focus outline not displayed on a div with mask-image CSS rule in Firefox
  • Removing a redundant parent class in LESS?
  • Override CSS of component selector style from ng module
  • How do I move (center) an svg icon?
  • Styling a chamfer / scooped rectangle with a border
  • css animation to happen when on scroll, not when pages loads
  • How to make my flexbox elements divide the total height of the container?
  • CSS Only Pie Chart - How to add spacing/padding between slices?
  • Not able to style nested animations with keyframes with styled-components
  • How to inspect pseudo elements using Internet Explorer 11 developer tools
  • How to fit innerHtml into a p tag
  • How can i make border for active class nav-item in bootstrap 4?
  • Mixing Multiple conditions in a Single NgStyle Tag?
  • I need an element to be a child of other without inheriting certains properties
  • React - JSS have element fade in when rendered
  • Chrome's hidden CSS scroll-snap threshold and how to change it
  • Why can't I see my linear gradient over my background image?
  • Trying to hide a div using CSS
  • How to import css to only one component?
  • Best practices for styling an element that can be positioned anywhere in a page
  • should i use media queries for responsive design with react?
  • Color words ending with a digit?
  • Long Text inside Table Cell Overflow
  • Center text in column/vertically, CSS Grid
  • MDC-Web CSS theme colors not defined
  • css transform + width + left + top transition jump on safari browser
  • How to correctly position vertical oriented text on a div?
  • Why does position: sticky; not work in react?
  • Is there a way to snake/queue the flow of items in a CSS Grid?
  • two screen widths: 375px and 1024px
  • React native - Highlight a TextInput if it's empty on form submit
  • How to get the css property of a tags in testcafe?
  • Cropping the top 10% of an image using CSS?
  • how to keep a footer at the bottom of the page, even if the content grows?
  • Firefox: How to test prefers-color-scheme?
  • Is there anyway to remove the shadow, or force vuetify menu to fully align with the left side of the screen?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com