UserManager.cs 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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. using CommonIO;
  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. // If there are no local users with admin rights, make them all admins
  151. if (!users.Any(i => i.Policy.IsAdministrator))
  152. {
  153. foreach (var user in users)
  154. {
  155. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value == UserLinkType.LinkedUser)
  156. {
  157. user.Policy.IsAdministrator = true;
  158. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(false);
  159. }
  160. }
  161. }
  162. }
  163. public Task<bool> AuthenticateUser(string username, string passwordSha1, string remoteEndPoint)
  164. {
  165. return AuthenticateUser(username, passwordSha1, null, remoteEndPoint);
  166. }
  167. public bool IsValidUsername(string username)
  168. {
  169. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  170. return username.All(IsValidUsernameCharacter);
  171. }
  172. private bool IsValidUsernameCharacter(char i)
  173. {
  174. return char.IsLetterOrDigit(i) || char.Equals(i, '-') || char.Equals(i, '_') || char.Equals(i, '\'') ||
  175. char.Equals(i, '.');
  176. }
  177. public string MakeValidUsername(string username)
  178. {
  179. if (IsValidUsername(username))
  180. {
  181. return username;
  182. }
  183. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  184. var builder = new StringBuilder();
  185. foreach (var c in username)
  186. {
  187. if (IsValidUsernameCharacter(c))
  188. {
  189. builder.Append(c);
  190. }
  191. }
  192. return builder.ToString();
  193. }
  194. public async Task<bool> AuthenticateUser(string username, string passwordSha1, string passwordMd5, string remoteEndPoint)
  195. {
  196. if (string.IsNullOrWhiteSpace(username))
  197. {
  198. throw new ArgumentNullException("username");
  199. }
  200. var user = Users
  201. .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  202. if (user == null)
  203. {
  204. throw new SecurityException("Invalid username or password entered.");
  205. }
  206. if (user.Policy.IsDisabled)
  207. {
  208. throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  209. }
  210. var success = false;
  211. // Authenticate using local credentials if not a guest
  212. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value != UserLinkType.Guest)
  213. {
  214. success = string.Equals(GetPasswordHash(user), passwordSha1.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  215. if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
  216. {
  217. success = string.Equals(GetLocalPasswordHash(user), passwordSha1.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  218. }
  219. }
  220. // Update LastActivityDate and LastLoginDate, then save
  221. if (success)
  222. {
  223. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  224. await UpdateUser(user).ConfigureAwait(false);
  225. await UpdateInvalidLoginAttemptCount(user, 0).ConfigureAwait(false);
  226. }
  227. else
  228. {
  229. await UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1).ConfigureAwait(false);
  230. }
  231. _logger.Info("Authentication request for {0} {1}.", user.Name, (success ? "has succeeded" : "has been denied"));
  232. return success;
  233. }
  234. private async Task UpdateInvalidLoginAttemptCount(User user, int newValue)
  235. {
  236. if (user.Policy.InvalidLoginAttemptCount != newValue || newValue > 0)
  237. {
  238. user.Policy.InvalidLoginAttemptCount = newValue;
  239. var maxCount = user.Policy.IsAdministrator ?
  240. 3 :
  241. 5;
  242. var fireLockout = false;
  243. if (newValue >= maxCount)
  244. {
  245. //_logger.Debug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture));
  246. //user.Policy.IsDisabled = true;
  247. //fireLockout = true;
  248. }
  249. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(false);
  250. if (fireLockout)
  251. {
  252. if (UserLockedOut != null)
  253. {
  254. EventHelper.FireEventIfNotNull(UserLockedOut, this, new GenericEventArgs<User>(user), _logger);
  255. }
  256. }
  257. }
  258. }
  259. private string GetPasswordHash(User user)
  260. {
  261. return string.IsNullOrEmpty(user.Password)
  262. ? GetSha1String(string.Empty)
  263. : user.Password;
  264. }
  265. private string GetLocalPasswordHash(User user)
  266. {
  267. return string.IsNullOrEmpty(user.EasyPassword)
  268. ? GetSha1String(string.Empty)
  269. : user.EasyPassword;
  270. }
  271. private bool IsPasswordEmpty(string passwordHash)
  272. {
  273. return string.Equals(passwordHash, GetSha1String(string.Empty), StringComparison.OrdinalIgnoreCase);
  274. }
  275. /// <summary>
  276. /// Gets the sha1 string.
  277. /// </summary>
  278. /// <param name="str">The STR.</param>
  279. /// <returns>System.String.</returns>
  280. private static string GetSha1String(string str)
  281. {
  282. using (var provider = SHA1.Create())
  283. {
  284. var hash = provider.ComputeHash(Encoding.UTF8.GetBytes(str));
  285. return BitConverter.ToString(hash).Replace("-", string.Empty);
  286. }
  287. }
  288. /// <summary>
  289. /// Loads the users from the repository
  290. /// </summary>
  291. /// <returns>IEnumerable{User}.</returns>
  292. private async Task<IEnumerable<User>> LoadUsers()
  293. {
  294. var users = UserRepository.RetrieveAllUsers().ToList();
  295. // There always has to be at least one user.
  296. if (users.Count == 0)
  297. {
  298. var name = MakeValidUsername(Environment.UserName);
  299. var user = InstantiateNewUser(name);
  300. user.DateLastSaved = DateTime.UtcNow;
  301. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  302. users.Add(user);
  303. user.Policy.IsAdministrator = true;
  304. user.Policy.EnableRemoteControlOfOtherUsers = true;
  305. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(false);
  306. }
  307. return users;
  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(_fileSystem), 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);
  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. /// <returns>User.</returns>
  581. private User InstantiateNewUser(string name)
  582. {
  583. return new User
  584. {
  585. Name = name,
  586. Id = Guid.NewGuid(),
  587. DateCreated = DateTime.UtcNow,
  588. DateModified = DateTime.UtcNow,
  589. UsesIdForConfigurationPath = true
  590. };
  591. }
  592. private string PasswordResetFile
  593. {
  594. get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); }
  595. }
  596. private string _lastPin;
  597. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  598. private int _pinAttempts;
  599. private PasswordPinCreationResult CreatePasswordResetPin()
  600. {
  601. var num = new Random().Next(1, 9999);
  602. var path = PasswordResetFile;
  603. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  604. _lastPin = pin;
  605. var time = TimeSpan.FromMinutes(5);
  606. var expiration = DateTime.UtcNow.Add(time);
  607. var text = new StringBuilder();
  608. var localAddress = _appHost.LocalApiUrl ?? string.Empty;
  609. text.AppendLine("Use your web browser to visit:");
  610. text.AppendLine(string.Empty);
  611. text.AppendLine(localAddress + "/web/forgotpasswordpin.html");
  612. text.AppendLine(string.Empty);
  613. text.AppendLine("Enter the following pin code:");
  614. text.AppendLine(string.Empty);
  615. text.AppendLine(pin);
  616. text.AppendLine(string.Empty);
  617. text.AppendLine("The pin code will expire at " + expiration.ToLocalTime().ToShortDateString() + " " + expiration.ToLocalTime().ToShortTimeString());
  618. _fileSystem.WriteAllText(path, text.ToString(), Encoding.UTF8);
  619. var result = new PasswordPinCreationResult
  620. {
  621. PinFile = path,
  622. ExpirationDate = expiration
  623. };
  624. _lastPasswordPinCreationResult = result;
  625. _pinAttempts = 0;
  626. return result;
  627. }
  628. public ForgotPasswordResult StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  629. {
  630. DeletePinFile();
  631. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  632. null :
  633. GetUserByName(enteredUsername);
  634. if (user != null && user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  635. {
  636. throw new ArgumentException("Unable to process forgot password request for guests.");
  637. }
  638. var action = ForgotPasswordAction.InNetworkRequired;
  639. string pinFile = null;
  640. DateTime? expirationDate = null;
  641. if (user != null && !user.Policy.IsAdministrator)
  642. {
  643. action = ForgotPasswordAction.ContactAdmin;
  644. }
  645. else
  646. {
  647. if (isInNetwork)
  648. {
  649. action = ForgotPasswordAction.PinCode;
  650. }
  651. var result = CreatePasswordResetPin();
  652. pinFile = result.PinFile;
  653. expirationDate = result.ExpirationDate;
  654. }
  655. return new ForgotPasswordResult
  656. {
  657. Action = action,
  658. PinFile = pinFile,
  659. PinExpirationDate = expirationDate
  660. };
  661. }
  662. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  663. {
  664. DeletePinFile();
  665. var usersReset = new List<string>();
  666. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  667. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  668. _lastPasswordPinCreationResult != null &&
  669. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  670. if (valid)
  671. {
  672. _lastPin = null;
  673. _lastPasswordPinCreationResult = null;
  674. var users = Users.Where(i => !i.ConnectLinkType.HasValue || i.ConnectLinkType.Value != UserLinkType.Guest)
  675. .ToList();
  676. foreach (var user in users)
  677. {
  678. await ResetPassword(user).ConfigureAwait(false);
  679. if (user.Policy.IsDisabled)
  680. {
  681. user.Policy.IsDisabled = false;
  682. await UpdateUserPolicy(user, user.Policy, true).ConfigureAwait(false);
  683. }
  684. usersReset.Add(user.Name);
  685. }
  686. }
  687. else
  688. {
  689. _pinAttempts++;
  690. if (_pinAttempts >= 3)
  691. {
  692. _lastPin = null;
  693. _lastPasswordPinCreationResult = null;
  694. }
  695. }
  696. return new PinRedeemResult
  697. {
  698. Success = valid,
  699. UsersReset = usersReset.ToArray()
  700. };
  701. }
  702. private void DeletePinFile()
  703. {
  704. try
  705. {
  706. _fileSystem.DeleteFile(PasswordResetFile);
  707. }
  708. catch
  709. {
  710. }
  711. }
  712. class PasswordPinCreationResult
  713. {
  714. public string PinFile { get; set; }
  715. public DateTime ExpirationDate { get; set; }
  716. }
  717. public UserPolicy GetUserPolicy(User user)
  718. {
  719. var path = GetPolifyFilePath(user);
  720. try
  721. {
  722. lock (_policySyncLock)
  723. {
  724. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  725. }
  726. }
  727. catch (DirectoryNotFoundException)
  728. {
  729. return GetDefaultPolicy(user);
  730. }
  731. catch (FileNotFoundException)
  732. {
  733. return GetDefaultPolicy(user);
  734. }
  735. catch (Exception ex)
  736. {
  737. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  738. return GetDefaultPolicy(user);
  739. }
  740. }
  741. private UserPolicy GetDefaultPolicy(User user)
  742. {
  743. return new UserPolicy
  744. {
  745. EnableSync = true
  746. };
  747. }
  748. private readonly object _policySyncLock = new object();
  749. public Task UpdateUserPolicy(string userId, UserPolicy userPolicy)
  750. {
  751. var user = GetUserById(userId);
  752. return UpdateUserPolicy(user, userPolicy, true);
  753. }
  754. private async Task UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  755. {
  756. // The xml serializer will output differently if the type is not exact
  757. if (userPolicy.GetType() != typeof(UserPolicy))
  758. {
  759. var json = _jsonSerializer.SerializeToString(userPolicy);
  760. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  761. }
  762. var path = GetPolifyFilePath(user);
  763. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  764. lock (_policySyncLock)
  765. {
  766. _xmlSerializer.SerializeToFile(userPolicy, path);
  767. user.Policy = userPolicy;
  768. }
  769. await UpdateConfiguration(user, user.Configuration, true).ConfigureAwait(false);
  770. }
  771. private void DeleteUserPolicy(User user)
  772. {
  773. var path = GetPolifyFilePath(user);
  774. try
  775. {
  776. lock (_policySyncLock)
  777. {
  778. _fileSystem.DeleteFile(path);
  779. }
  780. }
  781. catch (IOException)
  782. {
  783. }
  784. catch (Exception ex)
  785. {
  786. _logger.ErrorException("Error deleting policy file", ex);
  787. }
  788. }
  789. private string GetPolifyFilePath(User user)
  790. {
  791. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  792. }
  793. private string GetConfigurationFilePath(User user)
  794. {
  795. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  796. }
  797. public UserConfiguration GetUserConfiguration(User user)
  798. {
  799. var path = GetConfigurationFilePath(user);
  800. try
  801. {
  802. lock (_configSyncLock)
  803. {
  804. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  805. }
  806. }
  807. catch (DirectoryNotFoundException)
  808. {
  809. return new UserConfiguration();
  810. }
  811. catch (FileNotFoundException)
  812. {
  813. return new UserConfiguration();
  814. }
  815. catch (Exception ex)
  816. {
  817. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  818. return new UserConfiguration();
  819. }
  820. }
  821. private readonly object _configSyncLock = new object();
  822. public Task UpdateConfiguration(string userId, UserConfiguration config)
  823. {
  824. var user = GetUserById(userId);
  825. return UpdateConfiguration(user, config, true);
  826. }
  827. private async Task UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  828. {
  829. var path = GetConfigurationFilePath(user);
  830. // The xml serializer will output differently if the type is not exact
  831. if (config.GetType() != typeof(UserConfiguration))
  832. {
  833. var json = _jsonSerializer.SerializeToString(config);
  834. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  835. }
  836. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  837. lock (_configSyncLock)
  838. {
  839. _xmlSerializer.SerializeToFile(config, path);
  840. user.Configuration = config;
  841. }
  842. if (fireEvent)
  843. {
  844. EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  845. }
  846. }
  847. }
  848. }