UserManager.cs 26 KB

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