UserManager.cs 39 KB

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