IsInRole() public method

IsInRole answers the question: does an identity this principal possesses contain a claim of type RoleClaimType where the value is '==' to the role.
Each Identity has its own definition of the ClaimType that represents a role.
public IsInRole ( string role ) : bool
role string The role to check for.
return bool
Example #1
0
        /// <summary>
        /// Filter list of users based on availability.
        /// </summary>
        /// <param name="users">Sequence of users.</param>
        /// <param name="principal">Principal which is used for accessing data.</param>
        /// <returns>Filter sequence with applied security rules.</returns>
        protected virtual IQueryable <TUser> FilterUsers(IQueryable <TUser> users, System.Security.Claims.ClaimsPrincipal principal)
        {
            if (principal == null)
            {
                throw new ArgumentNullException("principal");
            }

            if (users == null)
            {
                throw new ArgumentNullException("users");
            }

            if (principal.IsInRole(RoleNames.Administrator))
            {
                return(users);
            }

            if (principal.IsInRole(RoleNames.ClientAdministrator))
            {
                var clientId = principal.GetClient();
                users = users.Cast <DubUserWithClient>()
                        .Where(_ => _.ClientId == clientId)
                        .Cast <TUser>();
            }

            return(Enumerable.Empty <TUser>().AsQueryable());
        }
Example #2
0
        public async Task <IActionResult> Index()
        {
            DashboardViewModel _model = new DashboardViewModel();

            using RDATContext context = new RDATContext();
            List <TestingLog> activeLogs = context.TestingLogs.Where(tl => Convert.ToInt32(tl.Reported_Results) < 1).ToList();

            char[] goodResults = { '1', '2', '3' };

            // Get User Roles
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            bool IsAdmin    = currentUser.IsInRole("Admin");
            bool IsReadOnly = currentUser.IsInRole("ReadOnly");

            _model.BadgeTotalActiveDrivers     = context.Drivers.Where(d => d.TerminationDate == null && !d.isDelete).Count();
            _model.BadgeTotalActiveCompanies   = context.Companys.Where(c => c.Status == "1" && c.isDelete != true).Count(); // context.Companys.Where(d => ??).Count();
            _model.BadgeOutstandingDrugTest    = activeLogs.Where(tl => tl.Test_Type == "Drug").Count();
            _model.BadgeOutstandingAlcoholTest = activeLogs.Where(tl => tl.Test_Type == "Alcohol").Count();

            _model.FavoriteCompanies = context.Companys.Where(c => c.isFavorite).OrderByDescending(p => p.Id).ToList();

            _model.FavoriteDrivers = context.Drivers.Where(d => d.isFavorite).OrderByDescending(p => p.Id).ToList();



            return(View(_model));
        }
 public static IHtmlContent PartialWithRole(this IHtmlHelper helper, string partialName, object model, ClaimsPrincipal user, UserRoleEnum userRole)
 {
     if (user.IsInRole(userRole.ToString()))
     {
         return helper.Partial(partialName, model: model);
     }
     else
     {
         return helper.Raw(string.Empty);
     }
 }
        private Claim GetRole(ClaimsPrincipal incomingPrincipal)
        {
            var sid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

            if (incomingPrincipal.IsInRole(sid.Value))
            {
                return new Claim(ClaimTypes.Role, "Operator");
            }
            else
            {
                return new Claim(ClaimTypes.Role, "User");
            }
        }
        public async Task <IActionResult> PutMessageBoard(long id, MessageBoard messageBoard)
        {
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            bool IsModerator = currentUser.IsInRole("Moderator");

            // var currmsg = await _context.Messages.FindAsync(id);

            if (id != messageBoard.Id)
            {
                return(BadRequest());
            }


            //  if (messageBoard.flagged != currmsg.flagged && !IsModerator)
            if (messageBoard.Flagged == true && !IsModerator)
            {
                return(StatusCode(StatusCodes.Status203NonAuthoritative, new Response {
                    Status = "Error", Message = " Flag modification not allowed(Only Moderator can update flag)"
                }));
            }

            _context.Entry(messageBoard).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MessageBoardExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Ok(new Response {
                Status = "Success", Message = "Record Updated Successfully"
            }));
        }
        /// <summary>
        /// First string is expected, others are not.
        /// </summary>
        /// <param name="names"></param>
        /// <param name="roles"></param>
        private void CheckNamesAndRole(string[] names, string[] roles, ClaimsPrincipal principal, string expectedNameClaimType = ClaimsIdentity.DefaultNameClaimType, string expectedRoleClaimType = ClaimsIdentity.DefaultRoleClaimType)
        {
            ClaimsIdentity identity = principal.Identity as ClaimsIdentity;
            Assert.AreEqual(identity.NameClaimType, expectedNameClaimType);
            Assert.AreEqual(identity.RoleClaimType, expectedRoleClaimType);
            Assert.IsTrue(principal.IsInRole(roles[0]));
            for (int i = 1; i < roles.Length; i++)
            {
                Assert.IsFalse(principal.IsInRole(roles[i]));
            }

            Assert.AreEqual(identity.Name, names[0]);
            for (int i = 1; i < names.Length; i++)
            {
                Assert.AreNotEqual(identity.Name, names[i]);
            }
        }
 public static bool IsInRole(this System.Security.Claims.ClaimsPrincipal User, string Form, AuthType auth)
 {
     return(User.IsInRole(GetAuthCode(Form, auth)) || User.IsInRole(GetAuthCode(Form, AuthType.Full)) || User.IsInRole(GetAuthCode("Admin", AuthType.Full)));
 }
        /// <summary>
        /// First role is expected, others are not.
        /// </summary>
        /// <param name="names"></param>
        /// <param name="roles"></param>
        private void CheckForRoles(string[] expectedRoles, string[] unexpectedRoles, ClaimsPrincipal principal, string expectedRoleClaimType = ClaimsIdentity.DefaultRoleClaimType)
        {
            ClaimsIdentity identity = principal.Identity as ClaimsIdentity;
            Assert.AreEqual(identity.RoleClaimType, expectedRoleClaimType);
            for (int i = 1; i < expectedRoles.Length; i++)
            {
                Assert.IsTrue(principal.IsInRole(expectedRoles[i]));
            }

            for (int i = 1; i < unexpectedRoles.Length; i++)
            {
                Assert.IsFalse(principal.IsInRole(unexpectedRoles[i]));
            }
        }
 public static bool IsAdmin(this ClaimsPrincipal user)
 {
     return(user.IsInRole(KnownRoles.Admin));
 }
Example #10
0
 public List<VoteMatchViewModel> GetVoteMatchs(ClaimsPrincipal user)
 {
     return BddContext
         .Matchs
         .Where(m => (m.Equipe1.Contains("HORGUES ODOS") || m.Equipe2.Contains("HORGUES ODOS")) && (m.VoteStatut == 1 || m.VoteStatut == 2 || (user.IsInRole("Contributor") && m.VoteStatut == 0 && m.Date < DateTime.Now)))
         .Select(x => new VoteMatchViewModel() { MatchId = x.Id, Date = x.Date, Equipe1 = x.Equipe1, Equipe2 = x.Equipe2, Statut = x.VoteStatutEnum, Competition = x.Competition.Nom })
         .OrderBy(x => x.Date)
         .ToList();
 }