ApiKeyController.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.ComponentModel.DataAnnotations;
  2. using System.Threading.Tasks;
  3. using Jellyfin.Api.Constants;
  4. using MediaBrowser.Controller.Security;
  5. using MediaBrowser.Model.Querying;
  6. using Microsoft.AspNetCore.Authorization;
  7. using Microsoft.AspNetCore.Http;
  8. using Microsoft.AspNetCore.Mvc;
  9. namespace Jellyfin.Api.Controllers;
  10. /// <summary>
  11. /// Authentication controller.
  12. /// </summary>
  13. [Route("Auth")]
  14. public class ApiKeyController : BaseJellyfinApiController
  15. {
  16. private readonly IAuthenticationManager _authenticationManager;
  17. /// <summary>
  18. /// Initializes a new instance of the <see cref="ApiKeyController"/> class.
  19. /// </summary>
  20. /// <param name="authenticationManager">Instance of <see cref="IAuthenticationManager"/> interface.</param>
  21. public ApiKeyController(IAuthenticationManager authenticationManager)
  22. {
  23. _authenticationManager = authenticationManager;
  24. }
  25. /// <summary>
  26. /// Get all keys.
  27. /// </summary>
  28. /// <response code="200">Api keys retrieved.</response>
  29. /// <returns>A <see cref="QueryResult{AuthenticationInfo}"/> with all keys.</returns>
  30. [HttpGet("Keys")]
  31. [Authorize(Policy = Policies.RequiresElevation)]
  32. [ProducesResponseType(StatusCodes.Status200OK)]
  33. public async Task<ActionResult<QueryResult<AuthenticationInfo>>> GetKeys()
  34. {
  35. var keys = await _authenticationManager.GetApiKeys().ConfigureAwait(false);
  36. return new QueryResult<AuthenticationInfo>(keys);
  37. }
  38. /// <summary>
  39. /// Create a new api key.
  40. /// </summary>
  41. /// <param name="app">Name of the app using the authentication key.</param>
  42. /// <response code="204">Api key created.</response>
  43. /// <returns>A <see cref="NoContentResult"/>.</returns>
  44. [HttpPost("Keys")]
  45. [Authorize(Policy = Policies.RequiresElevation)]
  46. [ProducesResponseType(StatusCodes.Status204NoContent)]
  47. public async Task<ActionResult> CreateKey([FromQuery, Required] string app)
  48. {
  49. await _authenticationManager.CreateApiKey(app).ConfigureAwait(false);
  50. return NoContent();
  51. }
  52. /// <summary>
  53. /// Remove an api key.
  54. /// </summary>
  55. /// <param name="key">The access token to delete.</param>
  56. /// <response code="204">Api key deleted.</response>
  57. /// <returns>A <see cref="NoContentResult"/>.</returns>
  58. [HttpDelete("Keys/{key}")]
  59. [Authorize(Policy = Policies.RequiresElevation)]
  60. [ProducesResponseType(StatusCodes.Status204NoContent)]
  61. public async Task<ActionResult> RevokeKey([FromRoute, Required] string key)
  62. {
  63. await _authenticationManager.DeleteApiKey(key).ConfigureAwait(false);
  64. return NoContent();
  65. }
  66. }