DefaultPasswordResetProvider.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. #nullable enable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Security.Cryptography;
  6. using System.Threading.Tasks;
  7. using Jellyfin.Data.Entities;
  8. using MediaBrowser.Common.Extensions;
  9. using MediaBrowser.Controller.Authentication;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Model.Serialization;
  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 IJsonSerializer _jsonSerializer;
  23. private readonly IUserManager _userManager;
  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="jsonSerializer">The JSON serializer.</param>
  31. /// <param name="userManager">The user manager.</param>
  32. public DefaultPasswordResetProvider(
  33. IServerConfigurationManager configurationManager,
  34. IJsonSerializer jsonSerializer,
  35. IUserManager userManager)
  36. {
  37. _passwordResetFileBaseDir = configurationManager.ApplicationPaths.ProgramDataPath;
  38. _passwordResetFileBase = Path.Combine(_passwordResetFileBaseDir, BaseResetFileName);
  39. _jsonSerializer = jsonSerializer;
  40. _userManager = userManager;
  41. }
  42. /// <inheritdoc />
  43. public string Name => "Default Password Reset Provider";
  44. /// <inheritdoc />
  45. public bool IsEnabled => true;
  46. /// <inheritdoc />
  47. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  48. {
  49. var usersReset = new List<string>();
  50. foreach (var resetFile in Directory.EnumerateFiles(_passwordResetFileBaseDir, $"{BaseResetFileName}*"))
  51. {
  52. SerializablePasswordReset spr;
  53. await using (var str = File.OpenRead(resetFile))
  54. {
  55. spr = await _jsonSerializer.DeserializeFromStreamAsync<SerializablePasswordReset>(str).ConfigureAwait(false);
  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.InvariantCultureIgnoreCase))
  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, bool isInNetwork)
  85. {
  86. string pin;
  87. using (var cryptoRandom = RandomNumberGenerator.Create())
  88. {
  89. byte[] bytes = new byte[4];
  90. cryptoRandom.GetBytes(bytes);
  91. pin = BitConverter.ToString(bytes);
  92. }
  93. DateTime expireTime = DateTime.UtcNow.AddMinutes(30);
  94. string filePath = _passwordResetFileBase + user.Id + ".json";
  95. SerializablePasswordReset spr = new SerializablePasswordReset
  96. {
  97. ExpirationDate = expireTime,
  98. Pin = pin,
  99. PinFile = filePath,
  100. UserName = user.Username
  101. };
  102. await using (FileStream fileStream = File.OpenWrite(filePath))
  103. {
  104. _jsonSerializer.SerializeToStream(spr, fileStream);
  105. await fileStream.FlushAsync().ConfigureAwait(false);
  106. }
  107. user.EasyPassword = pin;
  108. await _userManager.UpdateUserAsync(user).ConfigureAwait(false);
  109. return new ForgotPasswordResult
  110. {
  111. Action = ForgotPasswordAction.PinCode,
  112. PinExpirationDate = expireTime,
  113. };
  114. }
  115. #nullable disable
  116. private class SerializablePasswordReset : PasswordPinCreationResult
  117. {
  118. public string Pin { get; set; }
  119. public string UserName { get; set; }
  120. }
  121. }
  122. }