AuthenticationManager.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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<JellyfinDbContext> _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<JellyfinDbContext> 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. .Select(key => new AuthenticationInfo
  39. {
  40. AppName = key.Name,
  41. AccessToken = key.AccessToken,
  42. DateCreated = key.DateCreated,
  43. DeviceId = string.Empty,
  44. DeviceName = string.Empty,
  45. AppVersion = string.Empty
  46. }).ToListAsync().ConfigureAwait(false);
  47. }
  48. }
  49. /// <inheritdoc />
  50. public async Task DeleteApiKey(string accessToken)
  51. {
  52. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  53. await using (dbContext.ConfigureAwait(false))
  54. {
  55. await dbContext.ApiKeys
  56. .Where(apiKey => apiKey.AccessToken == accessToken)
  57. .ExecuteDeleteAsync()
  58. .ConfigureAwait(false);
  59. }
  60. }
  61. }
  62. }