AuthenticationManager.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using Jellyfin.Data.Entities.Security;
  5. using MediaBrowser.Controller.Security;
  6. using Microsoft.EntityFrameworkCore;
  7. namespace Jellyfin.Server.Implementations.Security
  8. {
  9. /// <inheritdoc />
  10. public class AuthenticationManager : IAuthenticationManager
  11. {
  12. private readonly JellyfinDbProvider _dbProvider;
  13. /// <summary>
  14. /// Initializes a new instance of the <see cref="AuthenticationManager"/> class.
  15. /// </summary>
  16. /// <param name="dbProvider">The database provider.</param>
  17. public AuthenticationManager(JellyfinDbProvider dbProvider)
  18. {
  19. _dbProvider = dbProvider;
  20. }
  21. /// <inheritdoc />
  22. public async Task CreateApiKey(string name)
  23. {
  24. await using var dbContext = _dbProvider.CreateContext();
  25. dbContext.ApiKeys.Add(new ApiKey(name));
  26. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  27. }
  28. /// <inheritdoc />
  29. public async Task<IReadOnlyList<AuthenticationInfo>> GetApiKeys()
  30. {
  31. await using var dbContext = _dbProvider.CreateContext();
  32. return await dbContext.ApiKeys
  33. .AsAsyncEnumerable()
  34. .Select(key => new AuthenticationInfo
  35. {
  36. AppName = key.Name,
  37. AccessToken = key.AccessToken,
  38. DateCreated = key.DateCreated,
  39. DeviceId = string.Empty,
  40. DeviceName = string.Empty,
  41. AppVersion = string.Empty
  42. }).ToListAsync().ConfigureAwait(false);
  43. }
  44. /// <inheritdoc />
  45. public async Task DeleteApiKey(string accessToken)
  46. {
  47. await using var dbContext = _dbProvider.CreateContext();
  48. var key = await dbContext.ApiKeys
  49. .AsQueryable()
  50. .Where(apiKey => apiKey.AccessToken == accessToken)
  51. .FirstOrDefaultAsync()
  52. .ConfigureAwait(false);
  53. if (key == null)
  54. {
  55. return;
  56. }
  57. dbContext.Remove(key);
  58. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  59. }
  60. }
  61. }