UserManager.cs 34 KB

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