UserManager.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Controller;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Connect;
  8. using MediaBrowser.Controller.Drawing;
  9. using MediaBrowser.Controller.Dto;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.Persistence;
  13. using MediaBrowser.Controller.Providers;
  14. using MediaBrowser.Model.Configuration;
  15. using MediaBrowser.Model.Connect;
  16. using MediaBrowser.Model.Dto;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.Events;
  19. using MediaBrowser.Model.Logging;
  20. using MediaBrowser.Model.Serialization;
  21. using MediaBrowser.Model.Users;
  22. using MediaBrowser.Server.Implementations.Security;
  23. using System;
  24. using System.Collections.Generic;
  25. using System.Globalization;
  26. using System.IO;
  27. using System.Linq;
  28. using System.Security.Cryptography;
  29. using System.Text;
  30. using System.Threading;
  31. using System.Threading.Tasks;
  32. namespace MediaBrowser.Server.Implementations.Library
  33. {
  34. /// <summary>
  35. /// Class UserManager
  36. /// </summary>
  37. public class UserManager : IUserManager
  38. {
  39. /// <summary>
  40. /// Gets the users.
  41. /// </summary>
  42. /// <value>The users.</value>
  43. public IEnumerable<User> Users { get; private set; }
  44. /// <summary>
  45. /// The _logger
  46. /// </summary>
  47. private readonly ILogger _logger;
  48. /// <summary>
  49. /// Gets or sets the configuration manager.
  50. /// </summary>
  51. /// <value>The configuration manager.</value>
  52. private IServerConfigurationManager ConfigurationManager { get; set; }
  53. /// <summary>
  54. /// Gets the active user repository
  55. /// </summary>
  56. /// <value>The user repository.</value>
  57. private IUserRepository UserRepository { get; set; }
  58. public event EventHandler<GenericEventArgs<User>> UserPasswordChanged;
  59. private readonly IXmlSerializer _xmlSerializer;
  60. private readonly INetworkManager _networkManager;
  61. private readonly Func<IImageProcessor> _imageProcessorFactory;
  62. private readonly Func<IDtoService> _dtoServiceFactory;
  63. private readonly Func<IConnectManager> _connectFactory;
  64. private readonly IServerApplicationHost _appHost;
  65. /// <summary>
  66. /// Initializes a new instance of the <see cref="UserManager" /> class.
  67. /// </summary>
  68. /// <param name="logger">The logger.</param>
  69. /// <param name="configurationManager">The configuration manager.</param>
  70. /// <param name="userRepository">The user repository.</param>
  71. public UserManager(ILogger logger, IServerConfigurationManager configurationManager, IUserRepository userRepository, IXmlSerializer xmlSerializer, INetworkManager networkManager, Func<IImageProcessor> imageProcessorFactory, Func<IDtoService> dtoServiceFactory, Func<IConnectManager> connectFactory, IServerApplicationHost appHost)
  72. {
  73. _logger = logger;
  74. UserRepository = userRepository;
  75. _xmlSerializer = xmlSerializer;
  76. _networkManager = networkManager;
  77. _imageProcessorFactory = imageProcessorFactory;
  78. _dtoServiceFactory = dtoServiceFactory;
  79. _connectFactory = connectFactory;
  80. _appHost = appHost;
  81. ConfigurationManager = configurationManager;
  82. Users = new List<User>();
  83. DeletePinFile();
  84. }
  85. #region UserUpdated Event
  86. /// <summary>
  87. /// Occurs when [user updated].
  88. /// </summary>
  89. public event EventHandler<GenericEventArgs<User>> UserUpdated;
  90. public event EventHandler<GenericEventArgs<User>> UserConfigurationUpdated;
  91. /// <summary>
  92. /// Called when [user updated].
  93. /// </summary>
  94. /// <param name="user">The user.</param>
  95. private void OnUserUpdated(User user)
  96. {
  97. EventHelper.FireEventIfNotNull(UserUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  98. }
  99. #endregion
  100. #region UserDeleted Event
  101. /// <summary>
  102. /// Occurs when [user deleted].
  103. /// </summary>
  104. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  105. /// <summary>
  106. /// Called when [user deleted].
  107. /// </summary>
  108. /// <param name="user">The user.</param>
  109. private void OnUserDeleted(User user)
  110. {
  111. EventHelper.QueueEventIfNotNull(UserDeleted, this, new GenericEventArgs<User> { Argument = user }, _logger);
  112. }
  113. #endregion
  114. /// <summary>
  115. /// Gets a User by Id
  116. /// </summary>
  117. /// <param name="id">The id.</param>
  118. /// <returns>User.</returns>
  119. /// <exception cref="System.ArgumentNullException"></exception>
  120. public User GetUserById(Guid id)
  121. {
  122. if (id == Guid.Empty)
  123. {
  124. throw new ArgumentNullException("id");
  125. }
  126. return Users.FirstOrDefault(u => u.Id == id);
  127. }
  128. /// <summary>
  129. /// Gets the user by identifier.
  130. /// </summary>
  131. /// <param name="id">The identifier.</param>
  132. /// <returns>User.</returns>
  133. public User GetUserById(string id)
  134. {
  135. return GetUserById(new Guid(id));
  136. }
  137. public User GetUserByName(string name)
  138. {
  139. if (string.IsNullOrWhiteSpace(name))
  140. {
  141. throw new ArgumentNullException("name");
  142. }
  143. return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));
  144. }
  145. public async Task Initialize()
  146. {
  147. Users = await LoadUsers().ConfigureAwait(false);
  148. }
  149. public Task<bool> AuthenticateUser(string username, string passwordSha1, string remoteEndPoint)
  150. {
  151. return AuthenticateUser(username, passwordSha1, null, remoteEndPoint);
  152. }
  153. public async Task<bool> AuthenticateUser(string username, string passwordSha1, string passwordMd5, string remoteEndPoint)
  154. {
  155. if (string.IsNullOrWhiteSpace(username))
  156. {
  157. throw new ArgumentNullException("username");
  158. }
  159. var user = Users.FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  160. if (user == null)
  161. {
  162. throw new AuthenticationException("Invalid username or password entered.");
  163. }
  164. if (user.Configuration.IsDisabled)
  165. {
  166. throw new AuthenticationException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  167. }
  168. var success = false;
  169. // Authenticate using local credentials if not a guest
  170. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value != UserLinkType.Guest)
  171. {
  172. success = string.Equals(GetPasswordHash(user), passwordSha1.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  173. if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
  174. {
  175. success = string.Equals(GetLocalPasswordHash(user), passwordSha1.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  176. }
  177. }
  178. // Maybe user accidently entered connect credentials. let's be flexible
  179. if (!success && user.ConnectLinkType.HasValue && !string.IsNullOrWhiteSpace(passwordMd5))
  180. {
  181. try
  182. {
  183. await _connectFactory().Authenticate(user.ConnectUserName, passwordMd5).ConfigureAwait(false);
  184. success = true;
  185. }
  186. catch
  187. {
  188. }
  189. }
  190. // Update LastActivityDate and LastLoginDate, then save
  191. if (success)
  192. {
  193. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  194. await UpdateUser(user).ConfigureAwait(false);
  195. }
  196. _logger.Info("Authentication request for {0} {1}.", user.Name, (success ? "has succeeded" : "has been denied"));
  197. return success;
  198. }
  199. private string GetPasswordHash(User user)
  200. {
  201. return string.IsNullOrEmpty(user.Password)
  202. ? GetSha1String(string.Empty)
  203. : user.Password;
  204. }
  205. private string GetLocalPasswordHash(User user)
  206. {
  207. return string.IsNullOrEmpty(user.LocalPassword)
  208. ? GetSha1String(string.Empty)
  209. : user.LocalPassword;
  210. }
  211. private bool IsPasswordEmpty(string passwordHash)
  212. {
  213. return string.Equals(passwordHash, GetSha1String(string.Empty), StringComparison.OrdinalIgnoreCase);
  214. }
  215. /// <summary>
  216. /// Gets the sha1 string.
  217. /// </summary>
  218. /// <param name="str">The STR.</param>
  219. /// <returns>System.String.</returns>
  220. private static string GetSha1String(string str)
  221. {
  222. using (var provider = SHA1.Create())
  223. {
  224. var hash = provider.ComputeHash(Encoding.UTF8.GetBytes(str));
  225. return BitConverter.ToString(hash).Replace("-", string.Empty);
  226. }
  227. }
  228. /// <summary>
  229. /// Loads the users from the repository
  230. /// </summary>
  231. /// <returns>IEnumerable{User}.</returns>
  232. private async Task<IEnumerable<User>> LoadUsers()
  233. {
  234. var users = UserRepository.RetrieveAllUsers().ToList();
  235. // There always has to be at least one user.
  236. if (users.Count == 0)
  237. {
  238. var name = Environment.UserName;
  239. var user = InstantiateNewUser(name, false);
  240. user.DateLastSaved = DateTime.UtcNow;
  241. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  242. users.Add(user);
  243. user.Configuration.IsAdministrator = true;
  244. user.Configuration.EnableRemoteControlOfOtherUsers = true;
  245. UpdateConfiguration(user, user.Configuration);
  246. }
  247. return users;
  248. }
  249. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  250. {
  251. if (user == null)
  252. {
  253. throw new ArgumentNullException("user");
  254. }
  255. var passwordHash = GetPasswordHash(user);
  256. var hasConfiguredDefaultPassword = !IsPasswordEmpty(passwordHash);
  257. var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  258. !IsPasswordEmpty(GetLocalPasswordHash(user)) :
  259. hasConfiguredDefaultPassword;
  260. var dto = new UserDto
  261. {
  262. Id = user.Id.ToString("N"),
  263. Name = user.Name,
  264. HasPassword = hasPassword,
  265. HasConfiguredPassword = hasConfiguredDefaultPassword,
  266. LastActivityDate = user.LastActivityDate,
  267. LastLoginDate = user.LastLoginDate,
  268. Configuration = user.Configuration,
  269. ConnectLinkType = user.ConnectLinkType,
  270. ConnectUserId = user.ConnectUserId,
  271. ConnectUserName = user.ConnectUserName,
  272. ServerId = _appHost.SystemId
  273. };
  274. var image = user.GetImageInfo(ImageType.Primary, 0);
  275. if (image != null)
  276. {
  277. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  278. try
  279. {
  280. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  281. }
  282. catch (Exception ex)
  283. {
  284. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  285. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  286. }
  287. }
  288. return dto;
  289. }
  290. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  291. {
  292. try
  293. {
  294. return _imageProcessorFactory().GetImageCacheTag(item, image);
  295. }
  296. catch (Exception ex)
  297. {
  298. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  299. return null;
  300. }
  301. }
  302. /// <summary>
  303. /// Refreshes metadata for each user
  304. /// </summary>
  305. /// <param name="cancellationToken">The cancellation token.</param>
  306. /// <returns>Task.</returns>
  307. public Task RefreshUsersMetadata(CancellationToken cancellationToken)
  308. {
  309. var tasks = Users.Select(user => user.RefreshMetadata(new MetadataRefreshOptions(), cancellationToken)).ToList();
  310. return Task.WhenAll(tasks);
  311. }
  312. /// <summary>
  313. /// Renames the user.
  314. /// </summary>
  315. /// <param name="user">The user.</param>
  316. /// <param name="newName">The new name.</param>
  317. /// <returns>Task.</returns>
  318. /// <exception cref="System.ArgumentNullException">user</exception>
  319. /// <exception cref="System.ArgumentException"></exception>
  320. public async Task RenameUser(User user, string newName)
  321. {
  322. if (user == null)
  323. {
  324. throw new ArgumentNullException("user");
  325. }
  326. if (string.IsNullOrEmpty(newName))
  327. {
  328. throw new ArgumentNullException("newName");
  329. }
  330. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  331. {
  332. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  333. }
  334. if (user.Name.Equals(newName, StringComparison.Ordinal))
  335. {
  336. throw new ArgumentException("The new and old names must be different.");
  337. }
  338. await user.Rename(newName);
  339. OnUserUpdated(user);
  340. }
  341. /// <summary>
  342. /// Updates the user.
  343. /// </summary>
  344. /// <param name="user">The user.</param>
  345. /// <exception cref="System.ArgumentNullException">user</exception>
  346. /// <exception cref="System.ArgumentException"></exception>
  347. public async Task UpdateUser(User user)
  348. {
  349. if (user == null)
  350. {
  351. throw new ArgumentNullException("user");
  352. }
  353. if (user.Id == Guid.Empty || !Users.Any(u => u.Id.Equals(user.Id)))
  354. {
  355. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  356. }
  357. user.DateModified = DateTime.UtcNow;
  358. user.DateLastSaved = DateTime.UtcNow;
  359. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  360. OnUserUpdated(user);
  361. }
  362. public event EventHandler<GenericEventArgs<User>> UserCreated;
  363. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  364. /// <summary>
  365. /// Creates the user.
  366. /// </summary>
  367. /// <param name="name">The name.</param>
  368. /// <returns>User.</returns>
  369. /// <exception cref="System.ArgumentNullException">name</exception>
  370. /// <exception cref="System.ArgumentException"></exception>
  371. public async Task<User> CreateUser(string name)
  372. {
  373. if (string.IsNullOrWhiteSpace(name))
  374. {
  375. throw new ArgumentNullException("name");
  376. }
  377. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  378. {
  379. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  380. }
  381. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  382. try
  383. {
  384. var user = InstantiateNewUser(name, true);
  385. var list = Users.ToList();
  386. list.Add(user);
  387. Users = list;
  388. user.DateLastSaved = DateTime.UtcNow;
  389. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  390. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  391. return user;
  392. }
  393. finally
  394. {
  395. _userListLock.Release();
  396. }
  397. }
  398. /// <summary>
  399. /// Deletes the user.
  400. /// </summary>
  401. /// <param name="user">The user.</param>
  402. /// <returns>Task.</returns>
  403. /// <exception cref="System.ArgumentNullException">user</exception>
  404. /// <exception cref="System.ArgumentException"></exception>
  405. public async Task DeleteUser(User user)
  406. {
  407. if (user == null)
  408. {
  409. throw new ArgumentNullException("user");
  410. }
  411. if (user.ConnectLinkType.HasValue)
  412. {
  413. await _connectFactory().RemoveConnect(user.Id.ToString("N")).ConfigureAwait(false);
  414. }
  415. var allUsers = Users.ToList();
  416. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  417. {
  418. throw new ArgumentException(string.Format("The user cannot be deleted because there is no user with the Name {0} and Id {1}.", user.Name, user.Id));
  419. }
  420. if (allUsers.Count == 1)
  421. {
  422. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  423. }
  424. if (user.Configuration.IsAdministrator && allUsers.Count(i => i.Configuration.IsAdministrator) == 1)
  425. {
  426. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one admin user in the system.", user.Name));
  427. }
  428. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  429. try
  430. {
  431. await UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  432. var path = user.ConfigurationFilePath;
  433. try
  434. {
  435. File.Delete(path);
  436. }
  437. catch (IOException ex)
  438. {
  439. _logger.ErrorException("Error deleting file {0}", ex, path);
  440. }
  441. // Force this to be lazy loaded again
  442. Users = await LoadUsers().ConfigureAwait(false);
  443. OnUserDeleted(user);
  444. }
  445. finally
  446. {
  447. _userListLock.Release();
  448. }
  449. }
  450. /// <summary>
  451. /// Resets the password by clearing it.
  452. /// </summary>
  453. /// <returns>Task.</returns>
  454. public Task ResetPassword(User user)
  455. {
  456. return ChangePassword(user, GetSha1String(string.Empty));
  457. }
  458. /// <summary>
  459. /// Changes the password.
  460. /// </summary>
  461. /// <param name="user">The user.</param>
  462. /// <param name="newPasswordSha1">The new password sha1.</param>
  463. /// <returns>Task.</returns>
  464. /// <exception cref="System.ArgumentNullException">
  465. /// user
  466. /// or
  467. /// newPassword
  468. /// </exception>
  469. /// <exception cref="System.ArgumentException">Passwords for guests cannot be changed.</exception>
  470. public async Task ChangePassword(User user, string newPasswordSha1)
  471. {
  472. if (user == null)
  473. {
  474. throw new ArgumentNullException("user");
  475. }
  476. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  477. {
  478. throw new ArgumentNullException("newPasswordSha1");
  479. }
  480. if (user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  481. {
  482. throw new ArgumentException("Passwords for guests cannot be changed.");
  483. }
  484. user.Password = newPasswordSha1;
  485. await UpdateUser(user).ConfigureAwait(false);
  486. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  487. }
  488. /// <summary>
  489. /// Instantiates the new user.
  490. /// </summary>
  491. /// <param name="name">The name.</param>
  492. /// <param name="checkId">if set to <c>true</c> [check identifier].</param>
  493. /// <returns>User.</returns>
  494. private User InstantiateNewUser(string name, bool checkId)
  495. {
  496. var id = ("MBUser" + name).GetMD5();
  497. if (checkId && Users.Select(i => i.Id).Contains(id))
  498. {
  499. id = Guid.NewGuid();
  500. }
  501. return new User
  502. {
  503. Name = name,
  504. Id = id,
  505. DateCreated = DateTime.UtcNow,
  506. DateModified = DateTime.UtcNow,
  507. UsesIdForConfigurationPath = true
  508. };
  509. }
  510. public void UpdateConfiguration(User user, UserConfiguration newConfiguration)
  511. {
  512. var xmlPath = user.ConfigurationFilePath;
  513. Directory.CreateDirectory(Path.GetDirectoryName(xmlPath));
  514. _xmlSerializer.SerializeToFile(newConfiguration, xmlPath);
  515. EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  516. }
  517. private string PasswordResetFile
  518. {
  519. get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); }
  520. }
  521. private string _lastPin;
  522. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  523. private int _pinAttempts;
  524. private PasswordPinCreationResult CreatePasswordResetPin()
  525. {
  526. var num = new Random().Next(1, 9999);
  527. var path = PasswordResetFile;
  528. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  529. _lastPin = pin;
  530. var time = TimeSpan.FromMinutes(5);
  531. var expiration = DateTime.UtcNow.Add(time);
  532. var text = new StringBuilder();
  533. var info = _appHost.GetSystemInfo();
  534. var localAddress = info.LocalAddress ?? string.Empty;
  535. text.AppendLine("Use your web browser to visit:");
  536. text.AppendLine(string.Empty);
  537. text.AppendLine(localAddress + "/mediabrowser/web/forgotpasswordpin.html");
  538. text.AppendLine(string.Empty);
  539. text.AppendLine("Enter the following pin code:");
  540. text.AppendLine(string.Empty);
  541. text.AppendLine(pin);
  542. text.AppendLine(string.Empty);
  543. text.AppendLine("The pin code will expire at " + expiration.ToLocalTime().ToShortDateString() + " " + expiration.ToLocalTime().ToShortTimeString());
  544. File.WriteAllText(path, text.ToString(), Encoding.UTF8);
  545. var result = new PasswordPinCreationResult
  546. {
  547. PinFile = path,
  548. ExpirationDate = expiration
  549. };
  550. _lastPasswordPinCreationResult = result;
  551. _pinAttempts = 0;
  552. return result;
  553. }
  554. public ForgotPasswordResult StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  555. {
  556. DeletePinFile();
  557. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  558. null :
  559. GetUserByName(enteredUsername);
  560. if (user != null && user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  561. {
  562. throw new ArgumentException("Unable to process forgot password request for guests.");
  563. }
  564. var action = ForgotPasswordAction.InNetworkRequired;
  565. string pinFile = null;
  566. DateTime? expirationDate = null;
  567. if (user != null && !user.Configuration.IsAdministrator)
  568. {
  569. action = ForgotPasswordAction.ContactAdmin;
  570. }
  571. else
  572. {
  573. if (isInNetwork)
  574. {
  575. action = ForgotPasswordAction.PinCode;
  576. }
  577. var result = CreatePasswordResetPin();
  578. pinFile = result.PinFile;
  579. expirationDate = result.ExpirationDate;
  580. }
  581. return new ForgotPasswordResult
  582. {
  583. Action = action,
  584. PinFile = pinFile,
  585. PinExpirationDate = expirationDate
  586. };
  587. }
  588. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  589. {
  590. DeletePinFile();
  591. var usersReset = new List<string>();
  592. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  593. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  594. _lastPasswordPinCreationResult != null &&
  595. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  596. if (valid)
  597. {
  598. _lastPin = null;
  599. _lastPasswordPinCreationResult = null;
  600. var users = Users.Where(i => !i.ConnectLinkType.HasValue || i.ConnectLinkType.Value != UserLinkType.Guest)
  601. .ToList();
  602. foreach (var user in users)
  603. {
  604. await ResetPassword(user).ConfigureAwait(false);
  605. usersReset.Add(user.Name);
  606. }
  607. }
  608. else
  609. {
  610. _pinAttempts++;
  611. if (_pinAttempts >= 3)
  612. {
  613. _lastPin = null;
  614. _lastPasswordPinCreationResult = null;
  615. }
  616. }
  617. return new PinRedeemResult
  618. {
  619. Success = valid,
  620. UsersReset = usersReset.ToArray()
  621. };
  622. }
  623. private void DeletePinFile()
  624. {
  625. try
  626. {
  627. File.Delete(PasswordResetFile);
  628. }
  629. catch
  630. {
  631. }
  632. }
  633. class PasswordPinCreationResult
  634. {
  635. public string PinFile { get; set; }
  636. public DateTime ExpirationDate { get; set; }
  637. }
  638. }
  639. }