using System;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Jellyfin.Api.Constants;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Security;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Jellyfin.Api.Controllers
{
///
/// Authentication controller.
///
[Route("/Auth")]
public class ApiKeyController : BaseJellyfinApiController
{
private readonly ISessionManager _sessionManager;
private readonly IServerApplicationHost _appHost;
private readonly IAuthenticationRepository _authRepo;
///
/// Initializes a new instance of the class.
///
/// Instance of interface.
/// Instance of interface.
/// Instance of interface.
public ApiKeyController(
ISessionManager sessionManager,
IServerApplicationHost appHost,
IAuthenticationRepository authRepo)
{
_sessionManager = sessionManager;
_appHost = appHost;
_authRepo = authRepo;
}
///
/// Get all keys.
///
/// Api keys retrieved.
/// A with all keys.
[HttpGet("Keys")]
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult> GetKeys()
{
var result = _authRepo.Get(new AuthenticationInfoQuery
{
HasUser = false
});
return result;
}
///
/// Create a new api key.
///
/// Name of the app using the authentication key.
/// Api key created.
/// A .
[HttpPost("Keys")]
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public ActionResult CreateKey([FromQuery, Required] string? app)
{
_authRepo.Create(new AuthenticationInfo
{
AppName = app,
AccessToken = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
DateCreated = DateTime.UtcNow,
DeviceId = _appHost.SystemId,
DeviceName = _appHost.FriendlyName,
AppVersion = _appHost.ApplicationVersionString
});
return NoContent();
}
///
/// Remove an api key.
///
/// The access token to delete.
/// Api key deleted.
/// A .
[HttpDelete("Keys/{key}")]
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public ActionResult RevokeKey([FromRoute] string? key)
{
_sessionManager.RevokeToken(key);
return NoContent();
}
}
}