UserManager.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Events;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.Authentication;
  13. using MediaBrowser.Controller.Configuration;
  14. using MediaBrowser.Controller.Devices;
  15. using MediaBrowser.Controller.Drawing;
  16. using MediaBrowser.Controller.Dto;
  17. using MediaBrowser.Controller.Entities;
  18. using MediaBrowser.Controller.Library;
  19. using MediaBrowser.Controller.Net;
  20. using MediaBrowser.Controller.Persistence;
  21. using MediaBrowser.Controller.Plugins;
  22. using MediaBrowser.Controller.Providers;
  23. using MediaBrowser.Controller.Security;
  24. using MediaBrowser.Controller.Session;
  25. using MediaBrowser.Model.Configuration;
  26. using MediaBrowser.Model.Connect;
  27. using MediaBrowser.Model.Cryptography;
  28. using MediaBrowser.Model.Dto;
  29. using MediaBrowser.Model.Entities;
  30. using MediaBrowser.Model.Events;
  31. using MediaBrowser.Model.IO;
  32. using MediaBrowser.Model.Serialization;
  33. using MediaBrowser.Model.Users;
  34. using Microsoft.Extensions.Logging;
  35. namespace Emby.Server.Implementations.Library
  36. {
  37. /// <summary>
  38. /// Class UserManager
  39. /// </summary>
  40. public class UserManager : IUserManager
  41. {
  42. /// <summary>
  43. /// Gets the users.
  44. /// </summary>
  45. /// <value>The users.</value>
  46. public IEnumerable<User> Users => _users;
  47. private User[] _users;
  48. /// <summary>
  49. /// The _logger
  50. /// </summary>
  51. private readonly ILogger _logger;
  52. /// <summary>
  53. /// Gets or sets the configuration manager.
  54. /// </summary>
  55. /// <value>The configuration manager.</value>
  56. private IServerConfigurationManager ConfigurationManager { get; set; }
  57. /// <summary>
  58. /// Gets the active user repository
  59. /// </summary>
  60. /// <value>The user repository.</value>
  61. private IUserRepository UserRepository { get; set; }
  62. public event EventHandler<GenericEventArgs<User>> UserPasswordChanged;
  63. private readonly IXmlSerializer _xmlSerializer;
  64. private readonly IJsonSerializer _jsonSerializer;
  65. private readonly INetworkManager _networkManager;
  66. private readonly Func<IImageProcessor> _imageProcessorFactory;
  67. private readonly Func<IDtoService> _dtoServiceFactory;
  68. private readonly IServerApplicationHost _appHost;
  69. private readonly IFileSystem _fileSystem;
  70. private readonly ICryptoProvider _cryptographyProvider;
  71. private IAuthenticationProvider[] _authenticationProviders;
  72. private DefaultAuthenticationProvider _defaultAuthenticationProvider;
  73. public UserManager(
  74. ILoggerFactory loggerFactory,
  75. IServerConfigurationManager configurationManager,
  76. IUserRepository userRepository,
  77. IXmlSerializer xmlSerializer,
  78. INetworkManager networkManager,
  79. Func<IImageProcessor> imageProcessorFactory,
  80. Func<IDtoService> dtoServiceFactory,
  81. IServerApplicationHost appHost,
  82. IJsonSerializer jsonSerializer,
  83. IFileSystem fileSystem,
  84. ICryptoProvider cryptographyProvider)
  85. {
  86. _logger = loggerFactory.CreateLogger(nameof(UserManager));
  87. UserRepository = userRepository;
  88. _xmlSerializer = xmlSerializer;
  89. _networkManager = networkManager;
  90. _imageProcessorFactory = imageProcessorFactory;
  91. _dtoServiceFactory = dtoServiceFactory;
  92. _appHost = appHost;
  93. _jsonSerializer = jsonSerializer;
  94. _fileSystem = fileSystem;
  95. _cryptographyProvider = cryptographyProvider;
  96. ConfigurationManager = configurationManager;
  97. _users = Array.Empty<User>();
  98. DeletePinFile();
  99. }
  100. public NameIdPair[] GetAuthenticationProviders()
  101. {
  102. return _authenticationProviders
  103. .Where(i => i.IsEnabled)
  104. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  105. .ThenBy(i => i.Name)
  106. .Select(i => new NameIdPair
  107. {
  108. Name = i.Name,
  109. Id = GetAuthenticationProviderId(i)
  110. })
  111. .ToArray();
  112. }
  113. public void AddParts(IEnumerable<IAuthenticationProvider> authenticationProviders)
  114. {
  115. _authenticationProviders = authenticationProviders.ToArray();
  116. _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
  117. }
  118. #region UserUpdated Event
  119. /// <summary>
  120. /// Occurs when [user updated].
  121. /// </summary>
  122. public event EventHandler<GenericEventArgs<User>> UserUpdated;
  123. public event EventHandler<GenericEventArgs<User>> UserPolicyUpdated;
  124. public event EventHandler<GenericEventArgs<User>> UserConfigurationUpdated;
  125. public event EventHandler<GenericEventArgs<User>> UserLockedOut;
  126. /// <summary>
  127. /// Called when [user updated].
  128. /// </summary>
  129. /// <param name="user">The user.</param>
  130. private void OnUserUpdated(User user)
  131. {
  132. UserUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  133. }
  134. #endregion
  135. #region UserDeleted Event
  136. /// <summary>
  137. /// Occurs when [user deleted].
  138. /// </summary>
  139. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  140. /// <summary>
  141. /// Called when [user deleted].
  142. /// </summary>
  143. /// <param name="user">The user.</param>
  144. private void OnUserDeleted(User user)
  145. {
  146. UserDeleted?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  147. }
  148. #endregion
  149. /// <summary>
  150. /// Gets a User by Id
  151. /// </summary>
  152. /// <param name="id">The id.</param>
  153. /// <returns>User.</returns>
  154. /// <exception cref="ArgumentNullException"></exception>
  155. public User GetUserById(Guid id)
  156. {
  157. if (id.Equals(Guid.Empty))
  158. {
  159. throw new ArgumentNullException(nameof(id));
  160. }
  161. return Users.FirstOrDefault(u => u.Id == id);
  162. }
  163. /// <summary>
  164. /// Gets the user by identifier.
  165. /// </summary>
  166. /// <param name="id">The identifier.</param>
  167. /// <returns>User.</returns>
  168. public User GetUserById(string id)
  169. {
  170. return GetUserById(new Guid(id));
  171. }
  172. public User GetUserByName(string name)
  173. {
  174. if (string.IsNullOrWhiteSpace(name))
  175. {
  176. throw new ArgumentNullException(nameof(name));
  177. }
  178. return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));
  179. }
  180. public void Initialize()
  181. {
  182. _users = LoadUsers();
  183. var users = Users.ToList();
  184. // If there are no local users with admin rights, make them all admins
  185. if (!users.Any(i => i.Policy.IsAdministrator))
  186. {
  187. foreach (var user in users)
  188. {
  189. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value == UserLinkType.LinkedUser)
  190. {
  191. user.Policy.IsAdministrator = true;
  192. UpdateUserPolicy(user, user.Policy, false);
  193. }
  194. }
  195. }
  196. }
  197. public bool IsValidUsername(string username)
  198. {
  199. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  200. foreach (var currentChar in username)
  201. {
  202. if (!IsValidUsernameCharacter(currentChar))
  203. {
  204. return false;
  205. }
  206. }
  207. return true;
  208. }
  209. private static bool IsValidUsernameCharacter(char i)
  210. {
  211. return !char.Equals(i, '<') && !char.Equals(i, '>');
  212. }
  213. public string MakeValidUsername(string username)
  214. {
  215. if (IsValidUsername(username))
  216. {
  217. return username;
  218. }
  219. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  220. var builder = new StringBuilder();
  221. foreach (var c in username)
  222. {
  223. if (IsValidUsernameCharacter(c))
  224. {
  225. builder.Append(c);
  226. }
  227. }
  228. return builder.ToString();
  229. }
  230. public async Task<User> AuthenticateUser(string username, string password, string hashedPassword, string remoteEndPoint, bool isUserSession)
  231. {
  232. if (string.IsNullOrWhiteSpace(username))
  233. {
  234. throw new ArgumentNullException(nameof(username));
  235. }
  236. var user = Users
  237. .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  238. var success = false;
  239. IAuthenticationProvider authenticationProvider = null;
  240. if (user != null)
  241. {
  242. // Authenticate using local credentials if not a guest
  243. if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value != UserLinkType.Guest)
  244. {
  245. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, user, remoteEndPoint).ConfigureAwait(false);
  246. authenticationProvider = authResult.Item1;
  247. success = authResult.Item2;
  248. }
  249. }
  250. else
  251. {
  252. // user is null
  253. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, null, remoteEndPoint).ConfigureAwait(false);
  254. authenticationProvider = authResult.Item1;
  255. success = authResult.Item2;
  256. if (success && authenticationProvider != null && !(authenticationProvider is DefaultAuthenticationProvider))
  257. {
  258. user = await CreateUser(username).ConfigureAwait(false);
  259. var hasNewUserPolicy = authenticationProvider as IHasNewUserPolicy;
  260. if (hasNewUserPolicy != null)
  261. {
  262. var policy = hasNewUserPolicy.GetNewUserPolicy();
  263. UpdateUserPolicy(user, policy, true);
  264. }
  265. }
  266. }
  267. if (success && user != null && authenticationProvider != null)
  268. {
  269. var providerId = GetAuthenticationProviderId(authenticationProvider);
  270. if (!string.Equals(providerId, user.Policy.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  271. {
  272. user.Policy.AuthenticationProviderId = providerId;
  273. UpdateUserPolicy(user, user.Policy, true);
  274. }
  275. }
  276. if (user == null)
  277. {
  278. throw new SecurityException("Invalid username or password entered.");
  279. }
  280. if (user.Policy.IsDisabled)
  281. {
  282. throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  283. }
  284. if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint))
  285. {
  286. throw new SecurityException("Forbidden.");
  287. }
  288. if (!user.IsParentalScheduleAllowed())
  289. {
  290. throw new SecurityException("User is not allowed access at this time.");
  291. }
  292. // Update LastActivityDate and LastLoginDate, then save
  293. if (success)
  294. {
  295. if (isUserSession)
  296. {
  297. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  298. UpdateUser(user);
  299. }
  300. UpdateInvalidLoginAttemptCount(user, 0);
  301. }
  302. else
  303. {
  304. UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1);
  305. }
  306. _logger.LogInformation("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
  307. return success ? user : null;
  308. }
  309. private static string GetAuthenticationProviderId(IAuthenticationProvider provider)
  310. {
  311. return provider.GetType().FullName;
  312. }
  313. private IAuthenticationProvider GetAuthenticationProvider(User user)
  314. {
  315. return GetAuthenticationProviders(user).First();
  316. }
  317. private IAuthenticationProvider[] GetAuthenticationProviders(User user)
  318. {
  319. var authenticationProviderId = user == null ? null : user.Policy.AuthenticationProviderId;
  320. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToArray();
  321. if (!string.IsNullOrEmpty(authenticationProviderId))
  322. {
  323. providers = providers.Where(i => string.Equals(authenticationProviderId, GetAuthenticationProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  324. }
  325. if (providers.Length == 0)
  326. {
  327. providers = new IAuthenticationProvider[] { _defaultAuthenticationProvider };
  328. }
  329. return providers;
  330. }
  331. private async Task<bool> AuthenticateWithProvider(IAuthenticationProvider provider, string username, string password, User resolvedUser)
  332. {
  333. try
  334. {
  335. var requiresResolvedUser = provider as IRequiresResolvedUser;
  336. if (requiresResolvedUser != null)
  337. {
  338. await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false);
  339. }
  340. else
  341. {
  342. await provider.Authenticate(username, password).ConfigureAwait(false);
  343. }
  344. return true;
  345. }
  346. catch (Exception ex)
  347. {
  348. _logger.LogError(ex, "Error authenticating with provider {provider}", provider.Name);
  349. return false;
  350. }
  351. }
  352. private async Task<Tuple<IAuthenticationProvider, bool>> AuthenticateLocalUser(string username, string password, string hashedPassword, User user, string remoteEndPoint)
  353. {
  354. bool success = false;
  355. IAuthenticationProvider authenticationProvider = null;
  356. if (password != null && user != null)
  357. {
  358. // Doesn't look like this is even possible to be used, because of password == null checks below
  359. hashedPassword = _defaultAuthenticationProvider.GetHashedString(user, password);
  360. }
  361. if (password == null)
  362. {
  363. // legacy
  364. success = string.Equals(_defaultAuthenticationProvider.GetPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  365. }
  366. else
  367. {
  368. foreach (var provider in GetAuthenticationProviders(user))
  369. {
  370. success = await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  371. if (success)
  372. {
  373. authenticationProvider = provider;
  374. break;
  375. }
  376. }
  377. }
  378. if (user != null)
  379. {
  380. if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
  381. {
  382. if (password == null)
  383. {
  384. // legacy
  385. success = string.Equals(GetLocalPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  386. }
  387. else
  388. {
  389. success = string.Equals(GetLocalPasswordHash(user), _defaultAuthenticationProvider.GetHashedString(user, password), StringComparison.OrdinalIgnoreCase);
  390. }
  391. }
  392. }
  393. return new Tuple<IAuthenticationProvider, bool>(authenticationProvider, success);
  394. }
  395. private void UpdateInvalidLoginAttemptCount(User user, int newValue)
  396. {
  397. if (user.Policy.InvalidLoginAttemptCount != newValue || newValue > 0)
  398. {
  399. user.Policy.InvalidLoginAttemptCount = newValue;
  400. var maxCount = user.Policy.IsAdministrator ? 3 : 5;
  401. // TODO: Fix
  402. /*
  403. var fireLockout = false;
  404. if (newValue >= maxCount)
  405. {
  406. _logger.LogDebug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture));
  407. user.Policy.IsDisabled = true;
  408. fireLockout = true;
  409. }*/
  410. UpdateUserPolicy(user, user.Policy, false);
  411. /* if (fireLockout)
  412. {
  413. UserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
  414. }*/
  415. }
  416. }
  417. private string GetLocalPasswordHash(User user)
  418. {
  419. return string.IsNullOrEmpty(user.EasyPassword)
  420. ? _defaultAuthenticationProvider.GetEmptyHashedString(user)
  421. : user.EasyPassword;
  422. }
  423. private bool IsPasswordEmpty(User user, string passwordHash)
  424. {
  425. return string.Equals(passwordHash, _defaultAuthenticationProvider.GetEmptyHashedString(user), StringComparison.OrdinalIgnoreCase);
  426. }
  427. /// <summary>
  428. /// Loads the users from the repository
  429. /// </summary>
  430. /// <returns>IEnumerable{User}.</returns>
  431. private User[] LoadUsers()
  432. {
  433. var users = UserRepository.RetrieveAllUsers();
  434. // There always has to be at least one user.
  435. if (users.Count == 0)
  436. {
  437. var defaultName = Environment.UserName;
  438. if (string.IsNullOrWhiteSpace(defaultName))
  439. {
  440. defaultName = "MyJellyfinUser";
  441. }
  442. var name = MakeValidUsername(defaultName);
  443. var user = InstantiateNewUser(name);
  444. user.DateLastSaved = DateTime.UtcNow;
  445. UserRepository.CreateUser(user);
  446. users.Add(user);
  447. user.Policy.IsAdministrator = true;
  448. user.Policy.EnableContentDeletion = true;
  449. user.Policy.EnableRemoteControlOfOtherUsers = true;
  450. UpdateUserPolicy(user, user.Policy, false);
  451. }
  452. return users.ToArray();
  453. }
  454. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  455. {
  456. if (user == null)
  457. {
  458. throw new ArgumentNullException(nameof(user));
  459. }
  460. var hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result;
  461. var hasConfiguredEasyPassword = !IsPasswordEmpty(user, GetLocalPasswordHash(user));
  462. var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  463. hasConfiguredEasyPassword :
  464. hasConfiguredPassword;
  465. var dto = new UserDto
  466. {
  467. Id = user.Id,
  468. Name = user.Name,
  469. HasPassword = hasPassword,
  470. HasConfiguredPassword = hasConfiguredPassword,
  471. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  472. LastActivityDate = user.LastActivityDate,
  473. LastLoginDate = user.LastLoginDate,
  474. Configuration = user.Configuration,
  475. ConnectLinkType = user.ConnectLinkType,
  476. ConnectUserId = user.ConnectUserId,
  477. ConnectUserName = user.ConnectUserName,
  478. ServerId = _appHost.SystemId,
  479. Policy = user.Policy
  480. };
  481. if (!hasPassword && Users.Count() == 1)
  482. {
  483. dto.EnableAutoLogin = true;
  484. }
  485. var image = user.GetImageInfo(ImageType.Primary, 0);
  486. if (image != null)
  487. {
  488. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  489. try
  490. {
  491. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  492. }
  493. catch (Exception ex)
  494. {
  495. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  496. _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {user}", user.Name);
  497. }
  498. }
  499. return dto;
  500. }
  501. public UserDto GetOfflineUserDto(User user)
  502. {
  503. var dto = GetUserDto(user);
  504. dto.ServerName = _appHost.FriendlyName;
  505. return dto;
  506. }
  507. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  508. {
  509. try
  510. {
  511. return _imageProcessorFactory().GetImageCacheTag(item, image);
  512. }
  513. catch (Exception ex)
  514. {
  515. _logger.LogError(ex, "Error getting {imageType} image info for {imagePath}", image.Type, image.Path);
  516. return null;
  517. }
  518. }
  519. /// <summary>
  520. /// Refreshes metadata for each user
  521. /// </summary>
  522. /// <param name="cancellationToken">The cancellation token.</param>
  523. /// <returns>Task.</returns>
  524. public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
  525. {
  526. foreach (var user in Users)
  527. {
  528. await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
  529. }
  530. }
  531. /// <summary>
  532. /// Renames the user.
  533. /// </summary>
  534. /// <param name="user">The user.</param>
  535. /// <param name="newName">The new name.</param>
  536. /// <returns>Task.</returns>
  537. /// <exception cref="ArgumentNullException">user</exception>
  538. /// <exception cref="ArgumentException"></exception>
  539. public async Task RenameUser(User user, string newName)
  540. {
  541. if (user == null)
  542. {
  543. throw new ArgumentNullException(nameof(user));
  544. }
  545. if (string.IsNullOrEmpty(newName))
  546. {
  547. throw new ArgumentNullException(nameof(newName));
  548. }
  549. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  550. {
  551. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  552. }
  553. if (user.Name.Equals(newName, StringComparison.Ordinal))
  554. {
  555. throw new ArgumentException("The new and old names must be different.");
  556. }
  557. await user.Rename(newName);
  558. OnUserUpdated(user);
  559. }
  560. /// <summary>
  561. /// Updates the user.
  562. /// </summary>
  563. /// <param name="user">The user.</param>
  564. /// <exception cref="ArgumentNullException">user</exception>
  565. /// <exception cref="ArgumentException"></exception>
  566. public void UpdateUser(User user)
  567. {
  568. if (user == null)
  569. {
  570. throw new ArgumentNullException(nameof(user));
  571. }
  572. if (user.Id.Equals(Guid.Empty) || !Users.Any(u => u.Id.Equals(user.Id)))
  573. {
  574. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  575. }
  576. user.DateModified = DateTime.UtcNow;
  577. user.DateLastSaved = DateTime.UtcNow;
  578. UserRepository.UpdateUser(user);
  579. OnUserUpdated(user);
  580. }
  581. public event EventHandler<GenericEventArgs<User>> UserCreated;
  582. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  583. /// <summary>
  584. /// Creates the user.
  585. /// </summary>
  586. /// <param name="name">The name.</param>
  587. /// <returns>User.</returns>
  588. /// <exception cref="ArgumentNullException">name</exception>
  589. /// <exception cref="ArgumentException"></exception>
  590. public async Task<User> CreateUser(string name)
  591. {
  592. if (string.IsNullOrWhiteSpace(name))
  593. {
  594. throw new ArgumentNullException(nameof(name));
  595. }
  596. if (!IsValidUsername(name))
  597. {
  598. throw new ArgumentException("Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  599. }
  600. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  601. {
  602. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  603. }
  604. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  605. try
  606. {
  607. var user = InstantiateNewUser(name);
  608. var list = Users.ToList();
  609. list.Add(user);
  610. _users = list.ToArray();
  611. user.DateLastSaved = DateTime.UtcNow;
  612. UserRepository.CreateUser(user);
  613. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  614. return user;
  615. }
  616. finally
  617. {
  618. _userListLock.Release();
  619. }
  620. }
  621. /// <summary>
  622. /// Deletes the user.
  623. /// </summary>
  624. /// <param name="user">The user.</param>
  625. /// <returns>Task.</returns>
  626. /// <exception cref="ArgumentNullException">user</exception>
  627. /// <exception cref="ArgumentException"></exception>
  628. public async Task DeleteUser(User user)
  629. {
  630. if (user == null)
  631. {
  632. throw new ArgumentNullException(nameof(user));
  633. }
  634. var allUsers = Users.ToList();
  635. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  636. {
  637. 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));
  638. }
  639. if (allUsers.Count == 1)
  640. {
  641. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  642. }
  643. if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1)
  644. {
  645. 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));
  646. }
  647. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  648. try
  649. {
  650. var configPath = GetConfigurationFilePath(user);
  651. UserRepository.DeleteUser(user);
  652. try
  653. {
  654. _fileSystem.DeleteFile(configPath);
  655. }
  656. catch (IOException ex)
  657. {
  658. _logger.LogError(ex, "Error deleting file {path}", configPath);
  659. }
  660. DeleteUserPolicy(user);
  661. _users = allUsers.Where(i => i.Id != user.Id).ToArray();
  662. OnUserDeleted(user);
  663. }
  664. finally
  665. {
  666. _userListLock.Release();
  667. }
  668. }
  669. /// <summary>
  670. /// Resets the password by clearing it.
  671. /// </summary>
  672. /// <returns>Task.</returns>
  673. public Task ResetPassword(User user)
  674. {
  675. return ChangePassword(user, string.Empty);
  676. }
  677. public void ResetEasyPassword(User user)
  678. {
  679. ChangeEasyPassword(user, string.Empty, null);
  680. }
  681. public async Task ChangePassword(User user, string newPassword)
  682. {
  683. if (user == null)
  684. {
  685. throw new ArgumentNullException(nameof(user));
  686. }
  687. if (user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  688. {
  689. throw new ArgumentException("Passwords for guests cannot be changed.");
  690. }
  691. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  692. UpdateUser(user);
  693. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  694. }
  695. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  696. {
  697. if (user == null)
  698. {
  699. throw new ArgumentNullException(nameof(user));
  700. }
  701. if (newPassword != null)
  702. {
  703. newPasswordHash = _defaultAuthenticationProvider.GetHashedString(user, newPassword);
  704. }
  705. if (string.IsNullOrWhiteSpace(newPasswordHash))
  706. {
  707. throw new ArgumentNullException(nameof(newPasswordHash));
  708. }
  709. user.EasyPassword = newPasswordHash;
  710. UpdateUser(user);
  711. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  712. }
  713. /// <summary>
  714. /// Instantiates the new user.
  715. /// </summary>
  716. /// <param name="name">The name.</param>
  717. /// <returns>User.</returns>
  718. private static User InstantiateNewUser(string name)
  719. {
  720. return new User
  721. {
  722. Name = name,
  723. Id = Guid.NewGuid(),
  724. DateCreated = DateTime.UtcNow,
  725. DateModified = DateTime.UtcNow,
  726. UsesIdForConfigurationPath = true,
  727. //Salt = BCrypt.GenerateSalt()
  728. };
  729. }
  730. private string PasswordResetFile => Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt");
  731. private string _lastPin;
  732. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  733. private int _pinAttempts;
  734. private async Task<PasswordPinCreationResult> CreatePasswordResetPin()
  735. {
  736. var num = new Random().Next(1, 9999);
  737. var path = PasswordResetFile;
  738. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  739. _lastPin = pin;
  740. var time = TimeSpan.FromMinutes(5);
  741. var expiration = DateTime.UtcNow.Add(time);
  742. var text = new StringBuilder();
  743. var localAddress = (await _appHost.GetLocalApiUrl(CancellationToken.None).ConfigureAwait(false)) ?? string.Empty;
  744. text.AppendLine("Use your web browser to visit:");
  745. text.AppendLine(string.Empty);
  746. text.AppendLine(localAddress + "/web/index.html#!/forgotpasswordpin.html");
  747. text.AppendLine(string.Empty);
  748. text.AppendLine("Enter the following pin code:");
  749. text.AppendLine(string.Empty);
  750. text.AppendLine(pin);
  751. text.AppendLine(string.Empty);
  752. var localExpirationTime = expiration.ToLocalTime();
  753. // Tuesday, 22 August 2006 06:30 AM
  754. text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
  755. File.WriteAllText(path, text.ToString(), Encoding.UTF8);
  756. var result = new PasswordPinCreationResult
  757. {
  758. PinFile = path,
  759. ExpirationDate = expiration
  760. };
  761. _lastPasswordPinCreationResult = result;
  762. _pinAttempts = 0;
  763. return result;
  764. }
  765. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  766. {
  767. DeletePinFile();
  768. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  769. null :
  770. GetUserByName(enteredUsername);
  771. if (user != null && user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  772. {
  773. throw new ArgumentException("Unable to process forgot password request for guests.");
  774. }
  775. var action = ForgotPasswordAction.InNetworkRequired;
  776. string pinFile = null;
  777. DateTime? expirationDate = null;
  778. if (user != null && !user.Policy.IsAdministrator)
  779. {
  780. action = ForgotPasswordAction.ContactAdmin;
  781. }
  782. else
  783. {
  784. if (isInNetwork)
  785. {
  786. action = ForgotPasswordAction.PinCode;
  787. }
  788. var result = await CreatePasswordResetPin().ConfigureAwait(false);
  789. pinFile = result.PinFile;
  790. expirationDate = result.ExpirationDate;
  791. }
  792. return new ForgotPasswordResult
  793. {
  794. Action = action,
  795. PinFile = pinFile,
  796. PinExpirationDate = expirationDate
  797. };
  798. }
  799. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  800. {
  801. DeletePinFile();
  802. var usersReset = new List<string>();
  803. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  804. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  805. _lastPasswordPinCreationResult != null &&
  806. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  807. if (valid)
  808. {
  809. _lastPin = null;
  810. _lastPasswordPinCreationResult = null;
  811. var users = Users.Where(i => !i.ConnectLinkType.HasValue || i.ConnectLinkType.Value != UserLinkType.Guest)
  812. .ToList();
  813. foreach (var user in users)
  814. {
  815. await ResetPassword(user).ConfigureAwait(false);
  816. if (user.Policy.IsDisabled)
  817. {
  818. user.Policy.IsDisabled = false;
  819. UpdateUserPolicy(user, user.Policy, true);
  820. }
  821. usersReset.Add(user.Name);
  822. }
  823. }
  824. else
  825. {
  826. _pinAttempts++;
  827. if (_pinAttempts >= 3)
  828. {
  829. _lastPin = null;
  830. _lastPasswordPinCreationResult = null;
  831. }
  832. }
  833. return new PinRedeemResult
  834. {
  835. Success = valid,
  836. UsersReset = usersReset.ToArray()
  837. };
  838. }
  839. private void DeletePinFile()
  840. {
  841. try
  842. {
  843. _fileSystem.DeleteFile(PasswordResetFile);
  844. }
  845. catch
  846. {
  847. }
  848. }
  849. class PasswordPinCreationResult
  850. {
  851. public string PinFile { get; set; }
  852. public DateTime ExpirationDate { get; set; }
  853. }
  854. public UserPolicy GetUserPolicy(User user)
  855. {
  856. var path = GetPolicyFilePath(user);
  857. if (!File.Exists(path))
  858. {
  859. return GetDefaultPolicy(user);
  860. }
  861. try
  862. {
  863. lock (_policySyncLock)
  864. {
  865. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  866. }
  867. }
  868. catch (IOException)
  869. {
  870. return GetDefaultPolicy(user);
  871. }
  872. catch (Exception ex)
  873. {
  874. _logger.LogError(ex, "Error reading policy file: {path}", path);
  875. return GetDefaultPolicy(user);
  876. }
  877. }
  878. private static UserPolicy GetDefaultPolicy(User user)
  879. {
  880. return new UserPolicy
  881. {
  882. EnableContentDownloading = true,
  883. EnableSyncTranscoding = true
  884. };
  885. }
  886. private readonly object _policySyncLock = new object();
  887. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  888. {
  889. var user = GetUserById(userId);
  890. UpdateUserPolicy(user, userPolicy, true);
  891. }
  892. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  893. {
  894. // The xml serializer will output differently if the type is not exact
  895. if (userPolicy.GetType() != typeof(UserPolicy))
  896. {
  897. var json = _jsonSerializer.SerializeToString(userPolicy);
  898. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  899. }
  900. var path = GetPolicyFilePath(user);
  901. Directory.CreateDirectory(Path.GetDirectoryName(path));
  902. lock (_policySyncLock)
  903. {
  904. _xmlSerializer.SerializeToFile(userPolicy, path);
  905. user.Policy = userPolicy;
  906. }
  907. if (fireEvent)
  908. {
  909. UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  910. }
  911. }
  912. private void DeleteUserPolicy(User user)
  913. {
  914. var path = GetPolicyFilePath(user);
  915. try
  916. {
  917. lock (_policySyncLock)
  918. {
  919. _fileSystem.DeleteFile(path);
  920. }
  921. }
  922. catch (IOException)
  923. {
  924. }
  925. catch (Exception ex)
  926. {
  927. _logger.LogError(ex, "Error deleting policy file");
  928. }
  929. }
  930. private static string GetPolicyFilePath(User user)
  931. {
  932. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  933. }
  934. private static string GetConfigurationFilePath(User user)
  935. {
  936. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  937. }
  938. public UserConfiguration GetUserConfiguration(User user)
  939. {
  940. var path = GetConfigurationFilePath(user);
  941. if (!File.Exists(path))
  942. {
  943. return new UserConfiguration();
  944. }
  945. try
  946. {
  947. lock (_configSyncLock)
  948. {
  949. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  950. }
  951. }
  952. catch (IOException)
  953. {
  954. return new UserConfiguration();
  955. }
  956. catch (Exception ex)
  957. {
  958. _logger.LogError(ex, "Error reading policy file: {path}", path);
  959. return new UserConfiguration();
  960. }
  961. }
  962. private readonly object _configSyncLock = new object();
  963. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  964. {
  965. var user = GetUserById(userId);
  966. UpdateConfiguration(user, config);
  967. }
  968. public void UpdateConfiguration(User user, UserConfiguration config)
  969. {
  970. UpdateConfiguration(user, config, true);
  971. }
  972. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  973. {
  974. var path = GetConfigurationFilePath(user);
  975. // The xml serializer will output differently if the type is not exact
  976. if (config.GetType() != typeof(UserConfiguration))
  977. {
  978. var json = _jsonSerializer.SerializeToString(config);
  979. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  980. }
  981. Directory.CreateDirectory(Path.GetDirectoryName(path));
  982. lock (_configSyncLock)
  983. {
  984. _xmlSerializer.SerializeToFile(config, path);
  985. user.Configuration = config;
  986. }
  987. if (fireEvent)
  988. {
  989. UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  990. }
  991. }
  992. }
  993. public class DeviceAccessEntryPoint : IServerEntryPoint
  994. {
  995. private IUserManager _userManager;
  996. private IAuthenticationRepository _authRepo;
  997. private IDeviceManager _deviceManager;
  998. private ISessionManager _sessionManager;
  999. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  1000. {
  1001. _userManager = userManager;
  1002. _authRepo = authRepo;
  1003. _deviceManager = deviceManager;
  1004. _sessionManager = sessionManager;
  1005. }
  1006. public void Run()
  1007. {
  1008. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  1009. }
  1010. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  1011. {
  1012. var user = e.Argument;
  1013. if (!user.Policy.EnableAllDevices)
  1014. {
  1015. UpdateDeviceAccess(user);
  1016. }
  1017. }
  1018. private void UpdateDeviceAccess(User user)
  1019. {
  1020. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1021. {
  1022. UserId = user.Id
  1023. }).Items;
  1024. foreach (var authInfo in existing)
  1025. {
  1026. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  1027. {
  1028. _sessionManager.Logout(authInfo);
  1029. }
  1030. }
  1031. }
  1032. public void Dispose()
  1033. {
  1034. }
  1035. }
  1036. }