UserManager.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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.Querying;
  21. using MediaBrowser.Model.Serialization;
  22. using MediaBrowser.Model.Users;
  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 SecurityException("Invalid username or password entered.");
  163. }
  164. if (user.Configuration.IsDisabled)
  165. {
  166. throw new SecurityException(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, new List<ItemFields>
  281. {
  282. ItemFields.PrimaryImageAspectRatio
  283. });
  284. }
  285. catch (Exception ex)
  286. {
  287. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  288. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  289. }
  290. }
  291. return dto;
  292. }
  293. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  294. {
  295. try
  296. {
  297. return _imageProcessorFactory().GetImageCacheTag(item, image);
  298. }
  299. catch (Exception ex)
  300. {
  301. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  302. return null;
  303. }
  304. }
  305. /// <summary>
  306. /// Refreshes metadata for each user
  307. /// </summary>
  308. /// <param name="cancellationToken">The cancellation token.</param>
  309. /// <returns>Task.</returns>
  310. public Task RefreshUsersMetadata(CancellationToken cancellationToken)
  311. {
  312. var tasks = Users.Select(user => user.RefreshMetadata(new MetadataRefreshOptions(), cancellationToken)).ToList();
  313. return Task.WhenAll(tasks);
  314. }
  315. /// <summary>
  316. /// Renames the user.
  317. /// </summary>
  318. /// <param name="user">The user.</param>
  319. /// <param name="newName">The new name.</param>
  320. /// <returns>Task.</returns>
  321. /// <exception cref="System.ArgumentNullException">user</exception>
  322. /// <exception cref="System.ArgumentException"></exception>
  323. public async Task RenameUser(User user, string newName)
  324. {
  325. if (user == null)
  326. {
  327. throw new ArgumentNullException("user");
  328. }
  329. if (string.IsNullOrEmpty(newName))
  330. {
  331. throw new ArgumentNullException("newName");
  332. }
  333. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  334. {
  335. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  336. }
  337. if (user.Name.Equals(newName, StringComparison.Ordinal))
  338. {
  339. throw new ArgumentException("The new and old names must be different.");
  340. }
  341. await user.Rename(newName);
  342. OnUserUpdated(user);
  343. }
  344. /// <summary>
  345. /// Updates the user.
  346. /// </summary>
  347. /// <param name="user">The user.</param>
  348. /// <exception cref="System.ArgumentNullException">user</exception>
  349. /// <exception cref="System.ArgumentException"></exception>
  350. public async Task UpdateUser(User user)
  351. {
  352. if (user == null)
  353. {
  354. throw new ArgumentNullException("user");
  355. }
  356. if (user.Id == Guid.Empty || !Users.Any(u => u.Id.Equals(user.Id)))
  357. {
  358. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  359. }
  360. user.DateModified = DateTime.UtcNow;
  361. user.DateLastSaved = DateTime.UtcNow;
  362. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  363. OnUserUpdated(user);
  364. }
  365. public event EventHandler<GenericEventArgs<User>> UserCreated;
  366. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  367. /// <summary>
  368. /// Creates the user.
  369. /// </summary>
  370. /// <param name="name">The name.</param>
  371. /// <returns>User.</returns>
  372. /// <exception cref="System.ArgumentNullException">name</exception>
  373. /// <exception cref="System.ArgumentException"></exception>
  374. public async Task<User> CreateUser(string name)
  375. {
  376. if (string.IsNullOrWhiteSpace(name))
  377. {
  378. throw new ArgumentNullException("name");
  379. }
  380. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  381. {
  382. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  383. }
  384. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  385. try
  386. {
  387. var user = InstantiateNewUser(name, true);
  388. var list = Users.ToList();
  389. list.Add(user);
  390. Users = list;
  391. user.DateLastSaved = DateTime.UtcNow;
  392. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  393. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  394. return user;
  395. }
  396. finally
  397. {
  398. _userListLock.Release();
  399. }
  400. }
  401. /// <summary>
  402. /// Deletes the user.
  403. /// </summary>
  404. /// <param name="user">The user.</param>
  405. /// <returns>Task.</returns>
  406. /// <exception cref="System.ArgumentNullException">user</exception>
  407. /// <exception cref="System.ArgumentException"></exception>
  408. public async Task DeleteUser(User user)
  409. {
  410. if (user == null)
  411. {
  412. throw new ArgumentNullException("user");
  413. }
  414. if (user.ConnectLinkType.HasValue)
  415. {
  416. await _connectFactory().RemoveConnect(user.Id.ToString("N")).ConfigureAwait(false);
  417. }
  418. var allUsers = Users.ToList();
  419. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  420. {
  421. 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));
  422. }
  423. if (allUsers.Count == 1)
  424. {
  425. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  426. }
  427. if (user.Configuration.IsAdministrator && allUsers.Count(i => i.Configuration.IsAdministrator) == 1)
  428. {
  429. 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));
  430. }
  431. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  432. try
  433. {
  434. await UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  435. var path = user.ConfigurationFilePath;
  436. try
  437. {
  438. File.Delete(path);
  439. }
  440. catch (IOException ex)
  441. {
  442. _logger.ErrorException("Error deleting file {0}", ex, path);
  443. }
  444. // Force this to be lazy loaded again
  445. Users = await LoadUsers().ConfigureAwait(false);
  446. OnUserDeleted(user);
  447. }
  448. finally
  449. {
  450. _userListLock.Release();
  451. }
  452. }
  453. /// <summary>
  454. /// Resets the password by clearing it.
  455. /// </summary>
  456. /// <returns>Task.</returns>
  457. public Task ResetPassword(User user)
  458. {
  459. return ChangePassword(user, GetSha1String(string.Empty));
  460. }
  461. /// <summary>
  462. /// Changes the password.
  463. /// </summary>
  464. /// <param name="user">The user.</param>
  465. /// <param name="newPasswordSha1">The new password sha1.</param>
  466. /// <returns>Task.</returns>
  467. /// <exception cref="System.ArgumentNullException">
  468. /// user
  469. /// or
  470. /// newPassword
  471. /// </exception>
  472. /// <exception cref="System.ArgumentException">Passwords for guests cannot be changed.</exception>
  473. public async Task ChangePassword(User user, string newPasswordSha1)
  474. {
  475. if (user == null)
  476. {
  477. throw new ArgumentNullException("user");
  478. }
  479. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  480. {
  481. throw new ArgumentNullException("newPasswordSha1");
  482. }
  483. if (user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  484. {
  485. throw new ArgumentException("Passwords for guests cannot be changed.");
  486. }
  487. user.Password = newPasswordSha1;
  488. await UpdateUser(user).ConfigureAwait(false);
  489. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  490. }
  491. /// <summary>
  492. /// Instantiates the new user.
  493. /// </summary>
  494. /// <param name="name">The name.</param>
  495. /// <param name="checkId">if set to <c>true</c> [check identifier].</param>
  496. /// <returns>User.</returns>
  497. private User InstantiateNewUser(string name, bool checkId)
  498. {
  499. var id = ("MBUser" + name).GetMD5();
  500. if (checkId && Users.Select(i => i.Id).Contains(id))
  501. {
  502. id = Guid.NewGuid();
  503. }
  504. return new User
  505. {
  506. Name = name,
  507. Id = id,
  508. DateCreated = DateTime.UtcNow,
  509. DateModified = DateTime.UtcNow,
  510. UsesIdForConfigurationPath = true
  511. };
  512. }
  513. public void UpdateConfiguration(User user, UserConfiguration newConfiguration)
  514. {
  515. var xmlPath = user.ConfigurationFilePath;
  516. Directory.CreateDirectory(Path.GetDirectoryName(xmlPath));
  517. _xmlSerializer.SerializeToFile(newConfiguration, xmlPath);
  518. EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  519. }
  520. private string PasswordResetFile
  521. {
  522. get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); }
  523. }
  524. private string _lastPin;
  525. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  526. private int _pinAttempts;
  527. private PasswordPinCreationResult CreatePasswordResetPin()
  528. {
  529. var num = new Random().Next(1, 9999);
  530. var path = PasswordResetFile;
  531. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  532. _lastPin = pin;
  533. var time = TimeSpan.FromMinutes(5);
  534. var expiration = DateTime.UtcNow.Add(time);
  535. var text = new StringBuilder();
  536. var info = _appHost.GetSystemInfo();
  537. var localAddress = info.LocalAddress ?? string.Empty;
  538. text.AppendLine("Use your web browser to visit:");
  539. text.AppendLine(string.Empty);
  540. text.AppendLine(localAddress + "/mediabrowser/web/forgotpasswordpin.html");
  541. text.AppendLine(string.Empty);
  542. text.AppendLine("Enter the following pin code:");
  543. text.AppendLine(string.Empty);
  544. text.AppendLine(pin);
  545. text.AppendLine(string.Empty);
  546. text.AppendLine("The pin code will expire at " + expiration.ToLocalTime().ToShortDateString() + " " + expiration.ToLocalTime().ToShortTimeString());
  547. File.WriteAllText(path, text.ToString(), Encoding.UTF8);
  548. var result = new PasswordPinCreationResult
  549. {
  550. PinFile = path,
  551. ExpirationDate = expiration
  552. };
  553. _lastPasswordPinCreationResult = result;
  554. _pinAttempts = 0;
  555. return result;
  556. }
  557. public ForgotPasswordResult StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  558. {
  559. DeletePinFile();
  560. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  561. null :
  562. GetUserByName(enteredUsername);
  563. if (user != null && user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  564. {
  565. throw new ArgumentException("Unable to process forgot password request for guests.");
  566. }
  567. var action = ForgotPasswordAction.InNetworkRequired;
  568. string pinFile = null;
  569. DateTime? expirationDate = null;
  570. if (user != null && !user.Configuration.IsAdministrator)
  571. {
  572. action = ForgotPasswordAction.ContactAdmin;
  573. }
  574. else
  575. {
  576. if (isInNetwork)
  577. {
  578. action = ForgotPasswordAction.PinCode;
  579. }
  580. var result = CreatePasswordResetPin();
  581. pinFile = result.PinFile;
  582. expirationDate = result.ExpirationDate;
  583. }
  584. return new ForgotPasswordResult
  585. {
  586. Action = action,
  587. PinFile = pinFile,
  588. PinExpirationDate = expirationDate
  589. };
  590. }
  591. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  592. {
  593. DeletePinFile();
  594. var usersReset = new List<string>();
  595. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  596. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  597. _lastPasswordPinCreationResult != null &&
  598. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  599. if (valid)
  600. {
  601. _lastPin = null;
  602. _lastPasswordPinCreationResult = null;
  603. var users = Users.Where(i => !i.ConnectLinkType.HasValue || i.ConnectLinkType.Value != UserLinkType.Guest)
  604. .ToList();
  605. foreach (var user in users)
  606. {
  607. await ResetPassword(user).ConfigureAwait(false);
  608. usersReset.Add(user.Name);
  609. }
  610. }
  611. else
  612. {
  613. _pinAttempts++;
  614. if (_pinAttempts >= 3)
  615. {
  616. _lastPin = null;
  617. _lastPasswordPinCreationResult = null;
  618. }
  619. }
  620. return new PinRedeemResult
  621. {
  622. Success = valid,
  623. UsersReset = usersReset.ToArray()
  624. };
  625. }
  626. private void DeletePinFile()
  627. {
  628. try
  629. {
  630. File.Delete(PasswordResetFile);
  631. }
  632. catch
  633. {
  634. }
  635. }
  636. class PasswordPinCreationResult
  637. {
  638. public string PinFile { get; set; }
  639. public DateTime ExpirationDate { get; set; }
  640. }
  641. public UserPolicy GetUserPolicy(string userId)
  642. {
  643. throw new NotImplementedException();
  644. }
  645. public Task UpdateUserPolicy(string userId, UserPolicy userPolicy)
  646. {
  647. throw new NotImplementedException();
  648. }
  649. }
  650. }