UserManager.cs 35 KB

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