UserManager.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Common.Cryptography;
  13. using MediaBrowser.Common.Events;
  14. using MediaBrowser.Common.Net;
  15. using MediaBrowser.Controller;
  16. using MediaBrowser.Controller.Authentication;
  17. using MediaBrowser.Controller.Devices;
  18. using MediaBrowser.Controller.Drawing;
  19. using MediaBrowser.Controller.Dto;
  20. using MediaBrowser.Controller.Entities;
  21. using MediaBrowser.Controller.Library;
  22. using MediaBrowser.Controller.Persistence;
  23. using MediaBrowser.Controller.Plugins;
  24. using MediaBrowser.Controller.Providers;
  25. using MediaBrowser.Controller.Security;
  26. using MediaBrowser.Controller.Session;
  27. using MediaBrowser.Model.Configuration;
  28. using MediaBrowser.Model.Cryptography;
  29. using MediaBrowser.Model.Dto;
  30. using MediaBrowser.Model.Entities;
  31. using MediaBrowser.Model.Events;
  32. using MediaBrowser.Model.IO;
  33. using MediaBrowser.Model.Serialization;
  34. using MediaBrowser.Model.Users;
  35. using Microsoft.Extensions.Logging;
  36. namespace Emby.Server.Implementations.Library
  37. {
  38. /// <summary>
  39. /// Class UserManager.
  40. /// </summary>
  41. public class UserManager : IUserManager
  42. {
  43. private readonly object _policySyncLock = new object();
  44. private readonly object _configSyncLock = new object();
  45. /// <summary>
  46. /// The logger.
  47. /// </summary>
  48. private readonly ILogger _logger;
  49. /// <summary>
  50. /// Gets the active user repository.
  51. /// </summary>
  52. /// <value>The user repository.</value>
  53. private readonly IUserRepository _userRepository;
  54. private readonly IXmlSerializer _xmlSerializer;
  55. private readonly IJsonSerializer _jsonSerializer;
  56. private readonly INetworkManager _networkManager;
  57. private readonly Func<IImageProcessor> _imageProcessorFactory;
  58. private readonly Func<IDtoService> _dtoServiceFactory;
  59. private readonly IServerApplicationHost _appHost;
  60. private readonly IFileSystem _fileSystem;
  61. private readonly ICryptoProvider _cryptoProvider;
  62. private ConcurrentDictionary<Guid, User> _users;
  63. private IAuthenticationProvider[] _authenticationProviders;
  64. private DefaultAuthenticationProvider _defaultAuthenticationProvider;
  65. private InvalidAuthProvider _invalidAuthProvider;
  66. private IPasswordResetProvider[] _passwordResetProviders;
  67. private DefaultPasswordResetProvider _defaultPasswordResetProvider;
  68. public UserManager(
  69. ILogger<UserManager> logger,
  70. IUserRepository userRepository,
  71. IXmlSerializer xmlSerializer,
  72. INetworkManager networkManager,
  73. Func<IImageProcessor> imageProcessorFactory,
  74. Func<IDtoService> dtoServiceFactory,
  75. IServerApplicationHost appHost,
  76. IJsonSerializer jsonSerializer,
  77. IFileSystem fileSystem,
  78. ICryptoProvider cryptoProvider)
  79. {
  80. _logger = logger;
  81. _userRepository = userRepository;
  82. _xmlSerializer = xmlSerializer;
  83. _networkManager = networkManager;
  84. _imageProcessorFactory = imageProcessorFactory;
  85. _dtoServiceFactory = dtoServiceFactory;
  86. _appHost = appHost;
  87. _jsonSerializer = jsonSerializer;
  88. _fileSystem = fileSystem;
  89. _cryptoProvider = cryptoProvider;
  90. _users = null;
  91. }
  92. public event EventHandler<GenericEventArgs<User>> UserPasswordChanged;
  93. /// <summary>
  94. /// Occurs when [user updated].
  95. /// </summary>
  96. public event EventHandler<GenericEventArgs<User>> UserUpdated;
  97. public event EventHandler<GenericEventArgs<User>> UserPolicyUpdated;
  98. public event EventHandler<GenericEventArgs<User>> UserConfigurationUpdated;
  99. public event EventHandler<GenericEventArgs<User>> UserLockedOut;
  100. public event EventHandler<GenericEventArgs<User>> UserCreated;
  101. /// <summary>
  102. /// Occurs when [user deleted].
  103. /// </summary>
  104. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  105. /// <inheritdoc />
  106. public IEnumerable<User> Users => _users.Values;
  107. /// <inheritdoc />
  108. public IEnumerable<Guid> UsersIds => _users.Keys;
  109. /// <summary>
  110. /// Called when [user updated].
  111. /// </summary>
  112. /// <param name="user">The user.</param>
  113. private void OnUserUpdated(User user)
  114. {
  115. UserUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  116. }
  117. /// <summary>
  118. /// Called when [user deleted].
  119. /// </summary>
  120. /// <param name="user">The user.</param>
  121. private void OnUserDeleted(User user)
  122. {
  123. UserDeleted?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  124. }
  125. public NameIdPair[] GetAuthenticationProviders()
  126. {
  127. return _authenticationProviders
  128. .Where(i => i.IsEnabled)
  129. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  130. .ThenBy(i => i.Name)
  131. .Select(i => new NameIdPair
  132. {
  133. Name = i.Name,
  134. Id = GetAuthenticationProviderId(i)
  135. })
  136. .ToArray();
  137. }
  138. public NameIdPair[] GetPasswordResetProviders()
  139. {
  140. return _passwordResetProviders
  141. .Where(i => i.IsEnabled)
  142. .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
  143. .ThenBy(i => i.Name)
  144. .Select(i => new NameIdPair
  145. {
  146. Name = i.Name,
  147. Id = GetPasswordResetProviderId(i)
  148. })
  149. .ToArray();
  150. }
  151. public void AddParts(IEnumerable<IAuthenticationProvider> authenticationProviders, IEnumerable<IPasswordResetProvider> passwordResetProviders)
  152. {
  153. _authenticationProviders = authenticationProviders.ToArray();
  154. _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
  155. _invalidAuthProvider = _authenticationProviders.OfType<InvalidAuthProvider>().First();
  156. _passwordResetProviders = passwordResetProviders.ToArray();
  157. _defaultPasswordResetProvider = passwordResetProviders.OfType<DefaultPasswordResetProvider>().First();
  158. }
  159. /// <inheritdoc />
  160. public User GetUserById(Guid id)
  161. {
  162. if (id == Guid.Empty)
  163. {
  164. throw new ArgumentException("Guid can't be empty", nameof(id));
  165. }
  166. _users.TryGetValue(id, out User user);
  167. return user;
  168. }
  169. public User GetUserByName(string name)
  170. {
  171. if (string.IsNullOrWhiteSpace(name))
  172. {
  173. throw new ArgumentException("Invalid username", nameof(name));
  174. }
  175. return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));
  176. }
  177. public void Initialize()
  178. {
  179. LoadUsers();
  180. var users = Users;
  181. // If there are no local users with admin rights, make them all admins
  182. if (!users.Any(i => i.Policy.IsAdministrator))
  183. {
  184. foreach (var user in users)
  185. {
  186. user.Policy.IsAdministrator = true;
  187. UpdateUserPolicy(user, user.Policy, false);
  188. }
  189. }
  190. }
  191. public static bool IsValidUsername(string username)
  192. {
  193. // This is some regex that matches only on unicode "word" characters, as well as -, _ and @
  194. // In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
  195. // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), and periods (.)
  196. return Regex.IsMatch(username, @"^[\w\-'._@]*$");
  197. }
  198. private static bool IsValidUsernameCharacter(char i)
  199. => IsValidUsername(i.ToString(CultureInfo.InvariantCulture));
  200. public string MakeValidUsername(string username)
  201. {
  202. if (IsValidUsername(username))
  203. {
  204. return username;
  205. }
  206. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  207. var builder = new StringBuilder();
  208. foreach (var c in username)
  209. {
  210. if (IsValidUsernameCharacter(c))
  211. {
  212. builder.Append(c);
  213. }
  214. }
  215. return builder.ToString();
  216. }
  217. public async Task<User> AuthenticateUser(
  218. string username,
  219. string password,
  220. string hashedPassword,
  221. string remoteEndPoint,
  222. bool isUserSession)
  223. {
  224. if (string.IsNullOrWhiteSpace(username))
  225. {
  226. _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
  227. throw new ArgumentNullException(nameof(username));
  228. }
  229. var user = Users.FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  230. var success = false;
  231. IAuthenticationProvider authenticationProvider = null;
  232. if (user != null)
  233. {
  234. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, user, remoteEndPoint).ConfigureAwait(false);
  235. authenticationProvider = authResult.authenticationProvider;
  236. success = authResult.success;
  237. }
  238. else
  239. {
  240. // user is null
  241. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, null, remoteEndPoint).ConfigureAwait(false);
  242. authenticationProvider = authResult.authenticationProvider;
  243. string updatedUsername = authResult.username;
  244. success = authResult.success;
  245. if (success
  246. && authenticationProvider != null
  247. && !(authenticationProvider is DefaultAuthenticationProvider))
  248. {
  249. // Trust the username returned by the authentication provider
  250. username = updatedUsername;
  251. // Search the database for the user again
  252. // the authentication provider might have created it
  253. user = Users
  254. .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  255. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy)
  256. {
  257. var policy = hasNewUserPolicy.GetNewUserPolicy();
  258. UpdateUserPolicy(user, policy, true);
  259. }
  260. }
  261. }
  262. if (success && user != null && authenticationProvider != null)
  263. {
  264. var providerId = GetAuthenticationProviderId(authenticationProvider);
  265. if (!string.Equals(providerId, user.Policy.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  266. {
  267. user.Policy.AuthenticationProviderId = providerId;
  268. UpdateUserPolicy(user, user.Policy, true);
  269. }
  270. }
  271. if (user == null)
  272. {
  273. _logger.LogInformation("Authentication request for {UserName} has been denied (IP: {IP}).", username, remoteEndPoint);
  274. throw new AuthenticationException("Invalid username or password entered.");
  275. }
  276. if (user.Policy.IsDisabled)
  277. {
  278. throw new AuthenticationException(
  279. string.Format(
  280. CultureInfo.InvariantCulture,
  281. "The {0} account is currently disabled. Please consult with your administrator.",
  282. user.Name));
  283. }
  284. if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint))
  285. {
  286. throw new AuthenticationException("Forbidden.");
  287. }
  288. if (!user.IsParentalScheduleAllowed())
  289. {
  290. throw new AuthenticationException("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. ResetInvalidLoginAttemptCount(user);
  301. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Name);
  302. }
  303. else
  304. {
  305. IncrementInvalidLoginAttemptCount(user);
  306. _logger.LogInformation("Authentication request for {UserName} has been denied (IP: {IP}).", user.Name, remoteEndPoint);
  307. }
  308. return success ? user : null;
  309. }
  310. #nullable enable
  311. private static string GetAuthenticationProviderId(IAuthenticationProvider provider)
  312. {
  313. return provider.GetType().FullName;
  314. }
  315. private static string GetPasswordResetProviderId(IPasswordResetProvider provider)
  316. {
  317. return provider.GetType().FullName;
  318. }
  319. private IAuthenticationProvider GetAuthenticationProvider(User user)
  320. {
  321. return GetAuthenticationProviders(user)[0];
  322. }
  323. private IPasswordResetProvider GetPasswordResetProvider(User user)
  324. {
  325. return GetPasswordResetProviders(user)[0];
  326. }
  327. private IAuthenticationProvider[] GetAuthenticationProviders(User? user)
  328. {
  329. var authenticationProviderId = user?.Policy.AuthenticationProviderId;
  330. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToArray();
  331. if (!string.IsNullOrEmpty(authenticationProviderId))
  332. {
  333. providers = providers.Where(i => string.Equals(authenticationProviderId, GetAuthenticationProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  334. }
  335. if (providers.Length == 0)
  336. {
  337. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  338. _logger.LogWarning("User {UserName} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected", user?.Name, user?.Policy.AuthenticationProviderId);
  339. providers = new IAuthenticationProvider[] { _invalidAuthProvider };
  340. }
  341. return providers;
  342. }
  343. private IPasswordResetProvider[] GetPasswordResetProviders(User? user)
  344. {
  345. var passwordResetProviderId = user?.Policy.PasswordResetProviderId;
  346. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  347. if (!string.IsNullOrEmpty(passwordResetProviderId))
  348. {
  349. providers = providers.Where(i => string.Equals(passwordResetProviderId, GetPasswordResetProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  350. }
  351. if (providers.Length == 0)
  352. {
  353. providers = new IPasswordResetProvider[] { _defaultPasswordResetProvider };
  354. }
  355. return providers;
  356. }
  357. private async Task<(string username, bool success)> AuthenticateWithProvider(
  358. IAuthenticationProvider provider,
  359. string username,
  360. string password,
  361. User? resolvedUser)
  362. {
  363. try
  364. {
  365. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  366. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  367. : await provider.Authenticate(username, password).ConfigureAwait(false);
  368. if (authenticationResult.Username != username)
  369. {
  370. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  371. username = authenticationResult.Username;
  372. }
  373. return (username, true);
  374. }
  375. catch (AuthenticationException ex)
  376. {
  377. _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
  378. return (username, false);
  379. }
  380. }
  381. private async Task<(IAuthenticationProvider? authenticationProvider, string username, bool success)> AuthenticateLocalUser(
  382. string username,
  383. string password,
  384. string hashedPassword,
  385. User? user,
  386. string remoteEndPoint)
  387. {
  388. bool success = false;
  389. IAuthenticationProvider? authenticationProvider = null;
  390. foreach (var provider in GetAuthenticationProviders(user))
  391. {
  392. var providerAuthResult = await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  393. var updatedUsername = providerAuthResult.username;
  394. success = providerAuthResult.success;
  395. if (success)
  396. {
  397. authenticationProvider = provider;
  398. username = updatedUsername;
  399. break;
  400. }
  401. }
  402. if (!success
  403. && _networkManager.IsInLocalNetwork(remoteEndPoint)
  404. && user?.Configuration.EnableLocalPassword == true
  405. && !string.IsNullOrEmpty(user.EasyPassword))
  406. {
  407. // Check easy password
  408. var passwordHash = PasswordHash.Parse(user.EasyPassword);
  409. var hash = _cryptoProvider.ComputeHash(
  410. passwordHash.Id,
  411. Encoding.UTF8.GetBytes(password),
  412. passwordHash.Salt.ToArray());
  413. success = passwordHash.Hash.SequenceEqual(hash);
  414. }
  415. return (authenticationProvider, username, success);
  416. }
  417. private void ResetInvalidLoginAttemptCount(User user)
  418. {
  419. user.Policy.InvalidLoginAttemptCount = 0;
  420. UpdateUserPolicy(user, user.Policy, false);
  421. }
  422. private void IncrementInvalidLoginAttemptCount(User user)
  423. {
  424. int invalidLogins = ++user.Policy.InvalidLoginAttemptCount;
  425. int maxInvalidLogins = user.Policy.LoginAttemptsBeforeLockout;
  426. if (maxInvalidLogins > 0
  427. && invalidLogins >= maxInvalidLogins)
  428. {
  429. user.Policy.IsDisabled = true;
  430. UserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
  431. _logger.LogWarning(
  432. "Disabling user {UserName} due to {Attempts} unsuccessful login attempts.",
  433. user.Name,
  434. invalidLogins);
  435. }
  436. UpdateUserPolicy(user, user.Policy, false);
  437. }
  438. /// <summary>
  439. /// Loads the users from the repository.
  440. /// </summary>
  441. private void LoadUsers()
  442. {
  443. var users = _userRepository.RetrieveAllUsers();
  444. // There always has to be at least one user.
  445. if (users.Count != 0)
  446. {
  447. _users = new ConcurrentDictionary<Guid, User>(
  448. users.Select(x => new KeyValuePair<Guid, User>(x.Id, x)));
  449. return;
  450. }
  451. var defaultName = Environment.UserName;
  452. if (string.IsNullOrWhiteSpace(defaultName))
  453. {
  454. defaultName = "MyJellyfinUser";
  455. }
  456. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  457. var name = MakeValidUsername(defaultName);
  458. var user = InstantiateNewUser(name);
  459. user.DateLastSaved = DateTime.UtcNow;
  460. _userRepository.CreateUser(user);
  461. user.Policy.IsAdministrator = true;
  462. user.Policy.EnableContentDeletion = true;
  463. user.Policy.EnableRemoteControlOfOtherUsers = true;
  464. UpdateUserPolicy(user, user.Policy, false);
  465. _users = new ConcurrentDictionary<Guid, User>();
  466. _users[user.Id] = user;
  467. }
  468. #nullable restore
  469. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  470. {
  471. if (user == null)
  472. {
  473. throw new ArgumentNullException(nameof(user));
  474. }
  475. bool hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user);
  476. bool hasConfiguredEasyPassword = !string.IsNullOrEmpty(GetAuthenticationProvider(user).GetEasyPasswordHash(user));
  477. bool hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  478. hasConfiguredEasyPassword :
  479. hasConfiguredPassword;
  480. UserDto dto = new UserDto
  481. {
  482. Id = user.Id,
  483. Name = user.Name,
  484. HasPassword = hasPassword,
  485. HasConfiguredPassword = hasConfiguredPassword,
  486. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  487. LastActivityDate = user.LastActivityDate,
  488. LastLoginDate = user.LastLoginDate,
  489. Configuration = user.Configuration,
  490. ServerId = _appHost.SystemId,
  491. Policy = user.Policy
  492. };
  493. if (!hasPassword && _users.Count == 1)
  494. {
  495. dto.EnableAutoLogin = true;
  496. }
  497. ItemImageInfo image = user.GetImageInfo(ImageType.Primary, 0);
  498. if (image != null)
  499. {
  500. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  501. try
  502. {
  503. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  504. }
  505. catch (Exception ex)
  506. {
  507. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  508. _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {User}", user.Name);
  509. }
  510. }
  511. return dto;
  512. }
  513. public UserDto GetOfflineUserDto(User user)
  514. {
  515. var dto = GetUserDto(user);
  516. dto.ServerName = _appHost.FriendlyName;
  517. return dto;
  518. }
  519. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  520. {
  521. try
  522. {
  523. return _imageProcessorFactory().GetImageCacheTag(item, image);
  524. }
  525. catch (Exception ex)
  526. {
  527. _logger.LogError(ex, "Error getting {ImageType} image info for {ImagePath}", image.Type, image.Path);
  528. return null;
  529. }
  530. }
  531. /// <summary>
  532. /// Refreshes metadata for each user
  533. /// </summary>
  534. /// <param name="cancellationToken">The cancellation token.</param>
  535. /// <returns>Task.</returns>
  536. public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
  537. {
  538. foreach (var user in Users)
  539. {
  540. await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)), cancellationToken).ConfigureAwait(false);
  541. }
  542. }
  543. /// <summary>
  544. /// Renames the user.
  545. /// </summary>
  546. /// <param name="user">The user.</param>
  547. /// <param name="newName">The new name.</param>
  548. /// <returns>Task.</returns>
  549. /// <exception cref="ArgumentNullException">user</exception>
  550. /// <exception cref="ArgumentException"></exception>
  551. public async Task RenameUser(User user, string newName)
  552. {
  553. if (user == null)
  554. {
  555. throw new ArgumentNullException(nameof(user));
  556. }
  557. if (string.IsNullOrWhiteSpace(newName))
  558. {
  559. throw new ArgumentException("Invalid username", nameof(newName));
  560. }
  561. if (user.Name.Equals(newName, StringComparison.Ordinal))
  562. {
  563. throw new ArgumentException("The new and old names must be different.");
  564. }
  565. if (Users.Any(
  566. u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  567. {
  568. throw new ArgumentException(string.Format(
  569. CultureInfo.InvariantCulture,
  570. "A user with the name '{0}' already exists.",
  571. newName));
  572. }
  573. await user.Rename(newName).ConfigureAwait(false);
  574. OnUserUpdated(user);
  575. }
  576. /// <summary>
  577. /// Updates the user.
  578. /// </summary>
  579. /// <param name="user">The user.</param>
  580. /// <exception cref="ArgumentNullException">user</exception>
  581. /// <exception cref="ArgumentException"></exception>
  582. public void UpdateUser(User user)
  583. {
  584. if (user == null)
  585. {
  586. throw new ArgumentNullException(nameof(user));
  587. }
  588. if (user.Id == Guid.Empty)
  589. {
  590. throw new ArgumentException("Id can't be empty.", nameof(user));
  591. }
  592. if (!_users.ContainsKey(user.Id))
  593. {
  594. throw new ArgumentException(
  595. string.Format(
  596. CultureInfo.InvariantCulture,
  597. "A user '{0}' with Id {1} does not exist.",
  598. user.Name,
  599. user.Id),
  600. nameof(user));
  601. }
  602. user.DateModified = DateTime.UtcNow;
  603. user.DateLastSaved = DateTime.UtcNow;
  604. _userRepository.UpdateUser(user);
  605. OnUserUpdated(user);
  606. }
  607. /// <summary>
  608. /// Creates the user.
  609. /// </summary>
  610. /// <param name="name">The name.</param>
  611. /// <returns>User.</returns>
  612. /// <exception cref="ArgumentNullException">name</exception>
  613. /// <exception cref="ArgumentException"></exception>
  614. public User CreateUser(string name)
  615. {
  616. if (string.IsNullOrWhiteSpace(name))
  617. {
  618. throw new ArgumentNullException(nameof(name));
  619. }
  620. if (!IsValidUsername(name))
  621. {
  622. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  623. }
  624. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  625. {
  626. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  627. }
  628. var user = InstantiateNewUser(name);
  629. _users[user.Id] = user;
  630. user.DateLastSaved = DateTime.UtcNow;
  631. _userRepository.CreateUser(user);
  632. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  633. return user;
  634. }
  635. /// <inheritdoc />
  636. /// <exception cref="ArgumentNullException">The <c>user</c> is <c>null</c>.</exception>
  637. /// <exception cref="ArgumentException">The <c>user</c> doesn't exist, or is the last administrator.</exception>
  638. /// <exception cref="InvalidOperationException">The <c>user</c> can't be deleted; there are no other users.</exception>
  639. public void DeleteUser(User user)
  640. {
  641. if (user == null)
  642. {
  643. throw new ArgumentNullException(nameof(user));
  644. }
  645. if (!_users.ContainsKey(user.Id))
  646. {
  647. throw new ArgumentException(string.Format(
  648. CultureInfo.InvariantCulture,
  649. "The user cannot be deleted because there is no user with the Name {0} and Id {1}.",
  650. user.Name,
  651. user.Id));
  652. }
  653. if (_users.Count == 1)
  654. {
  655. throw new InvalidOperationException(string.Format(
  656. CultureInfo.InvariantCulture,
  657. "The user '{0}' cannot be deleted because there must be at least one user in the system.",
  658. user.Name));
  659. }
  660. if (user.Policy.IsAdministrator
  661. && Users.Count(i => i.Policy.IsAdministrator) == 1)
  662. {
  663. throw new ArgumentException(
  664. string.Format(
  665. CultureInfo.InvariantCulture,
  666. "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
  667. user.Name),
  668. nameof(user));
  669. }
  670. var configPath = GetConfigurationFilePath(user);
  671. _userRepository.DeleteUser(user);
  672. // Delete user config dir
  673. lock (_configSyncLock)
  674. lock (_policySyncLock)
  675. {
  676. try
  677. {
  678. Directory.Delete(user.ConfigurationDirectoryPath, true);
  679. }
  680. catch (IOException ex)
  681. {
  682. _logger.LogError(ex, "Error deleting user config dir: {Path}", user.ConfigurationDirectoryPath);
  683. }
  684. }
  685. _users.TryRemove(user.Id, out _);
  686. OnUserDeleted(user);
  687. }
  688. /// <summary>
  689. /// Resets the password by clearing it.
  690. /// </summary>
  691. /// <returns>Task.</returns>
  692. public Task ResetPassword(User user)
  693. {
  694. return ChangePassword(user, string.Empty);
  695. }
  696. public void ResetEasyPassword(User user)
  697. {
  698. ChangeEasyPassword(user, string.Empty, null);
  699. }
  700. public async Task ChangePassword(User user, string newPassword)
  701. {
  702. if (user == null)
  703. {
  704. throw new ArgumentNullException(nameof(user));
  705. }
  706. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  707. UpdateUser(user);
  708. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  709. }
  710. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  711. {
  712. if (user == null)
  713. {
  714. throw new ArgumentNullException(nameof(user));
  715. }
  716. GetAuthenticationProvider(user).ChangeEasyPassword(user, newPassword, newPasswordHash);
  717. UpdateUser(user);
  718. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  719. }
  720. /// <summary>
  721. /// Instantiates the new user.
  722. /// </summary>
  723. /// <param name="name">The name.</param>
  724. /// <returns>User.</returns>
  725. private static User InstantiateNewUser(string name)
  726. {
  727. return new User
  728. {
  729. Name = name,
  730. Id = Guid.NewGuid(),
  731. DateCreated = DateTime.UtcNow,
  732. DateModified = DateTime.UtcNow
  733. };
  734. }
  735. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  736. {
  737. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  738. null :
  739. GetUserByName(enteredUsername);
  740. var action = ForgotPasswordAction.InNetworkRequired;
  741. if (user != null && isInNetwork)
  742. {
  743. var passwordResetProvider = GetPasswordResetProvider(user);
  744. return await passwordResetProvider.StartForgotPasswordProcess(user, isInNetwork).ConfigureAwait(false);
  745. }
  746. else
  747. {
  748. return new ForgotPasswordResult
  749. {
  750. Action = action,
  751. PinFile = string.Empty
  752. };
  753. }
  754. }
  755. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  756. {
  757. foreach (var provider in _passwordResetProviders)
  758. {
  759. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  760. if (result.Success)
  761. {
  762. return result;
  763. }
  764. }
  765. return new PinRedeemResult
  766. {
  767. Success = false,
  768. UsersReset = Array.Empty<string>()
  769. };
  770. }
  771. public UserPolicy GetUserPolicy(User user)
  772. {
  773. var path = GetPolicyFilePath(user);
  774. if (!File.Exists(path))
  775. {
  776. return GetDefaultPolicy();
  777. }
  778. try
  779. {
  780. lock (_policySyncLock)
  781. {
  782. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  783. }
  784. }
  785. catch (Exception ex)
  786. {
  787. _logger.LogError(ex, "Error reading policy file: {Path}", path);
  788. return GetDefaultPolicy();
  789. }
  790. }
  791. private static UserPolicy GetDefaultPolicy()
  792. {
  793. return new UserPolicy
  794. {
  795. EnableContentDownloading = true,
  796. EnableSyncTranscoding = true
  797. };
  798. }
  799. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  800. {
  801. var user = GetUserById(userId);
  802. UpdateUserPolicy(user, userPolicy, true);
  803. }
  804. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  805. {
  806. // The xml serializer will output differently if the type is not exact
  807. if (userPolicy.GetType() != typeof(UserPolicy))
  808. {
  809. var json = _jsonSerializer.SerializeToString(userPolicy);
  810. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  811. }
  812. var path = GetPolicyFilePath(user);
  813. Directory.CreateDirectory(Path.GetDirectoryName(path));
  814. lock (_policySyncLock)
  815. {
  816. _xmlSerializer.SerializeToFile(userPolicy, path);
  817. user.Policy = userPolicy;
  818. }
  819. if (fireEvent)
  820. {
  821. UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  822. }
  823. }
  824. private static string GetPolicyFilePath(User user)
  825. {
  826. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  827. }
  828. private static string GetConfigurationFilePath(User user)
  829. {
  830. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  831. }
  832. public UserConfiguration GetUserConfiguration(User user)
  833. {
  834. var path = GetConfigurationFilePath(user);
  835. if (!File.Exists(path))
  836. {
  837. return new UserConfiguration();
  838. }
  839. try
  840. {
  841. lock (_configSyncLock)
  842. {
  843. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  844. }
  845. }
  846. catch (Exception ex)
  847. {
  848. _logger.LogError(ex, "Error reading policy file: {Path}", path);
  849. return new UserConfiguration();
  850. }
  851. }
  852. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  853. {
  854. var user = GetUserById(userId);
  855. UpdateConfiguration(user, config);
  856. }
  857. public void UpdateConfiguration(User user, UserConfiguration config)
  858. {
  859. UpdateConfiguration(user, config, true);
  860. }
  861. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  862. {
  863. var path = GetConfigurationFilePath(user);
  864. // The xml serializer will output differently if the type is not exact
  865. if (config.GetType() != typeof(UserConfiguration))
  866. {
  867. var json = _jsonSerializer.SerializeToString(config);
  868. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  869. }
  870. Directory.CreateDirectory(Path.GetDirectoryName(path));
  871. lock (_configSyncLock)
  872. {
  873. _xmlSerializer.SerializeToFile(config, path);
  874. user.Configuration = config;
  875. }
  876. if (fireEvent)
  877. {
  878. UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  879. }
  880. }
  881. }
  882. public class DeviceAccessEntryPoint : IServerEntryPoint
  883. {
  884. private IUserManager _userManager;
  885. private IAuthenticationRepository _authRepo;
  886. private IDeviceManager _deviceManager;
  887. private ISessionManager _sessionManager;
  888. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  889. {
  890. _userManager = userManager;
  891. _authRepo = authRepo;
  892. _deviceManager = deviceManager;
  893. _sessionManager = sessionManager;
  894. }
  895. public Task RunAsync()
  896. {
  897. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  898. return Task.CompletedTask;
  899. }
  900. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  901. {
  902. var user = e.Argument;
  903. if (!user.Policy.EnableAllDevices)
  904. {
  905. UpdateDeviceAccess(user);
  906. }
  907. }
  908. private void UpdateDeviceAccess(User user)
  909. {
  910. var existing = _authRepo.Get(new AuthenticationInfoQuery
  911. {
  912. UserId = user.Id
  913. }).Items;
  914. foreach (var authInfo in existing)
  915. {
  916. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  917. {
  918. _sessionManager.Logout(authInfo);
  919. }
  920. }
  921. }
  922. public void Dispose()
  923. {
  924. }
  925. }
  926. }