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.FireEventIfNotNull(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<User> 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.Equals(i, '<') && !char.Equals(i, '>');
  183. }
  184. public string MakeValidUsername(string username)
  185. {
  186. if (IsValidUsername(username))
  187. {
  188. return username;
  189. }
  190. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  191. var builder = new StringBuilder();
  192. foreach (var c in username)
  193. {
  194. if (IsValidUsernameCharacter(c))
  195. {
  196. builder.Append(c);
  197. }
  198. }
  199. return builder.ToString();
  200. }
  201. public async Task<User> AuthenticateUser(string username, string passwordSha1, string passwordMd5, string remoteEndPoint)
  202. {
  203. if (string.IsNullOrWhiteSpace(username))
  204. {
  205. throw new ArgumentNullException("username");
  206. }
  207. var user = Users
  208. .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  209. var success = false;
  210. if (user != null)
  211. {
  212. // Authenticate using local credentials if not a guest
  213. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value != UserLinkType.Guest)
  214. {
  215. success = string.Equals(GetPasswordHash(user), passwordSha1.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  216. if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
  217. {
  218. success = string.Equals(GetLocalPasswordHash(user), passwordSha1.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  219. }
  220. }
  221. // Maybe user accidently entered connect credentials. let's be flexible
  222. if (!success && user.ConnectLinkType.HasValue && !string.IsNullOrWhiteSpace(passwordMd5) && !string.IsNullOrWhiteSpace(user.ConnectUserName))
  223. {
  224. try
  225. {
  226. await _connectFactory().Authenticate(user.ConnectUserName, passwordMd5).ConfigureAwait(false);
  227. success = true;
  228. }
  229. catch
  230. {
  231. }
  232. }
  233. }
  234. // Try originally entered username
  235. if (!success && (user == null || !string.Equals(user.ConnectUserName, username, StringComparison.OrdinalIgnoreCase)))
  236. {
  237. try
  238. {
  239. var connectAuthResult = await _connectFactory().Authenticate(username, passwordMd5).ConfigureAwait(false);
  240. user = Users.FirstOrDefault(i => string.Equals(i.ConnectUserId, connectAuthResult.User.Id, StringComparison.OrdinalIgnoreCase));
  241. success = user != null;
  242. }
  243. catch
  244. {
  245. }
  246. }
  247. if (user == null)
  248. {
  249. throw new SecurityException("Invalid username or password entered.");
  250. }
  251. if (user.Policy.IsDisabled)
  252. {
  253. throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  254. }
  255. // Update LastActivityDate and LastLoginDate, then save
  256. if (success)
  257. {
  258. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  259. await UpdateUser(user).ConfigureAwait(false);
  260. await UpdateInvalidLoginAttemptCount(user, 0).ConfigureAwait(false);
  261. }
  262. else
  263. {
  264. await UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1).ConfigureAwait(false);
  265. }
  266. _logger.Info("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
  267. return success ? user : null;
  268. }
  269. private async Task UpdateInvalidLoginAttemptCount(User user, int newValue)
  270. {
  271. if (user.Policy.InvalidLoginAttemptCount != newValue || newValue > 0)
  272. {
  273. user.Policy.InvalidLoginAttemptCount = newValue;
  274. var maxCount = user.Policy.IsAdministrator ?
  275. 3 :
  276. 5;
  277. var fireLockout = false;
  278. if (newValue >= maxCount)
  279. {
  280. //_logger.Debug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture));
  281. //user.Policy.IsDisabled = true;
  282. //fireLockout = true;
  283. }
  284. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(false);
  285. if (fireLockout)
  286. {
  287. if (UserLockedOut != null)
  288. {
  289. EventHelper.FireEventIfNotNull(UserLockedOut, this, new GenericEventArgs<User>(user), _logger);
  290. }
  291. }
  292. }
  293. }
  294. private string GetPasswordHash(User user)
  295. {
  296. return string.IsNullOrEmpty(user.Password)
  297. ? GetSha1String(string.Empty)
  298. : user.Password;
  299. }
  300. private string GetLocalPasswordHash(User user)
  301. {
  302. return string.IsNullOrEmpty(user.EasyPassword)
  303. ? GetSha1String(string.Empty)
  304. : user.EasyPassword;
  305. }
  306. private bool IsPasswordEmpty(string passwordHash)
  307. {
  308. return string.Equals(passwordHash, GetSha1String(string.Empty), StringComparison.OrdinalIgnoreCase);
  309. }
  310. /// <summary>
  311. /// Gets the sha1 string.
  312. /// </summary>
  313. /// <param name="str">The STR.</param>
  314. /// <returns>System.String.</returns>
  315. private string GetSha1String(string str)
  316. {
  317. return BitConverter.ToString(_cryptographyProvider.ComputeSHA1(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
  318. }
  319. /// <summary>
  320. /// Loads the users from the repository
  321. /// </summary>
  322. /// <returns>IEnumerable{User}.</returns>
  323. private async Task<IEnumerable<User>> LoadUsers()
  324. {
  325. var users = UserRepository.RetrieveAllUsers().ToList();
  326. // There always has to be at least one user.
  327. if (users.Count == 0)
  328. {
  329. var name = MakeValidUsername(_defaultUserName);
  330. var user = InstantiateNewUser(name);
  331. user.DateLastSaved = DateTime.UtcNow;
  332. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  333. users.Add(user);
  334. user.Policy.IsAdministrator = true;
  335. user.Policy.EnableContentDeletion = true;
  336. user.Policy.EnableRemoteControlOfOtherUsers = true;
  337. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(false);
  338. }
  339. return users;
  340. }
  341. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  342. {
  343. if (user == null)
  344. {
  345. throw new ArgumentNullException("user");
  346. }
  347. var passwordHash = GetPasswordHash(user);
  348. var hasConfiguredPassword = !IsPasswordEmpty(passwordHash);
  349. var hasConfiguredEasyPassword = !IsPasswordEmpty(GetLocalPasswordHash(user));
  350. var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  351. hasConfiguredEasyPassword :
  352. hasConfiguredPassword;
  353. var dto = new UserDto
  354. {
  355. Id = user.Id.ToString("N"),
  356. Name = user.Name,
  357. HasPassword = hasPassword,
  358. HasConfiguredPassword = hasConfiguredPassword,
  359. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  360. LastActivityDate = user.LastActivityDate,
  361. LastLoginDate = user.LastLoginDate,
  362. Configuration = user.Configuration,
  363. ConnectLinkType = user.ConnectLinkType,
  364. ConnectUserId = user.ConnectUserId,
  365. ConnectUserName = user.ConnectUserName,
  366. ServerId = _appHost.SystemId,
  367. Policy = user.Policy
  368. };
  369. if (!hasPassword && Users.Count() == 1)
  370. {
  371. dto.EnableAutoLogin = true;
  372. }
  373. var image = user.GetImageInfo(ImageType.Primary, 0);
  374. if (image != null)
  375. {
  376. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  377. try
  378. {
  379. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  380. }
  381. catch (Exception ex)
  382. {
  383. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  384. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  385. }
  386. }
  387. return dto;
  388. }
  389. public UserDto GetOfflineUserDto(User user)
  390. {
  391. var dto = GetUserDto(user);
  392. var offlinePasswordHash = GetLocalPasswordHash(user);
  393. dto.HasPassword = !IsPasswordEmpty(offlinePasswordHash);
  394. dto.OfflinePasswordSalt = Guid.NewGuid().ToString("N");
  395. // Hash the pin with the device Id to create a unique result for this device
  396. dto.OfflinePassword = GetSha1String((offlinePasswordHash + dto.OfflinePasswordSalt).ToLower());
  397. dto.ServerName = _appHost.FriendlyName;
  398. return dto;
  399. }
  400. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  401. {
  402. try
  403. {
  404. return _imageProcessorFactory().GetImageCacheTag(item, image);
  405. }
  406. catch (Exception ex)
  407. {
  408. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  409. return null;
  410. }
  411. }
  412. /// <summary>
  413. /// Refreshes metadata for each user
  414. /// </summary>
  415. /// <param name="cancellationToken">The cancellation token.</param>
  416. /// <returns>Task.</returns>
  417. public Task RefreshUsersMetadata(CancellationToken cancellationToken)
  418. {
  419. var tasks = Users.Select(user => user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken)).ToList();
  420. return Task.WhenAll(tasks);
  421. }
  422. /// <summary>
  423. /// Renames the user.
  424. /// </summary>
  425. /// <param name="user">The user.</param>
  426. /// <param name="newName">The new name.</param>
  427. /// <returns>Task.</returns>
  428. /// <exception cref="System.ArgumentNullException">user</exception>
  429. /// <exception cref="System.ArgumentException"></exception>
  430. public async Task RenameUser(User user, string newName)
  431. {
  432. if (user == null)
  433. {
  434. throw new ArgumentNullException("user");
  435. }
  436. if (string.IsNullOrEmpty(newName))
  437. {
  438. throw new ArgumentNullException("newName");
  439. }
  440. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  441. {
  442. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  443. }
  444. if (user.Name.Equals(newName, StringComparison.Ordinal))
  445. {
  446. throw new ArgumentException("The new and old names must be different.");
  447. }
  448. await user.Rename(newName);
  449. OnUserUpdated(user);
  450. }
  451. /// <summary>
  452. /// Updates the user.
  453. /// </summary>
  454. /// <param name="user">The user.</param>
  455. /// <exception cref="System.ArgumentNullException">user</exception>
  456. /// <exception cref="System.ArgumentException"></exception>
  457. public async Task UpdateUser(User user)
  458. {
  459. if (user == null)
  460. {
  461. throw new ArgumentNullException("user");
  462. }
  463. if (user.Id == Guid.Empty || !Users.Any(u => u.Id.Equals(user.Id)))
  464. {
  465. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  466. }
  467. user.DateModified = DateTime.UtcNow;
  468. user.DateLastSaved = DateTime.UtcNow;
  469. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  470. OnUserUpdated(user);
  471. }
  472. public event EventHandler<GenericEventArgs<User>> UserCreated;
  473. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  474. /// <summary>
  475. /// Creates the user.
  476. /// </summary>
  477. /// <param name="name">The name.</param>
  478. /// <returns>User.</returns>
  479. /// <exception cref="System.ArgumentNullException">name</exception>
  480. /// <exception cref="System.ArgumentException"></exception>
  481. public async Task<User> CreateUser(string name)
  482. {
  483. if (string.IsNullOrWhiteSpace(name))
  484. {
  485. throw new ArgumentNullException("name");
  486. }
  487. if (!IsValidUsername(name))
  488. {
  489. throw new ArgumentException("Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  490. }
  491. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  492. {
  493. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  494. }
  495. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  496. try
  497. {
  498. var user = InstantiateNewUser(name);
  499. var list = Users.ToList();
  500. list.Add(user);
  501. Users = list;
  502. user.DateLastSaved = DateTime.UtcNow;
  503. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  504. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  505. return user;
  506. }
  507. finally
  508. {
  509. _userListLock.Release();
  510. }
  511. }
  512. /// <summary>
  513. /// Deletes the user.
  514. /// </summary>
  515. /// <param name="user">The user.</param>
  516. /// <returns>Task.</returns>
  517. /// <exception cref="System.ArgumentNullException">user</exception>
  518. /// <exception cref="System.ArgumentException"></exception>
  519. public async Task DeleteUser(User user)
  520. {
  521. if (user == null)
  522. {
  523. throw new ArgumentNullException("user");
  524. }
  525. if (user.ConnectLinkType.HasValue)
  526. {
  527. await _connectFactory().RemoveConnect(user.Id.ToString("N")).ConfigureAwait(false);
  528. }
  529. var allUsers = Users.ToList();
  530. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  531. {
  532. 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));
  533. }
  534. if (allUsers.Count == 1)
  535. {
  536. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  537. }
  538. if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1)
  539. {
  540. 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));
  541. }
  542. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  543. try
  544. {
  545. var configPath = GetConfigurationFilePath(user);
  546. await UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  547. try
  548. {
  549. _fileSystem.DeleteFile(configPath);
  550. }
  551. catch (IOException ex)
  552. {
  553. _logger.ErrorException("Error deleting file {0}", ex, configPath);
  554. }
  555. DeleteUserPolicy(user);
  556. // Force this to be lazy loaded again
  557. Users = await LoadUsers().ConfigureAwait(false);
  558. OnUserDeleted(user);
  559. }
  560. finally
  561. {
  562. _userListLock.Release();
  563. }
  564. }
  565. /// <summary>
  566. /// Resets the password by clearing it.
  567. /// </summary>
  568. /// <returns>Task.</returns>
  569. public Task ResetPassword(User user)
  570. {
  571. return ChangePassword(user, GetSha1String(string.Empty));
  572. }
  573. public Task ResetEasyPassword(User user)
  574. {
  575. return ChangeEasyPassword(user, GetSha1String(string.Empty));
  576. }
  577. public async Task ChangePassword(User user, string newPasswordSha1)
  578. {
  579. if (user == null)
  580. {
  581. throw new ArgumentNullException("user");
  582. }
  583. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  584. {
  585. throw new ArgumentNullException("newPasswordSha1");
  586. }
  587. if (user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  588. {
  589. throw new ArgumentException("Passwords for guests cannot be changed.");
  590. }
  591. user.Password = newPasswordSha1;
  592. await UpdateUser(user).ConfigureAwait(false);
  593. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  594. }
  595. public async Task ChangeEasyPassword(User user, string newPasswordSha1)
  596. {
  597. if (user == null)
  598. {
  599. throw new ArgumentNullException("user");
  600. }
  601. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  602. {
  603. throw new ArgumentNullException("newPasswordSha1");
  604. }
  605. user.EasyPassword = newPasswordSha1;
  606. await UpdateUser(user).ConfigureAwait(false);
  607. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  608. }
  609. /// <summary>
  610. /// Instantiates the new user.
  611. /// </summary>
  612. /// <param name="name">The name.</param>
  613. /// <returns>User.</returns>
  614. private User InstantiateNewUser(string name)
  615. {
  616. return new User
  617. {
  618. Name = name,
  619. Id = Guid.NewGuid(),
  620. DateCreated = DateTime.UtcNow,
  621. DateModified = DateTime.UtcNow,
  622. UsesIdForConfigurationPath = true
  623. };
  624. }
  625. private string PasswordResetFile
  626. {
  627. get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); }
  628. }
  629. private string _lastPin;
  630. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  631. private int _pinAttempts;
  632. private PasswordPinCreationResult CreatePasswordResetPin()
  633. {
  634. var num = new Random().Next(1, 9999);
  635. var path = PasswordResetFile;
  636. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  637. _lastPin = pin;
  638. var time = TimeSpan.FromMinutes(5);
  639. var expiration = DateTime.UtcNow.Add(time);
  640. var text = new StringBuilder();
  641. var localAddress = _appHost.GetLocalApiUrl().Result ?? string.Empty;
  642. text.AppendLine("Use your web browser to visit:");
  643. text.AppendLine(string.Empty);
  644. text.AppendLine(localAddress + "/web/forgotpasswordpin.html");
  645. text.AppendLine(string.Empty);
  646. text.AppendLine("Enter the following pin code:");
  647. text.AppendLine(string.Empty);
  648. text.AppendLine(pin);
  649. text.AppendLine(string.Empty);
  650. var localExpirationTime = expiration.ToLocalTime();
  651. // Tuesday, 22 August 2006 06:30 AM
  652. text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
  653. _fileSystem.WriteAllText(path, text.ToString(), Encoding.UTF8);
  654. var result = new PasswordPinCreationResult
  655. {
  656. PinFile = path,
  657. ExpirationDate = expiration
  658. };
  659. _lastPasswordPinCreationResult = result;
  660. _pinAttempts = 0;
  661. return result;
  662. }
  663. public ForgotPasswordResult StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  664. {
  665. DeletePinFile();
  666. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  667. null :
  668. GetUserByName(enteredUsername);
  669. if (user != null && user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  670. {
  671. throw new ArgumentException("Unable to process forgot password request for guests.");
  672. }
  673. var action = ForgotPasswordAction.InNetworkRequired;
  674. string pinFile = null;
  675. DateTime? expirationDate = null;
  676. if (user != null && !user.Policy.IsAdministrator)
  677. {
  678. action = ForgotPasswordAction.ContactAdmin;
  679. }
  680. else
  681. {
  682. if (isInNetwork)
  683. {
  684. action = ForgotPasswordAction.PinCode;
  685. }
  686. var result = CreatePasswordResetPin();
  687. pinFile = result.PinFile;
  688. expirationDate = result.ExpirationDate;
  689. }
  690. return new ForgotPasswordResult
  691. {
  692. Action = action,
  693. PinFile = pinFile,
  694. PinExpirationDate = expirationDate
  695. };
  696. }
  697. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  698. {
  699. DeletePinFile();
  700. var usersReset = new List<string>();
  701. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  702. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  703. _lastPasswordPinCreationResult != null &&
  704. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  705. if (valid)
  706. {
  707. _lastPin = null;
  708. _lastPasswordPinCreationResult = null;
  709. var users = Users.Where(i => !i.ConnectLinkType.HasValue || i.ConnectLinkType.Value != UserLinkType.Guest)
  710. .ToList();
  711. foreach (var user in users)
  712. {
  713. await ResetPassword(user).ConfigureAwait(false);
  714. if (user.Policy.IsDisabled)
  715. {
  716. user.Policy.IsDisabled = false;
  717. await UpdateUserPolicy(user, user.Policy, true).ConfigureAwait(false);
  718. }
  719. usersReset.Add(user.Name);
  720. }
  721. }
  722. else
  723. {
  724. _pinAttempts++;
  725. if (_pinAttempts >= 3)
  726. {
  727. _lastPin = null;
  728. _lastPasswordPinCreationResult = null;
  729. }
  730. }
  731. return new PinRedeemResult
  732. {
  733. Success = valid,
  734. UsersReset = usersReset.ToArray()
  735. };
  736. }
  737. private void DeletePinFile()
  738. {
  739. try
  740. {
  741. _fileSystem.DeleteFile(PasswordResetFile);
  742. }
  743. catch
  744. {
  745. }
  746. }
  747. class PasswordPinCreationResult
  748. {
  749. public string PinFile { get; set; }
  750. public DateTime ExpirationDate { get; set; }
  751. }
  752. public UserPolicy GetUserPolicy(User user)
  753. {
  754. var path = GetPolifyFilePath(user);
  755. try
  756. {
  757. lock (_policySyncLock)
  758. {
  759. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  760. }
  761. }
  762. catch (FileNotFoundException)
  763. {
  764. return GetDefaultPolicy(user);
  765. }
  766. catch (IOException)
  767. {
  768. return GetDefaultPolicy(user);
  769. }
  770. catch (Exception ex)
  771. {
  772. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  773. return GetDefaultPolicy(user);
  774. }
  775. }
  776. private UserPolicy GetDefaultPolicy(User user)
  777. {
  778. return new UserPolicy
  779. {
  780. EnableContentDownloading = true,
  781. EnableSyncTranscoding = 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(_fileSystem.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(_fileSystem.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. }