UserManager.cs 35 KB

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