UserManager.cs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  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 async Task Initialize()
  146. {
  147. Users = await LoadUsers().ConfigureAwait(false);
  148. var users = Users.ToList();
  149. // If there are no local users with admin rights, make them all admins
  150. if (!users.Any(i => i.Policy.IsAdministrator))
  151. {
  152. foreach (var user in users)
  153. {
  154. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value == UserLinkType.LinkedUser)
  155. {
  156. user.Policy.IsAdministrator = true;
  157. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(false);
  158. }
  159. }
  160. }
  161. }
  162. public Task<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. await UpdateUser(user).ConfigureAwait(false);
  258. await UpdateInvalidLoginAttemptCount(user, 0).ConfigureAwait(false);
  259. }
  260. else
  261. {
  262. await UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1).ConfigureAwait(false);
  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 async Task 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. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(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 async Task<IEnumerable<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. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  331. users.Add(user);
  332. user.Policy.IsAdministrator = true;
  333. user.Policy.EnableContentDeletion = true;
  334. user.Policy.EnableRemoteControlOfOtherUsers = true;
  335. await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(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 async Task 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. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  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. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  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. await UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  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. // Force this to be lazy loaded again
  555. Users = await LoadUsers().ConfigureAwait(false);
  556. OnUserDeleted(user);
  557. }
  558. finally
  559. {
  560. _userListLock.Release();
  561. }
  562. }
  563. /// <summary>
  564. /// Resets the password by clearing it.
  565. /// </summary>
  566. /// <returns>Task.</returns>
  567. public Task ResetPassword(User user)
  568. {
  569. return ChangePassword(user, GetSha1String(string.Empty));
  570. }
  571. public Task ResetEasyPassword(User user)
  572. {
  573. return ChangeEasyPassword(user, GetSha1String(string.Empty));
  574. }
  575. public async Task ChangePassword(User user, string newPasswordSha1)
  576. {
  577. if (user == null)
  578. {
  579. throw new ArgumentNullException("user");
  580. }
  581. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  582. {
  583. throw new ArgumentNullException("newPasswordSha1");
  584. }
  585. if (user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  586. {
  587. throw new ArgumentException("Passwords for guests cannot be changed.");
  588. }
  589. user.Password = newPasswordSha1;
  590. await UpdateUser(user).ConfigureAwait(false);
  591. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  592. }
  593. public async Task ChangeEasyPassword(User user, string newPasswordSha1)
  594. {
  595. if (user == null)
  596. {
  597. throw new ArgumentNullException("user");
  598. }
  599. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  600. {
  601. throw new ArgumentNullException("newPasswordSha1");
  602. }
  603. user.EasyPassword = newPasswordSha1;
  604. await UpdateUser(user).ConfigureAwait(false);
  605. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  606. }
  607. /// <summary>
  608. /// Instantiates the new user.
  609. /// </summary>
  610. /// <param name="name">The name.</param>
  611. /// <returns>User.</returns>
  612. private User InstantiateNewUser(string name)
  613. {
  614. return new User
  615. {
  616. Name = name,
  617. Id = Guid.NewGuid(),
  618. DateCreated = DateTime.UtcNow,
  619. DateModified = DateTime.UtcNow,
  620. UsesIdForConfigurationPath = true
  621. };
  622. }
  623. private string PasswordResetFile
  624. {
  625. get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); }
  626. }
  627. private string _lastPin;
  628. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  629. private int _pinAttempts;
  630. private PasswordPinCreationResult CreatePasswordResetPin()
  631. {
  632. var num = new Random().Next(1, 9999);
  633. var path = PasswordResetFile;
  634. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  635. _lastPin = pin;
  636. var time = TimeSpan.FromMinutes(5);
  637. var expiration = DateTime.UtcNow.Add(time);
  638. var text = new StringBuilder();
  639. var localAddress = _appHost.GetLocalApiUrl().Result ?? string.Empty;
  640. text.AppendLine("Use your web browser to visit:");
  641. text.AppendLine(string.Empty);
  642. text.AppendLine(localAddress + "/web/forgotpasswordpin.html");
  643. text.AppendLine(string.Empty);
  644. text.AppendLine("Enter the following pin code:");
  645. text.AppendLine(string.Empty);
  646. text.AppendLine(pin);
  647. text.AppendLine(string.Empty);
  648. var localExpirationTime = expiration.ToLocalTime();
  649. // Tuesday, 22 August 2006 06:30 AM
  650. text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
  651. _fileSystem.WriteAllText(path, text.ToString(), Encoding.UTF8);
  652. var result = new PasswordPinCreationResult
  653. {
  654. PinFile = path,
  655. ExpirationDate = expiration
  656. };
  657. _lastPasswordPinCreationResult = result;
  658. _pinAttempts = 0;
  659. return result;
  660. }
  661. public ForgotPasswordResult StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  662. {
  663. DeletePinFile();
  664. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  665. null :
  666. GetUserByName(enteredUsername);
  667. if (user != null && user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  668. {
  669. throw new ArgumentException("Unable to process forgot password request for guests.");
  670. }
  671. var action = ForgotPasswordAction.InNetworkRequired;
  672. string pinFile = null;
  673. DateTime? expirationDate = null;
  674. if (user != null && !user.Policy.IsAdministrator)
  675. {
  676. action = ForgotPasswordAction.ContactAdmin;
  677. }
  678. else
  679. {
  680. if (isInNetwork)
  681. {
  682. action = ForgotPasswordAction.PinCode;
  683. }
  684. var result = CreatePasswordResetPin();
  685. pinFile = result.PinFile;
  686. expirationDate = result.ExpirationDate;
  687. }
  688. return new ForgotPasswordResult
  689. {
  690. Action = action,
  691. PinFile = pinFile,
  692. PinExpirationDate = expirationDate
  693. };
  694. }
  695. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  696. {
  697. DeletePinFile();
  698. var usersReset = new List<string>();
  699. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  700. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  701. _lastPasswordPinCreationResult != null &&
  702. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  703. if (valid)
  704. {
  705. _lastPin = null;
  706. _lastPasswordPinCreationResult = null;
  707. var users = Users.Where(i => !i.ConnectLinkType.HasValue || i.ConnectLinkType.Value != UserLinkType.Guest)
  708. .ToList();
  709. foreach (var user in users)
  710. {
  711. await ResetPassword(user).ConfigureAwait(false);
  712. if (user.Policy.IsDisabled)
  713. {
  714. user.Policy.IsDisabled = false;
  715. await UpdateUserPolicy(user, user.Policy, true).ConfigureAwait(false);
  716. }
  717. usersReset.Add(user.Name);
  718. }
  719. }
  720. else
  721. {
  722. _pinAttempts++;
  723. if (_pinAttempts >= 3)
  724. {
  725. _lastPin = null;
  726. _lastPasswordPinCreationResult = null;
  727. }
  728. }
  729. return new PinRedeemResult
  730. {
  731. Success = valid,
  732. UsersReset = usersReset.ToArray()
  733. };
  734. }
  735. private void DeletePinFile()
  736. {
  737. try
  738. {
  739. _fileSystem.DeleteFile(PasswordResetFile);
  740. }
  741. catch
  742. {
  743. }
  744. }
  745. class PasswordPinCreationResult
  746. {
  747. public string PinFile { get; set; }
  748. public DateTime ExpirationDate { get; set; }
  749. }
  750. public UserPolicy GetUserPolicy(User user)
  751. {
  752. var path = GetPolifyFilePath(user);
  753. try
  754. {
  755. lock (_policySyncLock)
  756. {
  757. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  758. }
  759. }
  760. catch (FileNotFoundException)
  761. {
  762. return GetDefaultPolicy(user);
  763. }
  764. catch (IOException)
  765. {
  766. return GetDefaultPolicy(user);
  767. }
  768. catch (Exception ex)
  769. {
  770. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  771. return GetDefaultPolicy(user);
  772. }
  773. }
  774. private UserPolicy GetDefaultPolicy(User user)
  775. {
  776. return new UserPolicy
  777. {
  778. EnableContentDownloading = true,
  779. EnableSyncTranscoding = true
  780. };
  781. }
  782. private readonly object _policySyncLock = new object();
  783. public Task UpdateUserPolicy(string userId, UserPolicy userPolicy)
  784. {
  785. var user = GetUserById(userId);
  786. return UpdateUserPolicy(user, userPolicy, true);
  787. }
  788. private async Task UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  789. {
  790. // The xml serializer will output differently if the type is not exact
  791. if (userPolicy.GetType() != typeof(UserPolicy))
  792. {
  793. var json = _jsonSerializer.SerializeToString(userPolicy);
  794. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  795. }
  796. var path = GetPolifyFilePath(user);
  797. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  798. lock (_policySyncLock)
  799. {
  800. _xmlSerializer.SerializeToFile(userPolicy, path);
  801. user.Policy = userPolicy;
  802. }
  803. await UpdateConfiguration(user, user.Configuration, true).ConfigureAwait(false);
  804. }
  805. private void DeleteUserPolicy(User user)
  806. {
  807. var path = GetPolifyFilePath(user);
  808. try
  809. {
  810. lock (_policySyncLock)
  811. {
  812. _fileSystem.DeleteFile(path);
  813. }
  814. }
  815. catch (IOException)
  816. {
  817. }
  818. catch (Exception ex)
  819. {
  820. _logger.ErrorException("Error deleting policy file", ex);
  821. }
  822. }
  823. private string GetPolifyFilePath(User user)
  824. {
  825. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  826. }
  827. private string GetConfigurationFilePath(User user)
  828. {
  829. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  830. }
  831. public UserConfiguration GetUserConfiguration(User user)
  832. {
  833. var path = GetConfigurationFilePath(user);
  834. try
  835. {
  836. lock (_configSyncLock)
  837. {
  838. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  839. }
  840. }
  841. catch (FileNotFoundException)
  842. {
  843. return new UserConfiguration();
  844. }
  845. catch (IOException)
  846. {
  847. return new UserConfiguration();
  848. }
  849. catch (Exception ex)
  850. {
  851. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  852. return new UserConfiguration();
  853. }
  854. }
  855. private readonly object _configSyncLock = new object();
  856. public Task UpdateConfiguration(string userId, UserConfiguration config)
  857. {
  858. var user = GetUserById(userId);
  859. return UpdateConfiguration(user, config, true);
  860. }
  861. private async Task UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  862. {
  863. var path = GetConfigurationFilePath(user);
  864. // The xml serializer will output differently if the type is not exact
  865. if (config.GetType() != typeof(UserConfiguration))
  866. {
  867. var json = _jsonSerializer.SerializeToString(config);
  868. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  869. }
  870. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  871. lock (_configSyncLock)
  872. {
  873. _xmlSerializer.SerializeToFile(config, path);
  874. user.Configuration = config;
  875. }
  876. if (fireEvent)
  877. {
  878. EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  879. }
  880. }
  881. }
  882. }