Example #1
0
 /// <summary>
 /// Calls <see cref="AssertionRequirement.Handler"/> to see if authorization is allowed.
 /// </summary>
 /// <param name="context">The authorization information.</param>
 public async Task HandleAsync(AuthorizationHandlerContext context)
 {
     if (await Handler(context))
     {
         context.Succeed(this);
     }
 }
 /// <summary>
 /// Makes a decision if authorization is allowed.
 /// </summary>
 /// <param name="context">The authorization context.</param>
 public async Task HandleAsync(AuthorizationHandlerContext context)
 {
     foreach (var handler in context.Requirements.OfType<IAuthorizationHandler>())
     {
         await handler.HandleAsync(context);
     }
 }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccessAdminActions requirement)
        {
            if (context.User.HasClaim(claim => claim.Type == XtremeIdiotsClaimTypes.SeniorAdmin))
            {
                context.Succeed(requirement);
            }

            if (context.User.HasClaim(claim => claim.Type == XtremeIdiotsClaimTypes.HeadAdmin))
            {
                context.Succeed(requirement);
            }

            if (context.User.HasClaim(claim => claim.Type == XtremeIdiotsClaimTypes.GameAdmin))
            {
                context.Succeed(requirement);
            }

            if (context.User.HasClaim(claim => claim.Type == XtremeIdiotsClaimTypes.Moderator))
            {
                context.Succeed(requirement);
            }

            return(Task.CompletedTask);
        }
Example #4
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccountAccessRequirement requirement)
        {
            //Get organizationn id
            if (context.Resource is AuthorizationFilterContext mvcContext)
            {
                if (mvcContext.HttpContext.Request.Method == HttpMethods.Get || mvcContext.HttpContext.Request.Method == HttpMethods.Delete)
                {
                    var routeDate = mvcContext.RouteData;
                    if (routeDate.Values.ContainsKey("id"))
                    {
                        var account = this.dbContext.Accounts.FirstOrDefault(a => a.Id.ToString() == routeDate.Values["id"].ToString());

                        if (account != null && !context.User.HasClaim(c => c.Type == "Organization" && c.Value == account.OrganizationId.ToString()))
                        {
                            context.Fail();
                            return(Task.CompletedTask);
                        }
                    }
                }
            }

            context.Succeed(requirement);
            return(Task.CompletedTask);
        }
        protected override Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            ShouldBeAnAdminRequirement requirement)
        {
            // check if Role claim exists - Else Return
            // (sort of Claim-based requirement)
            if (!context.User.HasClaim(x => x.Type == ClaimTypes.Role))
            {
                return(Task.CompletedTask);
            }

            // claim exists - retrieve the value
            var claim = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role);
            var role  = claim.Value;

            // check if the claim equals to either Admin or Editor
            // if satisfied, set the requirement as success
            if (role == Roles.Admin || role == Roles.Editor)
            {
                context.Succeed(requirement);
            }

            return(Task.CompletedTask);
        }
Example #6
0
        protected override Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            MinimumAgeRequirement requirement)
        {
            if (context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth))
            {
                var dateOfBirth = Convert.ToDateTime(
                    context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth).Value);

                int calculatedAge = DateTime.Today.Year - dateOfBirth.Year;

                if (dateOfBirth > DateTime.Today.AddYears(-calculatedAge))
                {
                    calculatedAge--;
                }

                if (calculatedAge >= requirement._minAge)
                {
                    context.Succeed(requirement);
                }
            }

            return(Task.CompletedTask);
        }
Example #7
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)
        {
            // If user does not have the scope claim, get out of here
            var hasClaim = context.User.HasClaim(c =>
            {
                return(c.Type == "scope" && c.Issuer == requirement.Issuer);
            });

            if (!hasClaim)
            {
                return(Task.CompletedTask);
            }

            // Split the scopes string into an array
            var scopes = context.User.FindFirst(c => c.Type == "scope" && c.Issuer == requirement.Issuer).Value.Split(' ');

            // Succeed if the scope array contains the required scope
            if (scopes.Any(s => s == requirement.Scope))
            {
                context.Succeed(requirement);
            }

            return(Task.CompletedTask);
        }
Example #8
0
        internal async Task HandlePersonRequirement(AuthorizationHandlerContext context,
                                                    PersonEditRequirement requirement,
                                                    Func <Guid> personId)
        {
            if (context.User.IsAdminOrHr() || context.User.IsHighLevelSupervisor() ||
                context.User.IsInRole("registrar"))
            {
                context.Succeed(requirement);
                return;
            }

            var supervisorGroupId = context.User.SupervisorGroupId() ?? Guid.Empty;

            if (!context.User.IsSupervisor() || supervisorGroupId == Guid.Empty)
            {
                context.Fail();
                return;
            }

            if (await _orgGroupService.IsPersonInGroup(personId(), supervisorGroupId))
            {
                context.Succeed(requirement);
            }
        }
Example #9
0
 protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccionRequirement requirement)
 {
     //marca como Succeed la autorizacion cuando el usuario actual contiene un Claim con el Tipo y el Valor igual a Accion
     if (context.User.HasClaim(c => c.Type == Accion && c.Value == Accion))
     {
         context.Succeed(requirement);
     }
     else
     {
         //existen metodos que deben ser llamados por la aplicación mediante AJAX para realizar distintas acciones
         //para estos casos se pregunta si el usuario tiene un Claim de las acciones que llaman al metodo.
         switch (Accion)
         {
         case "ListarAcciones":
             if (context.User.HasClaim(c => c.Type == "AdicionarRol" && c.Value == "AdicionarRol" ||
                                       c.Type == "ActualizarRol" && c.Value == "ActualizarRol"))
             {
                 context.Succeed(requirement);
             }
             break;
         }
     }
     return(Task.FromResult(0));
 }
        protected async override Task HandleRequirementAsync(AuthorizationHandlerContext context, MustBeQuestionAuthorRequirement requirement)
        {
            // check that the user is authenticated
            if (!context.User.Identity.IsAuthenticated)
            {
                context.Fail();
                return;
            }

            // get the question id from the request
            var questionId      = _httpContextAccessor.HttpContext.Request.RouteValues["questionId"];
            int questionIdAsInt = Convert.ToInt32(questionId);

            // get the user id from the name identifier claim
            var userId = context.User.FindFirst(ClaimTypes.NameIdentifier).Value;

            // get the question from the data repository
            var question = await _dataRepository.GetQuestion(questionIdAsInt);

            if (question == null)
            {
                //  let it through so the controller can return a 404
                context.Succeed(requirement);
                return;
            }
            // if the question can't be found go to the next piece of middleware
            if (question.UserId != userId)
            {
                context.Fail();
                return;
            }
            context.Succeed(requirement);

            // return failure if the user id in the question from the data repository is different to the user id in t
            // return success if we manage to get here
        }
Example #11
0
        protected override Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            MustOwnImageRequirement requirement)
        {
            var imageId = _httpContextAccessor.HttpContext.GetRouteValue("id").ToString();

            if (!Guid.TryParse(imageId, out Guid imageIdAsGuid))
            {
                context.Fail();
                return(Task.CompletedTask);
            }

            var ownerId = context.User.Claims.FirstOrDefault(c => c.Type == "sub").Value;

            if (!_galleryRepository.IsImageOwner(imageIdAsGuid, ownerId))
            {
                context.Fail();
                return(Task.CompletedTask);
            }

            // all checks out
            context.Succeed(requirement);
            return(Task.CompletedTask);
        }
Example #12
0
        public async Task ReleaseIsLiveAndOnlyVersion()
        {
            var publication = new Publication();

            var release = new Release
            {
                Published   = DateTime.Parse("2019-10-10T12:00:00"),
                Publication = publication
            };

            publication.Releases.Add(release);

            var contextId = Guid.NewGuid().ToString();

            await using (var contentDbContext = ContentDbUtils.InMemoryContentDbContext(contextId))
            {
                await contentDbContext.AddAsync(publication);

                await contentDbContext.SaveChangesAsync();
            }

            await using (var contentDbContext = ContentDbUtils.InMemoryContentDbContext(contextId))
            {
                var handler = new ViewReleaseAuthorizationHandler(contentDbContext);

                var authContext = new AuthorizationHandlerContext(
                    new IAuthorizationRequirement[] { Activator.CreateInstance <ViewReleaseRequirement>() },
                    null,
                    release
                    );

                await handler.HandleAsync(authContext);

                Assert.True(authContext.HasSucceeded);
            }
        }
Example #13
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authContext,
                                                             PlayerCanSeePuzzleRequirement requirement)
        {
            PuzzleUser puzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(dbContext, authContext.User, userManager);

            Puzzle puzzle = await AuthorizationHelper.GetPuzzleFromContext(authContext);

            Event thisEvent = await AuthorizationHelper.GetEventFromContext(authContext);

            if (thisEvent != null && puzzle != null)
            {
                Team team = await UserEventHelper.GetTeamForPlayer(dbContext, thisEvent, puzzleUser);

                if (team != null)
                {
                    IQueryable <PuzzleStatePerTeam> statesQ = PuzzleStateHelper.GetFullReadOnlyQuery(dbContext, thisEvent, puzzle, team);

                    if (statesQ.FirstOrDefault().UnlockedTime != null || thisEvent.AreAnswersAvailableNow)
                    {
                        authContext.Succeed(requirement);
                    }
                }
            }
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ScopeRequirement requirement)
        {
            var claim = context.User.FindFirst(c =>
                                               string.Equals(c.Issuer, requirement.Issuer) &&
                                               string.Equals(c.Type, "scope"));

            if (claim is null)
            {
                return(Task.CompletedTask);
            }

            var scopes = claim.Value.Split(' ');

            foreach (var scope in scopes)
            {
                if (string.Equals(scope, requirement.Scope))
                {
                    context.Succeed(requirement);
                    break;
                }
            }

            return(Task.CompletedTask);
        }
        private async Task <bool> BeforeAuthorizeAsync(AuthorizationHandlerContext context, TRequirement requirement)
        {
            var curentRole = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role);

            var userId = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

            if (curentRole != null && userId != null)
            {
                var _userManager = ResolverFactory.GetService <UserManager <ApplicationUser> >();

                var user = await _userManager.FindByIdAsync(userId.Value);

                var result = await _userManager.GetRolesAsync(user);

                var dbRole = result.FirstOrDefault();

                if (curentRole.Value != dbRole)
                {
                    return(false);
                }
            }

            return(true);
        }
Example #16
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       OperationAuthorizationRequirement requirement,
                                                       User user)
        {
            //it's a daemon application, all operations are allowed
            if (context.User.TryFindClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Daemon"))
            {
                context.Succeed(requirement);
            }

            //user is an admin of customer
            if (context.User.TryFindClaim("x-customer-admin", user.CustomerId.ToString()))
            {
                context.Succeed(requirement);
            }

            //user wants to get own claims
            if (context.User.TryFindClaim("x-userId", user.Id.ToString()))
            {
                context.Succeed(requirement);
            }

            return(Task.CompletedTask);
        }
        public async Task ReleaseIsLiveAndOnlyVersion()
        {
            var release = new Release
            {
                Published = new DateTime(2021, 1, 1),
            };

            var publication = new Publication
            {
                Releases = ListOf(release)
            };

            var contextId = Guid.NewGuid().ToString();

            await using (var contentDbContext = InMemoryContentDbContext(contextId))
            {
                await contentDbContext.AddAsync(publication);

                await contentDbContext.SaveChangesAsync();
            }

            await using (var contentDbContext = InMemoryContentDbContext(contextId))
            {
                var handler = new ViewReleaseAuthorizationHandler(contentDbContext);

                var authContext = new AuthorizationHandlerContext(
                    new IAuthorizationRequirement[] { Activator.CreateInstance <ViewReleaseRequirement>() },
                    null,
                    release
                    );

                await handler.HandleAsync(authContext);

                Assert.True(authContext.HasSucceeded);
            }
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement)
        {
            if (context.User != null)
            {
                var userIdClaim = context.User.FindFirst(_ => _.Type == JwtClaimTypes.Id);
                if (userIdClaim != null)
                {
                    var userId = userIdClaim.Value;

                    // 根据userId查询数据库权限 获取权限code
                    // 对比权限code 是否包含requirement.Code

                    if (requirement.Code == "3002")
                    {
                        context.Succeed(requirement);
                    }
                }
                else
                {
                    context.Fail();
                }
            }
            return(Task.CompletedTask);
        }
Example #19
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                             StaffEditRequirement requirement,
                                                             Guid staffId)
        {
            if (context.User.IsAdminOrHr() || context.User.IsHighLevelSupervisor() ||
                context.User.IsInRole("registrar"))
            {
                context.Succeed(requirement);
                return;
            }

            var supervisorGroupId = context.User.SupervisorGroupId() ?? Guid.Empty;

            if (!context.User.IsSupervisor() || supervisorGroupId == Guid.Empty)
            {
                context.Fail();
                return;
            }

            if (await _orgGroupService.IsStaffInGroup(staffId, supervisorGroupId))
            {
                context.Succeed(requirement);
            }
        }
Example #20
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       AuthorOnlyRequirement requirement)
        {
            if (context.Resource is IPost post)
            {
                var user = context.User;

                if (IsInBypassRole(user, requirement.BypassRoles) ||
                    IsAuthor(user, post))
                {
                    context.Succeed(requirement);
                }
                else
                {
                    context.Fail();
                }
            }
            else if (context.Resource != null)
            {
                throw new NotSupportedException();
            }

            return(Task.CompletedTask);
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       OperationAuthorizationRequirement requirement,
                                                       MalfunctionWorkOrder resource)
        {
            if (context.User == null || resource == null)
            {
                return(Task.CompletedTask);
            }

            if (requirement.Name != Constants.CreateOperationName &&
                requirement.Name != Constants.ReadOperationName &&
                requirement.Name != Constants.UpdateOperationName &&
                requirement.Name != Constants.DeleteOperationName)
            {
                return(Task.CompletedTask);
            }

            if (resource.Creator == _userManager.GetUserAsync(context.User).Result.Name)
            {
                context.Succeed(requirement);
            }

            return(Task.CompletedTask);
        }
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, CourseRoleRequirement requirement)
        {
            /* Get MVC context. See https://docs.microsoft.com/en-US/aspnet/core/security/authorization/policies#accessing-mvc-request-context-in-handlers */
            if (!(context.Resource is AuthorizationFilterContext mvcContext))
            {
                logger.Error("Can't get MVC context in CourseRoleAuthenticationHandler");
                context.Fail();
                return;
            }

            var routeData = mvcContext.RouteData;

            if (!(routeData.Values["courseId"] is string courseId))
            {
                logger.Error("Can't find `courseId` parameter in route data for checking course role requirement.");
                context.Fail();
                return;
            }

            if (context.User.IsSystemAdministrator())
            {
                context.Succeed(requirement);
                return;
            }

            var userId = context.User.GetUserId();

            if (await userRolesRepo.HasUserAccessToCourseAsync(userId, courseId, requirement.MinCourseRole))
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }
        }
Example #23
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       RoleAuthorizeRequirement requirement)
        {
            var controllerContext = context.Resource as AuthorizationFilterContext;
            var redirectResult    = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                area       = requirement.Role,
                controller = "Account",
                action     = "Login"
            }));

            if (context.User?.Identity.IsAuthenticated ?? false)
            {
                if (context.User.HasClaim(c => c.Type == ClaimTypes.Role) && context.User.IsInRole(requirement.Role))
                {
                    context.Succeed(requirement);
                }
                else
                {
                    if (controllerContext != null)
                    {
                        controllerContext.Result = redirectResult;
                    }
                    context.Succeed(requirement);
                }
            }
            else
            {
                if (controllerContext != null)
                {
                    controllerContext.Result = redirectResult;
                }
                context.Succeed(requirement);
            }
            return(Task.CompletedTask);
        }
Example #24
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, OmsApiRequirement requirement)
        {
            if (!(context.User.Identity is WindowsIdentity windowsIdentity))
            {
                return(Task.CompletedTask);
            }

            var windowsUser = new WindowsPrincipal(windowsIdentity);

            try
            {
                var hasRole = windowsUser?.IsInRole(requirement.GroupName) ?? false;
                if (hasRole)
                {
                    context.Succeed(requirement);
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Unable to check groups the user belongs too");
            }

            return(Task.CompletedTask);
        }
Example #25
0
        HandleRequirementAsync(AuthorizationHandlerContext context,
                               OperationAuthorizationRequirement requirement,
                               Contact resource)
        {
            if (context.User == null || resource == null)
            {
                return(Task.FromResult(0));
            }

            // If not asking for approval/reject, return.
            if (requirement.Name != Constants.ApproveOperationName &&
                requirement.Name != Constants.RejectOperationName)
            {
                return(Task.FromResult(0));
            }

            // Managers can approve or reject.
            if (context.User.IsInRole(Constants.ContactManagersRole))
            {
                context.Succeed(requirement);
            }

            return(Task.FromResult(0));
        }
        public Task HandleAsync(AuthorizationHandlerContext context)
        {
            var pendingRequirements = context.PendingRequirements.ToList();

            foreach (var requirement in pendingRequirements)
            {
                switch (requirement)
                {
                case RoleIsPresentRequirement roleIsPresentRequirement:
                {
                    if (context.User.IsInRole(roleIsPresentRequirement.Role))
                    {
                        context.Succeed(roleIsPresentRequirement);
                    }

                    break;
                }

                case GenderRequirement genderRequirement:
                {
                    if (context.User.HasClaim(c => c.Type == JwtClaimTypes.Gender))
                    {
                        var claim = context.User.FindFirst(c => c.Type == JwtClaimTypes.Gender);
                        if (claim.Value == genderRequirement.Gender)
                        {
                            context.Succeed(requirement);
                        }
                    }

                    break;
                }
                }
            }

            return(Task.CompletedTask);
        }
Example #27
0
        /// <summary>
        /// Handle requirement
        /// </summary>
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, EmailDomainRequirement requirement)
        {
            string validateMsgOK = $"Validate OK with {nameof(EmailDomainAuthHandler)}";
            string validateMsgNG = $"Validate NG with {nameof(EmailDomainAuthHandler)}";

            ClaimsPrincipal userClaim = context.User;

            if (context.HasFailed || userClaim.Identity == null || !userClaim.Identities.Any(i => i.IsAuthenticated))
            {
                context.Fail();
                this.logger.LogWarning($"Skip validating with {nameof(EmailDomainAuthHandler)} cus the authorization process had been failed!");
                return;
            }

            var userEmailClaim = userClaim.Claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Email));

            if (userEmailClaim != null)
            {
                // Get domain name from email
                var    address    = new MailAddress(userEmailClaim.Value);
                string userDomain = address.Host; // e.q. google.com

                // Verify domain
                if (userDomain.Equals(requirement.Domain))
                {
                    this.logger.LogDebug(validateMsgOK);
                    context.Succeed(requirement);
                    return;
                }
            }

            this.logger.LogDebug(validateMsgNG);
            context.Fail();

            await Task.CompletedTask;
        }
Example #28
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            if (context.User.Claims.Any())
            {
                if (context.Resource is Endpoint endpoint)
                {
                    var actionDescriptor = endpoint.Metadata.GetMetadata <ControllerActionDescriptor>();
                    var theController    = actionDescriptor.RouteValues["controller"];
                    var theAction        = actionDescriptor.RouteValues["action"];
                    //判断过期时间
                    if (DateTime.Parse(context.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration).Value) >= DateTime.Now)
                    {
                        context.Succeed(requirement);
                    }
                    else
                    {
                        context.Fail();
                    }
                }
            }
            ;

            return(Task.CompletedTask);
        }
Example #29
0
        async protected override Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            AccountRequirement requirement)
        {
            var httpContext = _httpContextAccessor;

            httpContext.HttpContext.Request.EnableBuffering();
            string authHeader = httpContext.HttpContext.Request.Headers["Authorization"];
            string tokenStr   = authHeader.Replace("Bearer ", "");
            var    handler    = new JwtSecurityTokenHandler();
            var    payload    = handler.ReadJwtToken(tokenStr).Payload;
            var    claims     = payload.Claims;
            var    roomId     = claims.First(claim => claim.Type == "roomId").Value;
            var    body       = httpContext.HttpContext.Request.Body;
            var    reader     = new StreamReader(body);
            var    bodyStr    = await reader.ReadToEndAsync();

            body.Position = 0;
            string roomIdByBody = string.Empty;

            if (string.IsNullOrEmpty(bodyStr) || !bodyStr.Contains("roomId"))
            {
                roomIdByBody = httpContext.HttpContext.Request.RouteValues.Values.ToList()[2].ToString();
            }
            else
            {
                roomIdByBody = JsonConvert.DeserializeObject <CreatRoomDTO>(bodyStr).RoomId.ToString();
            }
            if (roomId != roomIdByBody)
            {
                context.Fail();
                return;
            }
            context.Succeed(requirement);
            return;
        }
Example #30
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IsHostRequirement requirement)
        {
            if (context.Resource is AuthorizationFilterContext authContext)
            {
                var currentUserName = _httpContextAccessor.HttpContext.User?.Claims?.SingleOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
                var activityId      = Guid.Parse(authContext.RouteData.Values["id"].ToString());

                var activity = _context.Activities.FindAsync(activityId).Result;

                var host = activity.UserActivities.FirstOrDefault(x => x.IsHost);

                if (host?.AppUser?.UserName == currentUserName)
                {
                    context.Succeed(requirement);
                }
            }

            else
            {
                context.Fail();
            }

            return(Task.CompletedTask);
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       ManageAdminRolesAndClaimsRequirement requirement)
        {
            var authFilterContext = httpContextAccessor.HttpContext;

            if (authFilterContext == null)
            {
                return(Task.CompletedTask);
            }

            string loggedInAdminId =
                context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;

            string adminIdBeingEdited = httpContextAccessor.HttpContext.Request.Query["userId"].ToString();

            if (context.User.IsInRole("Admin") &&
                context.User.HasClaim(claim => claim.Type == "Edit Role" && claim.Value == "true") &&
                adminIdBeingEdited.ToLower() != loggedInAdminId.ToLower())
            {
                context.Succeed(requirement);
            }

            return(Task.CompletedTask);
        }
        /// <inheritdoc/>
        public async Task HandleAsync(AuthorizationHandlerContext context)
        {
            context = context ?? throw new ArgumentNullException(nameof(context));

            string teamId       = string.Empty;
            var    oidClaimType = Constants.OidClaimType;

            var oidClaim = context.User.Claims.FirstOrDefault(p => oidClaimType == p.Type);

            foreach (var requirement in context.Requirements)
            {
                if (requirement is MustBeTeacherOrAdminUserPolicyRequirement)
                {
                    if (context.Resource is AuthorizationFilterContext authorizationFilterContext)
                    {
                        // Wrap the request stream so that we can rewind it back to the start for regular request processing.
                        authorizationFilterContext.HttpContext.Request.EnableBuffering();

                        var isUserPartOfTeachersGroup = await this.memberValidationService.ValidateMemberAsync(oidClaim.Value, this.securityGroupOptions.Value.TeacherSecurityGroupId, authorizationFilterContext.HttpContext.Request.Headers["Authorization"].ToString());

                        if (isUserPartOfTeachersGroup)
                        {
                            context.Succeed(requirement);
                        }

                        // Check whether user is part of Administrator group or not. Administrator has access to edit and delete other teachers content.
                        var isUserPartOfAdminGroup = await this.memberValidationService.ValidateMemberAsync(oidClaim.Value, this.securityGroupOptions.Value.AdminGroupId, authorizationFilterContext.HttpContext.Request.Headers["Authorization"].ToString());

                        if (isUserPartOfAdminGroup)
                        {
                            context.Succeed(requirement);
                        }
                    }
                }
            }
        }