DefaultPasswordResetProvider.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Security.Cryptography;
  5. using System.Text.Json;
  6. using System.Threading.Tasks;
  7. using Jellyfin.Data.Entities;
  8. using MediaBrowser.Common;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Controller.Authentication;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Model.IO;
  14. using MediaBrowser.Model.Users;
  15. namespace Jellyfin.Server.Implementations.Users
  16. {
  17. /// <summary>
  18. /// The default password reset provider.
  19. /// </summary>
  20. public class DefaultPasswordResetProvider : IPasswordResetProvider
  21. {
  22. private const string BaseResetFileName = "passwordreset";
  23. private readonly IApplicationHost _appHost;
  24. private readonly string _passwordResetFileBase;
  25. private readonly string _passwordResetFileBaseDir;
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="DefaultPasswordResetProvider"/> class.
  28. /// </summary>
  29. /// <param name="configurationManager">The configuration manager.</param>
  30. /// <param name="appHost">The application host.</param>
  31. public DefaultPasswordResetProvider(IServerConfigurationManager configurationManager, IApplicationHost appHost)
  32. {
  33. _passwordResetFileBaseDir = configurationManager.ApplicationPaths.ProgramDataPath;
  34. _passwordResetFileBase = Path.Combine(_passwordResetFileBaseDir, BaseResetFileName);
  35. _appHost = appHost;
  36. // TODO: Remove the circular dependency on UserManager
  37. }
  38. /// <inheritdoc />
  39. public string Name => "Default Password Reset Provider";
  40. /// <inheritdoc />
  41. public bool IsEnabled => true;
  42. /// <inheritdoc />
  43. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  44. {
  45. var userManager = _appHost.Resolve<IUserManager>();
  46. var usersReset = new List<string>();
  47. foreach (var resetFile in Directory.EnumerateFiles(_passwordResetFileBaseDir, $"{BaseResetFileName}*"))
  48. {
  49. SerializablePasswordReset spr;
  50. await using (var str = AsyncFile.OpenRead(resetFile))
  51. {
  52. spr = await JsonSerializer.DeserializeAsync<SerializablePasswordReset>(str).ConfigureAwait(false)
  53. ?? throw new ResourceNotFoundException($"Provided path ({resetFile}) is not valid.");
  54. }
  55. if (spr.ExpirationDate < DateTime.UtcNow)
  56. {
  57. File.Delete(resetFile);
  58. }
  59. else if (string.Equals(
  60. spr.Pin.Replace("-", string.Empty, StringComparison.Ordinal),
  61. pin.Replace("-", string.Empty, StringComparison.Ordinal),
  62. StringComparison.OrdinalIgnoreCase))
  63. {
  64. var resetUser = userManager.GetUserByName(spr.UserName)
  65. ?? throw new ResourceNotFoundException($"User with a username of {spr.UserName} not found");
  66. await userManager.ChangePassword(resetUser, pin).ConfigureAwait(false);
  67. usersReset.Add(resetUser.Username);
  68. File.Delete(resetFile);
  69. }
  70. }
  71. if (usersReset.Count < 1)
  72. {
  73. throw new ResourceNotFoundException($"No Users found with a password reset request matching pin {pin}");
  74. }
  75. return new PinRedeemResult
  76. {
  77. Success = true,
  78. UsersReset = usersReset.ToArray()
  79. };
  80. }
  81. /// <inheritdoc />
  82. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(User user, bool isInNetwork)
  83. {
  84. byte[] bytes = new byte[4];
  85. RandomNumberGenerator.Fill(bytes);
  86. string pin = BitConverter.ToString(bytes);
  87. DateTime expireTime = DateTime.UtcNow.AddMinutes(30);
  88. string filePath = _passwordResetFileBase + user.Id + ".json";
  89. SerializablePasswordReset spr = new SerializablePasswordReset
  90. {
  91. ExpirationDate = expireTime,
  92. Pin = pin,
  93. PinFile = filePath,
  94. UserName = user.Username
  95. };
  96. await using (FileStream fileStream = AsyncFile.OpenWrite(filePath))
  97. {
  98. await JsonSerializer.SerializeAsync(fileStream, spr).ConfigureAwait(false);
  99. }
  100. user.EasyPassword = pin;
  101. return new ForgotPasswordResult
  102. {
  103. Action = ForgotPasswordAction.PinCode,
  104. PinExpirationDate = expireTime,
  105. PinFile = filePath
  106. };
  107. }
  108. #nullable disable
  109. private class SerializablePasswordReset : PasswordPinCreationResult
  110. {
  111. public string Pin { get; set; }
  112. public string UserName { get; set; }
  113. }
  114. }
  115. }