DefaultPasswordResetProvider.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 == null)
  55. {
  56. throw new NullReferenceException(nameof(spr));
  57. }
  58. if (spr.ExpirationDate < DateTime.UtcNow)
  59. {
  60. File.Delete(resetFile);
  61. }
  62. else if (string.Equals(
  63. spr.Pin.Replace("-", string.Empty, StringComparison.Ordinal),
  64. pin.Replace("-", string.Empty, StringComparison.Ordinal),
  65. StringComparison.InvariantCultureIgnoreCase))
  66. {
  67. var resetUser = userManager.GetUserByName(spr.UserName)
  68. ?? throw new ResourceNotFoundException($"User with a username of {spr.UserName} not found");
  69. await userManager.ChangePassword(resetUser, pin).ConfigureAwait(false);
  70. usersReset.Add(resetUser.Username);
  71. File.Delete(resetFile);
  72. }
  73. }
  74. if (usersReset.Count < 1)
  75. {
  76. throw new ResourceNotFoundException($"No Users found with a password reset request matching pin {pin}");
  77. }
  78. return new PinRedeemResult
  79. {
  80. Success = true,
  81. UsersReset = usersReset.ToArray()
  82. };
  83. }
  84. /// <inheritdoc />
  85. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(User user, bool isInNetwork)
  86. {
  87. string pin;
  88. using (var cryptoRandom = RandomNumberGenerator.Create())
  89. {
  90. byte[] bytes = new byte[4];
  91. cryptoRandom.GetBytes(bytes);
  92. pin = BitConverter.ToString(bytes);
  93. }
  94. DateTime expireTime = DateTime.UtcNow.AddMinutes(30);
  95. string filePath = _passwordResetFileBase + user.Id + ".json";
  96. SerializablePasswordReset spr = new SerializablePasswordReset
  97. {
  98. ExpirationDate = expireTime,
  99. Pin = pin,
  100. PinFile = filePath,
  101. UserName = user.Username
  102. };
  103. await using (FileStream fileStream = File.OpenWrite(filePath))
  104. {
  105. await JsonSerializer.SerializeAsync(fileStream, spr).ConfigureAwait(false);
  106. await fileStream.FlushAsync().ConfigureAwait(false);
  107. }
  108. user.EasyPassword = pin;
  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. }