UserManager.cs 35 KB

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