UserManager.cs 34 KB

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