using System.Threading.Tasks;
using Jellyfin.Api.Extensions;
using Jellyfin.Extensions;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Library;
using Microsoft.AspNetCore.Authorization;
namespace Jellyfin.Api.Auth.UserPermissionPolicy
{
///
/// User permission authorization handler.
///
public class UserPermissionHandler : AuthorizationHandler
{
private readonly IUserManager _userManager;
///
/// Initializes a new instance of the class.
///
/// Instance of the interface.
public UserPermissionHandler(IUserManager userManager)
{
_userManager = userManager;
}
///
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserPermissionRequirement requirement)
{
// Api keys have global permissions, so just succeed the requirement.
if (context.User.GetIsApiKey())
{
context.Succeed(requirement);
}
else
{
var userId = context.User.GetUserId();
if (!userId.IsEmpty())
{
var user = _userManager.GetUserById(context.User.GetUserId());
if (user is null)
{
throw new ResourceNotFoundException();
}
if (user.HasPermission(requirement.RequiredPermission))
{
context.Succeed(requirement);
}
}
}
return Task.CompletedTask;
}
}
}