DefaultPasswordResetProvider.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. #nullable enable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Security.Cryptography;
  6. using System.Text.Json;
  7. using System.Threading.Tasks;
  8. using Jellyfin.Data.Entities;
  9. using MediaBrowser.Common;
  10. using MediaBrowser.Common.Extensions;
  11. using MediaBrowser.Controller.Authentication;
  12. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.Library;
  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 = File.OpenRead(resetFile))
  51. {
  52. spr = await JsonSerializer.DeserializeAsync<SerializablePasswordReset>(str).ConfigureAwait(false);
  53. }
  54. if (spr.ExpirationDate < DateTime.UtcNow)
  55. {
  56. File.Delete(resetFile);
  57. }
  58. else if (string.Equals(
  59. spr.Pin.Replace("-", string.Empty, StringComparison.Ordinal),
  60. pin.Replace("-", string.Empty, StringComparison.Ordinal),
  61. StringComparison.InvariantCultureIgnoreCase))
  62. {
  63. var resetUser = userManager.GetUserByName(spr.UserName)
  64. ?? throw new ResourceNotFoundException($"User with a username of {spr.UserName} not found");
  65. await userManager.ChangePassword(resetUser, pin).ConfigureAwait(false);
  66. usersReset.Add(resetUser.Username);
  67. File.Delete(resetFile);
  68. }
  69. }
  70. if (usersReset.Count < 1)
  71. {
  72. throw new ResourceNotFoundException($"No Users found with a password reset request matching pin {pin}");
  73. }
  74. return new PinRedeemResult
  75. {
  76. Success = true,
  77. UsersReset = usersReset.ToArray()
  78. };
  79. }
  80. /// <inheritdoc />
  81. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(User user, bool isInNetwork)
  82. {
  83. string pin;
  84. using (var cryptoRandom = RandomNumberGenerator.Create())
  85. {
  86. byte[] bytes = new byte[4];
  87. cryptoRandom.GetBytes(bytes);
  88. pin = BitConverter.ToString(bytes);
  89. }
  90. DateTime expireTime = DateTime.UtcNow.AddMinutes(30);
  91. string filePath = _passwordResetFileBase + user.Id + ".json";
  92. SerializablePasswordReset spr = new SerializablePasswordReset
  93. {
  94. ExpirationDate = expireTime,
  95. Pin = pin,
  96. PinFile = filePath,
  97. UserName = user.Username
  98. };
  99. await using (FileStream fileStream = File.OpenWrite(filePath))
  100. {
  101. await JsonSerializer.SerializeAsync(fileStream, spr).ConfigureAwait(false);
  102. await fileStream.FlushAsync().ConfigureAwait(false);
  103. }
  104. user.EasyPassword = pin;
  105. return new ForgotPasswordResult
  106. {
  107. Action = ForgotPasswordAction.PinCode,
  108. PinExpirationDate = expireTime,
  109. };
  110. }
  111. #nullable disable
  112. private class SerializablePasswordReset : PasswordPinCreationResult
  113. {
  114. public string Pin { get; set; }
  115. public string UserName { get; set; }
  116. }
  117. }
  118. }