UserManager.cs 28 KB

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