AuthenticationManager.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 id)
  48. {
  49. await using var dbContext = _dbProvider.CreateContext();
  50. var key = await dbContext.ApiKeys
  51. .AsQueryable()
  52. .Where(apiKey => apiKey.AccessToken == id)
  53. .FirstOrDefaultAsync();
  54. if (key == null)
  55. {
  56. return;
  57. }
  58. dbContext.Remove(key);
  59. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  60. }
  61. }
  62. }