AuthenticationManager.cs 2.3 KB

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