DefaultPasswordResetProvider.cs 5.3 KB

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