ApiKeyController.cs 2.8 KB

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