UserManager.cs 36 KB

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