using Microsoft.AspNetCore.Authorization;
using System;
using System.Threading.Tasks;

namespace WK5_Blazor.Authorization
{
    /// <summary>
    /// Diese Policy kann dazu verwendet werden, um nur speziellen Usern Zugriff auf bestimmte Seiten und Funktionen zu geben.
    /// </summary>
    public class IsUserRequirement : IAuthorizationRequirement
    {
        public IsUserRequirement(params string[] usernames)
        {
            Usernames = usernames;
        }

        public string[] Usernames { get; }
    }

    public class IsUserAuthHandler : AuthorizationHandler<IsUserRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IsUserRequirement requirement)
        {
            foreach (var username in requirement.Usernames)
            {
                if (context.User.Identity?.Name?.Equals(username, StringComparison.OrdinalIgnoreCase) == true)
                {
                    context.Succeed(requirement);
                    break;
                }
            }

            return Task.CompletedTask;
        }
    }
}
