UserManager.cs 36 KB

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