UserManager.cs 35 KB

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