UserManager.cs 35 KB

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