AuthenticationManager.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using Jellyfin.Database.Implementations;
  5. using Jellyfin.Database.Implementations.Entities.Security;
  6. using MediaBrowser.Controller.Security;
  7. using Microsoft.EntityFrameworkCore;
  8. namespace Jellyfin.Server.Implementations.Security
  9. {
  10. /// <inheritdoc />
  11. public class AuthenticationManager : IAuthenticationManager
  12. {
  13. private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="AuthenticationManager"/> class.
  16. /// </summary>
  17. /// <param name="dbProvider">The database provider.</param>
  18. public AuthenticationManager(IDbContextFactory<JellyfinDbContext> dbProvider)
  19. {
  20. _dbProvider = dbProvider;
  21. }
  22. /// <inheritdoc />
  23. public async Task CreateApiKey(string name)
  24. {
  25. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  26. await using (dbContext.ConfigureAwait(false))
  27. {
  28. dbContext.ApiKeys.Add(new ApiKey(name));
  29. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  30. }
  31. }
  32. /// <inheritdoc />
  33. public async Task<IReadOnlyList<AuthenticationInfo>> GetApiKeys()
  34. {
  35. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  36. await using (dbContext.ConfigureAwait(false))
  37. {
  38. return await dbContext.ApiKeys
  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. await dbContext.ApiKeys
  57. .Where(apiKey => apiKey.AccessToken == accessToken)
  58. .ExecuteDeleteAsync()
  59. .ConfigureAwait(false);
  60. }
  61. }
  62. }
  63. }