UserManager.cs 36 KB

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