DefaultPasswordResetProvider.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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.Database.Implementations.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.IO;
  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. var str = AsyncFile.OpenRead(resetFile);
  51. await using (str.ConfigureAwait(false))
  52. {
  53. spr = await JsonSerializer.DeserializeAsync<SerializablePasswordReset>(str).ConfigureAwait(false)
  54. ?? throw new ResourceNotFoundException($"Provided path ({resetFile}) is not valid.");
  55. }
  56. if (spr.ExpirationDate < DateTime.UtcNow)
  57. {
  58. File.Delete(resetFile);
  59. }
  60. else if (string.Equals(
  61. spr.Pin.Replace("-", string.Empty, StringComparison.Ordinal),
  62. pin.Replace("-", string.Empty, StringComparison.Ordinal),
  63. StringComparison.Ordinal))
  64. {
  65. var resetUser = userManager.GetUserByName(spr.UserName)
  66. ?? throw new ResourceNotFoundException($"User with a username of {spr.UserName} not found");
  67. await userManager.ChangePassword(resetUser, pin).ConfigureAwait(false);
  68. usersReset.Add(resetUser.Username);
  69. File.Delete(resetFile);
  70. }
  71. }
  72. if (usersReset.Count < 1)
  73. {
  74. throw new ResourceNotFoundException($"No Users found with a password reset request matching pin {pin}");
  75. }
  76. return new PinRedeemResult
  77. {
  78. Success = true,
  79. UsersReset = usersReset.ToArray()
  80. };
  81. }
  82. /// <inheritdoc />
  83. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(User user, bool isInNetwork)
  84. {
  85. byte[] bytes = new byte[4];
  86. RandomNumberGenerator.Fill(bytes);
  87. string pin = BitConverter.ToString(bytes);
  88. DateTime expireTime = DateTime.UtcNow.AddMinutes(30);
  89. string filePath = _passwordResetFileBase + user.Id + ".json";
  90. SerializablePasswordReset spr = new SerializablePasswordReset
  91. {
  92. ExpirationDate = expireTime,
  93. Pin = pin,
  94. PinFile = filePath,
  95. UserName = user.Username
  96. };
  97. FileStream fileStream = AsyncFile.OpenWrite(filePath);
  98. await using (fileStream.ConfigureAwait(false))
  99. {
  100. await JsonSerializer.SerializeAsync(fileStream, spr).ConfigureAwait(false);
  101. }
  102. return new ForgotPasswordResult
  103. {
  104. Action = ForgotPasswordAction.PinCode,
  105. PinExpirationDate = expireTime,
  106. PinFile = filePath
  107. };
  108. }
  109. #nullable disable
  110. private class SerializablePasswordReset : PasswordPinCreationResult
  111. {
  112. public string Pin { get; set; }
  113. public string UserName { get; set; }
  114. }
  115. }
  116. }