AuthenticationManager.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 IDbContextFactory<JellyfinDb> _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(IDbContextFactory<JellyfinDb> dbProvider)
  18. {
  19. _dbProvider = dbProvider;
  20. }
  21. /// <inheritdoc />
  22. public async Task CreateApiKey(string name)
  23. {
  24. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  25. await using (dbContext.ConfigureAwait(false))
  26. {
  27. dbContext.ApiKeys.Add(new ApiKey(name));
  28. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  29. }
  30. }
  31. /// <inheritdoc />
  32. public async Task<IReadOnlyList<AuthenticationInfo>> GetApiKeys()
  33. {
  34. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  35. await using (dbContext.ConfigureAwait(false))
  36. {
  37. return await dbContext.ApiKeys
  38. .AsAsyncEnumerable()
  39. .Select(key => new AuthenticationInfo
  40. {
  41. AppName = key.Name,
  42. AccessToken = key.AccessToken,
  43. DateCreated = key.DateCreated,
  44. DeviceId = string.Empty,
  45. DeviceName = string.Empty,
  46. AppVersion = string.Empty
  47. }).ToListAsync().ConfigureAwait(false);
  48. }
  49. }
  50. /// <inheritdoc />
  51. public async Task DeleteApiKey(string accessToken)
  52. {
  53. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  54. await using (dbContext.ConfigureAwait(false))
  55. {
  56. var key = await dbContext.ApiKeys
  57. .AsQueryable()
  58. .Where(apiKey => apiKey.AccessToken == accessToken)
  59. .FirstOrDefaultAsync()
  60. .ConfigureAwait(false);
  61. if (key == null)
  62. {
  63. return;
  64. }
  65. dbContext.Remove(key);
  66. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  67. }
  68. }
  69. }
  70. }