UserManager.cs 36 KB

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