Example #1
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       AtLeast12Requirement requirement)
        {
            if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth &&
                                       c.Issuer == Token.Issuer))
            {
                return(Task.FromResult(0));
            }

            if (!context.TryGetParamValue <int>("Id", out var Id))
            {
                return(Task.FromResult(0));
            }

            Book book          = _bookService.Get(Id);
            var  atLeast12Book = book.AgeLimit > requirement.RequiredMinimumAge;

            var dateOfBirth = Convert.ToDateTime(
                context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth &&
                                       c.Issuer == Token.Issuer).Value);

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

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

            if (!atLeast12Book || calculatedAge >= requirement.RequiredMinimumAge)
            {
                context.Succeed(requirement);
            }
            return(Task.FromResult(0));
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       AdultsOnlyRequirement requirement)
        {
            if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth &&
                                       c.Issuer == "https://localhost:5001/"))
            {
                return(Task.FromResult(0));
            }

            if (!context.TryGetParamValue <int>("Id", out var Id))
            {
                return(Task.FromResult(0));
            }

            Book book            = _dataService.GetBook(Id).Result;
            var  adultsOnlyEvent = book.AgeLimit > requirement.RequiredMinimumAge;

            var dateOfBirth = Convert.ToDateTime(
                context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth &&
                                       c.Issuer == "https://localhost:5001/").Value);

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

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

            if (!adultsOnlyEvent || calculatedAge >= requirement.RequiredMinimumAge)
            {
                context.Succeed(requirement);
            }
            return(Task.FromResult(0));
        }