DefaultPasswordResetProvider.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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.Users;
  14. namespace Jellyfin.Server.Implementations.Users
  15. {
  16. /// <summary>
  17. /// The default password reset provider.
  18. /// </summary>
  19. public class DefaultPasswordResetProvider : IPasswordResetProvider
  20. {
  21. private const string BaseResetFileName = "passwordreset";
  22. private readonly IApplicationHost _appHost;
  23. private readonly string _passwordResetFileBase;
  24. private readonly string _passwordResetFileBaseDir;
  25. /// <summary>
  26. /// Initializes a new instance of the <see cref="DefaultPasswordResetProvider"/> class.
  27. /// </summary>
  28. /// <param name="configurationManager">The configuration manager.</param>
  29. /// <param name="appHost">The application host.</param>
  30. public DefaultPasswordResetProvider(IServerConfigurationManager configurationManager, IApplicationHost appHost)
  31. {
  32. _passwordResetFileBaseDir = configurationManager.ApplicationPaths.ProgramDataPath;
  33. _passwordResetFileBase = Path.Combine(_passwordResetFileBaseDir, BaseResetFileName);
  34. _appHost = appHost;
  35. // TODO: Remove the circular dependency on UserManager
  36. }
  37. /// <inheritdoc />
  38. public string Name => "Default Password Reset Provider";
  39. /// <inheritdoc />
  40. public bool IsEnabled => true;
  41. /// <inheritdoc />
  42. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  43. {
  44. var userManager = _appHost.Resolve<IUserManager>();
  45. var usersReset = new List<string>();
  46. foreach (var resetFile in Directory.EnumerateFiles(_passwordResetFileBaseDir, $"{BaseResetFileName}*"))
  47. {
  48. SerializablePasswordReset spr;
  49. await using (var str = File.OpenRead(resetFile))
  50. {
  51. spr = await JsonSerializer.DeserializeAsync<SerializablePasswordReset>(str).ConfigureAwait(false)
  52. ?? throw new ResourceNotFoundException($"Provided path ({resetFile}) is not valid.");
  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.OrdinalIgnoreCase))
  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. }