UserManager.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Connect;
  6. using MediaBrowser.Controller.Drawing;
  7. using MediaBrowser.Controller.Dto;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Controller.Net;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Controller.Providers;
  13. using MediaBrowser.Model.Configuration;
  14. using MediaBrowser.Model.Connect;
  15. using MediaBrowser.Model.Dto;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.Events;
  18. using MediaBrowser.Model.Logging;
  19. using MediaBrowser.Model.Serialization;
  20. using MediaBrowser.Model.Users;
  21. using System;
  22. using System.Collections.Generic;
  23. using System.Globalization;
  24. using System.IO;
  25. using System.Linq;
  26. using System.Text;
  27. using System.Threading;
  28. using System.Threading.Tasks;
  29. using MediaBrowser.Model.Cryptography;
  30. using MediaBrowser.Model.IO;
  31. namespace Emby.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 IJsonSerializer _jsonSerializer;
  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. private readonly IFileSystem _fileSystem;
  66. private readonly ICryptographyProvider _cryptographyProvider;
  67. private readonly string _defaultUserName;
  68. public UserManager(ILogger logger, IServerConfigurationManager configurationManager, IUserRepository userRepository, IXmlSerializer xmlSerializer, INetworkManager networkManager, Func<IImageProcessor> imageProcessorFactory, Func<IDtoService> dtoServiceFactory, Func<IConnectManager> connectFactory, IServerApplicationHost appHost, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ICryptographyProvider cryptographyProvider, string defaultUserName)
  69. {
  70. _logger = logger;
  71. UserRepository = userRepository;
  72. _xmlSerializer = xmlSerializer;
  73. _networkManager = networkManager;
  74. _imageProcessorFactory = imageProcessorFactory;
  75. _dtoServiceFactory = dtoServiceFactory;
  76. _connectFactory = connectFactory;
  77. _appHost = appHost;
  78. _jsonSerializer = jsonSerializer;
  79. _fileSystem = fileSystem;
  80. _cryptographyProvider = cryptographyProvider;
  81. _defaultUserName = defaultUserName;
  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. public event EventHandler<GenericEventArgs<User>> UserLockedOut;
  93. /// <summary>
  94. /// Called when [user updated].
  95. /// </summary>
  96. /// <param name="user">The user.</param>
  97. private void OnUserUpdated(User user)
  98. {
  99. EventHelper.FireEventIfNotNull(UserUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  100. }
  101. #endregion
  102. #region UserDeleted Event
  103. /// <summary>
  104. /// Occurs when [user deleted].
  105. /// </summary>
  106. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  107. /// <summary>
  108. /// Called when [user deleted].
  109. /// </summary>
  110. /// <param name="user">The user.</param>
  111. private void OnUserDeleted(User user)
  112. {
  113. EventHelper.QueueEventIfNotNull(UserDeleted, this, new GenericEventArgs<User> { Argument = user }, _logger);
  114. }
  115. #endregion
  116. /// <summary>
  117. /// Gets a User by Id
  118. /// </summary>
  119. /// <param name="id">The id.</param>
  120. /// <returns>User.</returns>
  121. /// <exception cref="System.ArgumentNullException"></exception>
  122. public User GetUserById(Guid id)
  123. {
  124. if (id == Guid.Empty)
  125. {
  126. throw new ArgumentNullException("id");
  127. }
  128. return Users.FirstOrDefault(u => u.Id == id);
  129. }
  130. /// <summary>
  131. /// Gets the user by identifier.
  132. /// </summary>
  133. /// <param name="id">The identifier.</param>
  134. /// <returns>User.</returns>
  135. public User GetUserById(string id)
  136. {
  137. return GetUserById(new Guid(id));
  138. }
  139. public User GetUserByName(string name)
  140. {
  141. if (string.IsNullOrWhiteSpace(name))
  142. {
  143. throw new ArgumentNullException("name");
  144. }
  145. return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));
  146. }
  147. public async Task Initialize()
  148. {
  149. Users = await LoadUsers().ConfigureAwait(false);
  150. var users = Users.ToList();
  151. // If there are no local users with admin rights, make them all admins
  152. if (!users.Any(i => i.Policy.IsAdministrator))
  153. {
  154. foreach (var user in users)
  155. {
  156. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value == UserLinkType.LinkedUser)
  157. {
  158. user.Policy.IsAdministrator = true;
  159. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(false);
  160. }
  161. }
  162. }
  163. }
  164. public Task<bool> AuthenticateUser(string username, string passwordSha1, string remoteEndPoint)
  165. {
  166. return AuthenticateUser(username, passwordSha1, null, remoteEndPoint);
  167. }
  168. public bool IsValidUsername(string username)
  169. {
  170. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  171. foreach (var currentChar in username)
  172. {
  173. if (!IsValidUsernameCharacter(currentChar))
  174. {
  175. return false;
  176. }
  177. }
  178. return true;
  179. }
  180. private bool IsValidUsernameCharacter(char i)
  181. {
  182. return char.IsLetterOrDigit(i) || char.Equals(i, '-') || char.Equals(i, '_') || char.Equals(i, '\'') ||
  183. char.Equals(i, '.');
  184. }
  185. public string MakeValidUsername(string username)
  186. {
  187. if (IsValidUsername(username))
  188. {
  189. return username;
  190. }
  191. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  192. var builder = new StringBuilder();
  193. foreach (var c in username)
  194. {
  195. if (IsValidUsernameCharacter(c))
  196. {
  197. builder.Append(c);
  198. }
  199. }
  200. return builder.ToString();
  201. }
  202. public async Task<bool> AuthenticateUser(string username, string passwordSha1, string passwordMd5, string remoteEndPoint)
  203. {
  204. if (string.IsNullOrWhiteSpace(username))
  205. {
  206. throw new ArgumentNullException("username");
  207. }
  208. var user = Users
  209. .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  210. if (user == null)
  211. {
  212. throw new SecurityException("Invalid username or password entered.");
  213. }
  214. if (user.Policy.IsDisabled)
  215. {
  216. throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  217. }
  218. var success = false;
  219. // Authenticate using local credentials if not a guest
  220. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value != UserLinkType.Guest)
  221. {
  222. success = string.Equals(GetPasswordHash(user), passwordSha1.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  223. if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
  224. {
  225. success = string.Equals(GetLocalPasswordHash(user), passwordSha1.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  226. }
  227. }
  228. // Update LastActivityDate and LastLoginDate, then save
  229. if (success)
  230. {
  231. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  232. await UpdateUser(user).ConfigureAwait(false);
  233. await UpdateInvalidLoginAttemptCount(user, 0).ConfigureAwait(false);
  234. }
  235. else
  236. {
  237. await UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1).ConfigureAwait(false);
  238. }
  239. _logger.Info("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
  240. return success;
  241. }
  242. private async Task UpdateInvalidLoginAttemptCount(User user, int newValue)
  243. {
  244. if (user.Policy.InvalidLoginAttemptCount != newValue || newValue > 0)
  245. {
  246. user.Policy.InvalidLoginAttemptCount = newValue;
  247. var maxCount = user.Policy.IsAdministrator ?
  248. 3 :
  249. 5;
  250. var fireLockout = false;
  251. if (newValue >= maxCount)
  252. {
  253. //_logger.Debug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture));
  254. //user.Policy.IsDisabled = true;
  255. //fireLockout = true;
  256. }
  257. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(false);
  258. if (fireLockout)
  259. {
  260. if (UserLockedOut != null)
  261. {
  262. EventHelper.FireEventIfNotNull(UserLockedOut, this, new GenericEventArgs<User>(user), _logger);
  263. }
  264. }
  265. }
  266. }
  267. private string GetPasswordHash(User user)
  268. {
  269. return string.IsNullOrEmpty(user.Password)
  270. ? GetSha1String(string.Empty)
  271. : user.Password;
  272. }
  273. private string GetLocalPasswordHash(User user)
  274. {
  275. return string.IsNullOrEmpty(user.EasyPassword)
  276. ? GetSha1String(string.Empty)
  277. : user.EasyPassword;
  278. }
  279. private bool IsPasswordEmpty(string passwordHash)
  280. {
  281. return string.Equals(passwordHash, GetSha1String(string.Empty), StringComparison.OrdinalIgnoreCase);
  282. }
  283. /// <summary>
  284. /// Gets the sha1 string.
  285. /// </summary>
  286. /// <param name="str">The STR.</param>
  287. /// <returns>System.String.</returns>
  288. private string GetSha1String(string str)
  289. {
  290. return BitConverter.ToString(_cryptographyProvider.GetSHA1Bytes(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
  291. }
  292. /// <summary>
  293. /// Loads the users from the repository
  294. /// </summary>
  295. /// <returns>IEnumerable{User}.</returns>
  296. private async Task<IEnumerable<User>> LoadUsers()
  297. {
  298. var users = UserRepository.RetrieveAllUsers().ToList();
  299. // There always has to be at least one user.
  300. if (users.Count == 0)
  301. {
  302. var name = MakeValidUsername(_defaultUserName);
  303. var user = InstantiateNewUser(name);
  304. user.DateLastSaved = DateTime.UtcNow;
  305. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  306. users.Add(user);
  307. user.Policy.IsAdministrator = true;
  308. user.Policy.EnableContentDeletion = true;
  309. user.Policy.EnableRemoteControlOfOtherUsers = true;
  310. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(false);
  311. }
  312. return users;
  313. }
  314. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  315. {
  316. if (user == null)
  317. {
  318. throw new ArgumentNullException("user");
  319. }
  320. var passwordHash = GetPasswordHash(user);
  321. var hasConfiguredPassword = !IsPasswordEmpty(passwordHash);
  322. var hasConfiguredEasyPassword = !IsPasswordEmpty(GetLocalPasswordHash(user));
  323. var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  324. hasConfiguredEasyPassword :
  325. hasConfiguredPassword;
  326. var dto = new UserDto
  327. {
  328. Id = user.Id.ToString("N"),
  329. Name = user.Name,
  330. HasPassword = hasPassword,
  331. HasConfiguredPassword = hasConfiguredPassword,
  332. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  333. LastActivityDate = user.LastActivityDate,
  334. LastLoginDate = user.LastLoginDate,
  335. Configuration = user.Configuration,
  336. ConnectLinkType = user.ConnectLinkType,
  337. ConnectUserId = user.ConnectUserId,
  338. ConnectUserName = user.ConnectUserName,
  339. ServerId = _appHost.SystemId,
  340. Policy = user.Policy
  341. };
  342. var image = user.GetImageInfo(ImageType.Primary, 0);
  343. if (image != null)
  344. {
  345. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  346. try
  347. {
  348. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  349. }
  350. catch (Exception ex)
  351. {
  352. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  353. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  354. }
  355. }
  356. return dto;
  357. }
  358. public UserDto GetOfflineUserDto(User user)
  359. {
  360. var dto = GetUserDto(user);
  361. var offlinePasswordHash = GetLocalPasswordHash(user);
  362. dto.HasPassword = !IsPasswordEmpty(offlinePasswordHash);
  363. dto.OfflinePasswordSalt = Guid.NewGuid().ToString("N");
  364. // Hash the pin with the device Id to create a unique result for this device
  365. dto.OfflinePassword = GetSha1String((offlinePasswordHash + dto.OfflinePasswordSalt).ToLower());
  366. dto.ServerName = _appHost.FriendlyName;
  367. return dto;
  368. }
  369. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  370. {
  371. try
  372. {
  373. return _imageProcessorFactory().GetImageCacheTag(item, image);
  374. }
  375. catch (Exception ex)
  376. {
  377. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  378. return null;
  379. }
  380. }
  381. /// <summary>
  382. /// Refreshes metadata for each user
  383. /// </summary>
  384. /// <param name="cancellationToken">The cancellation token.</param>
  385. /// <returns>Task.</returns>
  386. public Task RefreshUsersMetadata(CancellationToken cancellationToken)
  387. {
  388. var tasks = Users.Select(user => user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken)).ToList();
  389. return Task.WhenAll(tasks);
  390. }
  391. /// <summary>
  392. /// Renames the user.
  393. /// </summary>
  394. /// <param name="user">The user.</param>
  395. /// <param name="newName">The new name.</param>
  396. /// <returns>Task.</returns>
  397. /// <exception cref="System.ArgumentNullException">user</exception>
  398. /// <exception cref="System.ArgumentException"></exception>
  399. public async Task RenameUser(User user, string newName)
  400. {
  401. if (user == null)
  402. {
  403. throw new ArgumentNullException("user");
  404. }
  405. if (string.IsNullOrEmpty(newName))
  406. {
  407. throw new ArgumentNullException("newName");
  408. }
  409. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  410. {
  411. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  412. }
  413. if (user.Name.Equals(newName, StringComparison.Ordinal))
  414. {
  415. throw new ArgumentException("The new and old names must be different.");
  416. }
  417. await user.Rename(newName);
  418. OnUserUpdated(user);
  419. }
  420. /// <summary>
  421. /// Updates the user.
  422. /// </summary>
  423. /// <param name="user">The user.</param>
  424. /// <exception cref="System.ArgumentNullException">user</exception>
  425. /// <exception cref="System.ArgumentException"></exception>
  426. public async Task UpdateUser(User user)
  427. {
  428. if (user == null)
  429. {
  430. throw new ArgumentNullException("user");
  431. }
  432. if (user.Id == Guid.Empty || !Users.Any(u => u.Id.Equals(user.Id)))
  433. {
  434. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  435. }
  436. user.DateModified = DateTime.UtcNow;
  437. user.DateLastSaved = DateTime.UtcNow;
  438. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  439. OnUserUpdated(user);
  440. }
  441. public event EventHandler<GenericEventArgs<User>> UserCreated;
  442. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  443. /// <summary>
  444. /// Creates the user.
  445. /// </summary>
  446. /// <param name="name">The name.</param>
  447. /// <returns>User.</returns>
  448. /// <exception cref="System.ArgumentNullException">name</exception>
  449. /// <exception cref="System.ArgumentException"></exception>
  450. public async Task<User> CreateUser(string name)
  451. {
  452. if (string.IsNullOrWhiteSpace(name))
  453. {
  454. throw new ArgumentNullException("name");
  455. }
  456. if (!IsValidUsername(name))
  457. {
  458. throw new ArgumentException("Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  459. }
  460. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  461. {
  462. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  463. }
  464. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  465. try
  466. {
  467. var user = InstantiateNewUser(name);
  468. var list = Users.ToList();
  469. list.Add(user);
  470. Users = list;
  471. user.DateLastSaved = DateTime.UtcNow;
  472. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  473. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  474. return user;
  475. }
  476. finally
  477. {
  478. _userListLock.Release();
  479. }
  480. }
  481. /// <summary>
  482. /// Deletes the user.
  483. /// </summary>
  484. /// <param name="user">The user.</param>
  485. /// <returns>Task.</returns>
  486. /// <exception cref="System.ArgumentNullException">user</exception>
  487. /// <exception cref="System.ArgumentException"></exception>
  488. public async Task DeleteUser(User user)
  489. {
  490. if (user == null)
  491. {
  492. throw new ArgumentNullException("user");
  493. }
  494. if (user.ConnectLinkType.HasValue)
  495. {
  496. await _connectFactory().RemoveConnect(user.Id.ToString("N")).ConfigureAwait(false);
  497. }
  498. var allUsers = Users.ToList();
  499. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  500. {
  501. 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));
  502. }
  503. if (allUsers.Count == 1)
  504. {
  505. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  506. }
  507. if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1)
  508. {
  509. 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));
  510. }
  511. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  512. try
  513. {
  514. var configPath = GetConfigurationFilePath(user);
  515. await UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  516. try
  517. {
  518. _fileSystem.DeleteFile(configPath);
  519. }
  520. catch (IOException ex)
  521. {
  522. _logger.ErrorException("Error deleting file {0}", ex, configPath);
  523. }
  524. DeleteUserPolicy(user);
  525. // Force this to be lazy loaded again
  526. Users = await LoadUsers().ConfigureAwait(false);
  527. OnUserDeleted(user);
  528. }
  529. finally
  530. {
  531. _userListLock.Release();
  532. }
  533. }
  534. /// <summary>
  535. /// Resets the password by clearing it.
  536. /// </summary>
  537. /// <returns>Task.</returns>
  538. public Task ResetPassword(User user)
  539. {
  540. return ChangePassword(user, GetSha1String(string.Empty));
  541. }
  542. public Task ResetEasyPassword(User user)
  543. {
  544. return ChangeEasyPassword(user, GetSha1String(string.Empty));
  545. }
  546. public async Task ChangePassword(User user, string newPasswordSha1)
  547. {
  548. if (user == null)
  549. {
  550. throw new ArgumentNullException("user");
  551. }
  552. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  553. {
  554. throw new ArgumentNullException("newPasswordSha1");
  555. }
  556. if (user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  557. {
  558. throw new ArgumentException("Passwords for guests cannot be changed.");
  559. }
  560. user.Password = newPasswordSha1;
  561. await UpdateUser(user).ConfigureAwait(false);
  562. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  563. }
  564. public async Task ChangeEasyPassword(User user, string newPasswordSha1)
  565. {
  566. if (user == null)
  567. {
  568. throw new ArgumentNullException("user");
  569. }
  570. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  571. {
  572. throw new ArgumentNullException("newPasswordSha1");
  573. }
  574. user.EasyPassword = newPasswordSha1;
  575. await UpdateUser(user).ConfigureAwait(false);
  576. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  577. }
  578. /// <summary>
  579. /// Instantiates the new user.
  580. /// </summary>
  581. /// <param name="name">The name.</param>
  582. /// <returns>User.</returns>
  583. private User InstantiateNewUser(string name)
  584. {
  585. return new User
  586. {
  587. Name = name,
  588. Id = Guid.NewGuid(),
  589. DateCreated = DateTime.UtcNow,
  590. DateModified = DateTime.UtcNow,
  591. UsesIdForConfigurationPath = true
  592. };
  593. }
  594. private string PasswordResetFile
  595. {
  596. get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); }
  597. }
  598. private string _lastPin;
  599. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  600. private int _pinAttempts;
  601. private PasswordPinCreationResult CreatePasswordResetPin()
  602. {
  603. var num = new Random().Next(1, 9999);
  604. var path = PasswordResetFile;
  605. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  606. _lastPin = pin;
  607. var time = TimeSpan.FromMinutes(5);
  608. var expiration = DateTime.UtcNow.Add(time);
  609. var text = new StringBuilder();
  610. var localAddress = _appHost.GetLocalApiUrl().Result ?? string.Empty;
  611. text.AppendLine("Use your web browser to visit:");
  612. text.AppendLine(string.Empty);
  613. text.AppendLine(localAddress + "/web/forgotpasswordpin.html");
  614. text.AppendLine(string.Empty);
  615. text.AppendLine("Enter the following pin code:");
  616. text.AppendLine(string.Empty);
  617. text.AppendLine(pin);
  618. text.AppendLine(string.Empty);
  619. var localExpirationTime = expiration.ToLocalTime();
  620. // Tuesday, 22 August 2006 06:30 AM
  621. text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
  622. _fileSystem.WriteAllText(path, text.ToString(), Encoding.UTF8);
  623. var result = new PasswordPinCreationResult
  624. {
  625. PinFile = path,
  626. ExpirationDate = expiration
  627. };
  628. _lastPasswordPinCreationResult = result;
  629. _pinAttempts = 0;
  630. return result;
  631. }
  632. public ForgotPasswordResult StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  633. {
  634. DeletePinFile();
  635. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  636. null :
  637. GetUserByName(enteredUsername);
  638. if (user != null && user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  639. {
  640. throw new ArgumentException("Unable to process forgot password request for guests.");
  641. }
  642. var action = ForgotPasswordAction.InNetworkRequired;
  643. string pinFile = null;
  644. DateTime? expirationDate = null;
  645. if (user != null && !user.Policy.IsAdministrator)
  646. {
  647. action = ForgotPasswordAction.ContactAdmin;
  648. }
  649. else
  650. {
  651. if (isInNetwork)
  652. {
  653. action = ForgotPasswordAction.PinCode;
  654. }
  655. var result = CreatePasswordResetPin();
  656. pinFile = result.PinFile;
  657. expirationDate = result.ExpirationDate;
  658. }
  659. return new ForgotPasswordResult
  660. {
  661. Action = action,
  662. PinFile = pinFile,
  663. PinExpirationDate = expirationDate
  664. };
  665. }
  666. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  667. {
  668. DeletePinFile();
  669. var usersReset = new List<string>();
  670. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  671. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  672. _lastPasswordPinCreationResult != null &&
  673. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  674. if (valid)
  675. {
  676. _lastPin = null;
  677. _lastPasswordPinCreationResult = null;
  678. var users = Users.Where(i => !i.ConnectLinkType.HasValue || i.ConnectLinkType.Value != UserLinkType.Guest)
  679. .ToList();
  680. foreach (var user in users)
  681. {
  682. await ResetPassword(user).ConfigureAwait(false);
  683. if (user.Policy.IsDisabled)
  684. {
  685. user.Policy.IsDisabled = false;
  686. await UpdateUserPolicy(user, user.Policy, true).ConfigureAwait(false);
  687. }
  688. usersReset.Add(user.Name);
  689. }
  690. }
  691. else
  692. {
  693. _pinAttempts++;
  694. if (_pinAttempts >= 3)
  695. {
  696. _lastPin = null;
  697. _lastPasswordPinCreationResult = null;
  698. }
  699. }
  700. return new PinRedeemResult
  701. {
  702. Success = valid,
  703. UsersReset = usersReset.ToArray()
  704. };
  705. }
  706. private void DeletePinFile()
  707. {
  708. try
  709. {
  710. _fileSystem.DeleteFile(PasswordResetFile);
  711. }
  712. catch
  713. {
  714. }
  715. }
  716. class PasswordPinCreationResult
  717. {
  718. public string PinFile { get; set; }
  719. public DateTime ExpirationDate { get; set; }
  720. }
  721. public UserPolicy GetUserPolicy(User user)
  722. {
  723. var path = GetPolifyFilePath(user);
  724. try
  725. {
  726. lock (_policySyncLock)
  727. {
  728. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  729. }
  730. }
  731. catch (FileNotFoundException)
  732. {
  733. return GetDefaultPolicy(user);
  734. }
  735. catch (IOException)
  736. {
  737. return GetDefaultPolicy(user);
  738. }
  739. catch (Exception ex)
  740. {
  741. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  742. return GetDefaultPolicy(user);
  743. }
  744. }
  745. private UserPolicy GetDefaultPolicy(User user)
  746. {
  747. return new UserPolicy
  748. {
  749. EnableSync = true
  750. };
  751. }
  752. private readonly object _policySyncLock = new object();
  753. public Task UpdateUserPolicy(string userId, UserPolicy userPolicy)
  754. {
  755. var user = GetUserById(userId);
  756. return UpdateUserPolicy(user, userPolicy, true);
  757. }
  758. private async Task UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  759. {
  760. // The xml serializer will output differently if the type is not exact
  761. if (userPolicy.GetType() != typeof(UserPolicy))
  762. {
  763. var json = _jsonSerializer.SerializeToString(userPolicy);
  764. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  765. }
  766. var path = GetPolifyFilePath(user);
  767. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  768. lock (_policySyncLock)
  769. {
  770. _xmlSerializer.SerializeToFile(userPolicy, path);
  771. user.Policy = userPolicy;
  772. }
  773. await UpdateConfiguration(user, user.Configuration, true).ConfigureAwait(false);
  774. }
  775. private void DeleteUserPolicy(User user)
  776. {
  777. var path = GetPolifyFilePath(user);
  778. try
  779. {
  780. lock (_policySyncLock)
  781. {
  782. _fileSystem.DeleteFile(path);
  783. }
  784. }
  785. catch (IOException)
  786. {
  787. }
  788. catch (Exception ex)
  789. {
  790. _logger.ErrorException("Error deleting policy file", ex);
  791. }
  792. }
  793. private string GetPolifyFilePath(User user)
  794. {
  795. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  796. }
  797. private string GetConfigurationFilePath(User user)
  798. {
  799. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  800. }
  801. public UserConfiguration GetUserConfiguration(User user)
  802. {
  803. var path = GetConfigurationFilePath(user);
  804. try
  805. {
  806. lock (_configSyncLock)
  807. {
  808. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  809. }
  810. }
  811. catch (FileNotFoundException)
  812. {
  813. return new UserConfiguration();
  814. }
  815. catch (IOException)
  816. {
  817. return new UserConfiguration();
  818. }
  819. catch (Exception ex)
  820. {
  821. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  822. return new UserConfiguration();
  823. }
  824. }
  825. private readonly object _configSyncLock = new object();
  826. public Task UpdateConfiguration(string userId, UserConfiguration config)
  827. {
  828. var user = GetUserById(userId);
  829. return UpdateConfiguration(user, config, true);
  830. }
  831. private async Task UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  832. {
  833. var path = GetConfigurationFilePath(user);
  834. // The xml serializer will output differently if the type is not exact
  835. if (config.GetType() != typeof(UserConfiguration))
  836. {
  837. var json = _jsonSerializer.SerializeToString(config);
  838. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  839. }
  840. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  841. lock (_configSyncLock)
  842. {
  843. _xmlSerializer.SerializeToFile(config, path);
  844. user.Configuration = config;
  845. }
  846. if (fireEvent)
  847. {
  848. EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  849. }
  850. }
  851. }
  852. }