UserManager.cs 35 KB

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