UserManager.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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. _logger.LogInformation("Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).", username, remoteEndPoint);
  279. throw new AuthenticationException(
  280. string.Format(
  281. CultureInfo.InvariantCulture,
  282. "The {0} account is currently disabled. Please consult with your administrator.",
  283. user.Name));
  284. }
  285. if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint))
  286. {
  287. _logger.LogInformation("Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).", username, remoteEndPoint);
  288. throw new AuthenticationException("Forbidden.");
  289. }
  290. if (!user.IsParentalScheduleAllowed())
  291. {
  292. _logger.LogInformation("Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).", username, remoteEndPoint);
  293. throw new AuthenticationException("User is not allowed access at this time.");
  294. }
  295. // Update LastActivityDate and LastLoginDate, then save
  296. if (success)
  297. {
  298. if (isUserSession)
  299. {
  300. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  301. UpdateUser(user);
  302. }
  303. ResetInvalidLoginAttemptCount(user);
  304. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Name);
  305. }
  306. else
  307. {
  308. IncrementInvalidLoginAttemptCount(user);
  309. _logger.LogInformation("Authentication request for {UserName} has been denied (IP: {IP}).", user.Name, remoteEndPoint);
  310. }
  311. return success ? user : null;
  312. }
  313. #nullable enable
  314. private static string GetAuthenticationProviderId(IAuthenticationProvider provider)
  315. {
  316. return provider.GetType().FullName;
  317. }
  318. private static string GetPasswordResetProviderId(IPasswordResetProvider provider)
  319. {
  320. return provider.GetType().FullName;
  321. }
  322. private IAuthenticationProvider GetAuthenticationProvider(User user)
  323. {
  324. return GetAuthenticationProviders(user)[0];
  325. }
  326. private IPasswordResetProvider GetPasswordResetProvider(User user)
  327. {
  328. return GetPasswordResetProviders(user)[0];
  329. }
  330. private IAuthenticationProvider[] GetAuthenticationProviders(User? user)
  331. {
  332. var authenticationProviderId = user?.Policy.AuthenticationProviderId;
  333. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToArray();
  334. if (!string.IsNullOrEmpty(authenticationProviderId))
  335. {
  336. providers = providers.Where(i => string.Equals(authenticationProviderId, GetAuthenticationProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  337. }
  338. if (providers.Length == 0)
  339. {
  340. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  341. _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);
  342. providers = new IAuthenticationProvider[] { _invalidAuthProvider };
  343. }
  344. return providers;
  345. }
  346. private IPasswordResetProvider[] GetPasswordResetProviders(User? user)
  347. {
  348. var passwordResetProviderId = user?.Policy.PasswordResetProviderId;
  349. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  350. if (!string.IsNullOrEmpty(passwordResetProviderId))
  351. {
  352. providers = providers.Where(i => string.Equals(passwordResetProviderId, GetPasswordResetProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  353. }
  354. if (providers.Length == 0)
  355. {
  356. providers = new IPasswordResetProvider[] { _defaultPasswordResetProvider };
  357. }
  358. return providers;
  359. }
  360. private async Task<(string username, bool success)> AuthenticateWithProvider(
  361. IAuthenticationProvider provider,
  362. string username,
  363. string password,
  364. User? resolvedUser)
  365. {
  366. try
  367. {
  368. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  369. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  370. : await provider.Authenticate(username, password).ConfigureAwait(false);
  371. if (authenticationResult.Username != username)
  372. {
  373. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  374. username = authenticationResult.Username;
  375. }
  376. return (username, true);
  377. }
  378. catch (AuthenticationException ex)
  379. {
  380. _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
  381. return (username, false);
  382. }
  383. }
  384. private async Task<(IAuthenticationProvider? authenticationProvider, string username, bool success)> AuthenticateLocalUser(
  385. string username,
  386. string password,
  387. string hashedPassword,
  388. User? user,
  389. string remoteEndPoint)
  390. {
  391. bool success = false;
  392. IAuthenticationProvider? authenticationProvider = null;
  393. foreach (var provider in GetAuthenticationProviders(user))
  394. {
  395. var providerAuthResult = await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  396. var updatedUsername = providerAuthResult.username;
  397. success = providerAuthResult.success;
  398. if (success)
  399. {
  400. authenticationProvider = provider;
  401. username = updatedUsername;
  402. break;
  403. }
  404. }
  405. if (!success
  406. && _networkManager.IsInLocalNetwork(remoteEndPoint)
  407. && user?.Configuration.EnableLocalPassword == true
  408. && !string.IsNullOrEmpty(user.EasyPassword))
  409. {
  410. // Check easy password
  411. var passwordHash = PasswordHash.Parse(user.EasyPassword);
  412. var hash = _cryptoProvider.ComputeHash(
  413. passwordHash.Id,
  414. Encoding.UTF8.GetBytes(password),
  415. passwordHash.Salt.ToArray());
  416. success = passwordHash.Hash.SequenceEqual(hash);
  417. }
  418. return (authenticationProvider, username, success);
  419. }
  420. private void ResetInvalidLoginAttemptCount(User user)
  421. {
  422. user.Policy.InvalidLoginAttemptCount = 0;
  423. UpdateUserPolicy(user, user.Policy, false);
  424. }
  425. private void IncrementInvalidLoginAttemptCount(User user)
  426. {
  427. int invalidLogins = ++user.Policy.InvalidLoginAttemptCount;
  428. int maxInvalidLogins = user.Policy.LoginAttemptsBeforeLockout;
  429. if (maxInvalidLogins > 0
  430. && invalidLogins >= maxInvalidLogins)
  431. {
  432. user.Policy.IsDisabled = true;
  433. UserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
  434. _logger.LogWarning(
  435. "Disabling user {UserName} due to {Attempts} unsuccessful login attempts.",
  436. user.Name,
  437. invalidLogins);
  438. }
  439. UpdateUserPolicy(user, user.Policy, false);
  440. }
  441. /// <summary>
  442. /// Loads the users from the repository.
  443. /// </summary>
  444. private void LoadUsers()
  445. {
  446. var users = _userRepository.RetrieveAllUsers();
  447. // There always has to be at least one user.
  448. if (users.Count != 0)
  449. {
  450. _users = new ConcurrentDictionary<Guid, User>(
  451. users.Select(x => new KeyValuePair<Guid, User>(x.Id, x)));
  452. return;
  453. }
  454. var defaultName = Environment.UserName;
  455. if (string.IsNullOrWhiteSpace(defaultName))
  456. {
  457. defaultName = "MyJellyfinUser";
  458. }
  459. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  460. var name = MakeValidUsername(defaultName);
  461. var user = InstantiateNewUser(name);
  462. user.DateLastSaved = DateTime.UtcNow;
  463. _userRepository.CreateUser(user);
  464. user.Policy.IsAdministrator = true;
  465. user.Policy.EnableContentDeletion = true;
  466. user.Policy.EnableRemoteControlOfOtherUsers = true;
  467. UpdateUserPolicy(user, user.Policy, false);
  468. _users = new ConcurrentDictionary<Guid, User>();
  469. _users[user.Id] = user;
  470. }
  471. #nullable restore
  472. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  473. {
  474. if (user == null)
  475. {
  476. throw new ArgumentNullException(nameof(user));
  477. }
  478. bool hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user);
  479. bool hasConfiguredEasyPassword = !string.IsNullOrEmpty(GetAuthenticationProvider(user).GetEasyPasswordHash(user));
  480. bool hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  481. hasConfiguredEasyPassword :
  482. hasConfiguredPassword;
  483. UserDto dto = new UserDto
  484. {
  485. Id = user.Id,
  486. Name = user.Name,
  487. HasPassword = hasPassword,
  488. HasConfiguredPassword = hasConfiguredPassword,
  489. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  490. LastActivityDate = user.LastActivityDate,
  491. LastLoginDate = user.LastLoginDate,
  492. Configuration = user.Configuration,
  493. ServerId = _appHost.SystemId,
  494. Policy = user.Policy
  495. };
  496. if (!hasPassword && _users.Count == 1)
  497. {
  498. dto.EnableAutoLogin = true;
  499. }
  500. ItemImageInfo image = user.GetImageInfo(ImageType.Primary, 0);
  501. if (image != null)
  502. {
  503. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  504. try
  505. {
  506. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  507. }
  508. catch (Exception ex)
  509. {
  510. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  511. _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {User}", user.Name);
  512. }
  513. }
  514. return dto;
  515. }
  516. public UserDto GetOfflineUserDto(User user)
  517. {
  518. var dto = GetUserDto(user);
  519. dto.ServerName = _appHost.FriendlyName;
  520. return dto;
  521. }
  522. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  523. {
  524. try
  525. {
  526. return _imageProcessorFactory().GetImageCacheTag(item, image);
  527. }
  528. catch (Exception ex)
  529. {
  530. _logger.LogError(ex, "Error getting {ImageType} image info for {ImagePath}", image.Type, image.Path);
  531. return null;
  532. }
  533. }
  534. /// <summary>
  535. /// Refreshes metadata for each user
  536. /// </summary>
  537. /// <param name="cancellationToken">The cancellation token.</param>
  538. /// <returns>Task.</returns>
  539. public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
  540. {
  541. foreach (var user in Users)
  542. {
  543. await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)), cancellationToken).ConfigureAwait(false);
  544. }
  545. }
  546. /// <summary>
  547. /// Renames the user.
  548. /// </summary>
  549. /// <param name="user">The user.</param>
  550. /// <param name="newName">The new name.</param>
  551. /// <returns>Task.</returns>
  552. /// <exception cref="ArgumentNullException">user</exception>
  553. /// <exception cref="ArgumentException"></exception>
  554. public async Task RenameUser(User user, string newName)
  555. {
  556. if (user == null)
  557. {
  558. throw new ArgumentNullException(nameof(user));
  559. }
  560. if (string.IsNullOrWhiteSpace(newName))
  561. {
  562. throw new ArgumentException("Invalid username", nameof(newName));
  563. }
  564. if (user.Name.Equals(newName, StringComparison.Ordinal))
  565. {
  566. throw new ArgumentException("The new and old names must be different.");
  567. }
  568. if (Users.Any(
  569. u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  570. {
  571. throw new ArgumentException(string.Format(
  572. CultureInfo.InvariantCulture,
  573. "A user with the name '{0}' already exists.",
  574. newName));
  575. }
  576. await user.Rename(newName).ConfigureAwait(false);
  577. OnUserUpdated(user);
  578. }
  579. /// <summary>
  580. /// Updates the user.
  581. /// </summary>
  582. /// <param name="user">The user.</param>
  583. /// <exception cref="ArgumentNullException">user</exception>
  584. /// <exception cref="ArgumentException"></exception>
  585. public void UpdateUser(User user)
  586. {
  587. if (user == null)
  588. {
  589. throw new ArgumentNullException(nameof(user));
  590. }
  591. if (user.Id == Guid.Empty)
  592. {
  593. throw new ArgumentException("Id can't be empty.", nameof(user));
  594. }
  595. if (!_users.ContainsKey(user.Id))
  596. {
  597. throw new ArgumentException(
  598. string.Format(
  599. CultureInfo.InvariantCulture,
  600. "A user '{0}' with Id {1} does not exist.",
  601. user.Name,
  602. user.Id),
  603. nameof(user));
  604. }
  605. user.DateModified = DateTime.UtcNow;
  606. user.DateLastSaved = DateTime.UtcNow;
  607. _userRepository.UpdateUser(user);
  608. OnUserUpdated(user);
  609. }
  610. /// <summary>
  611. /// Creates the user.
  612. /// </summary>
  613. /// <param name="name">The name.</param>
  614. /// <returns>User.</returns>
  615. /// <exception cref="ArgumentNullException">name</exception>
  616. /// <exception cref="ArgumentException"></exception>
  617. public User CreateUser(string name)
  618. {
  619. if (string.IsNullOrWhiteSpace(name))
  620. {
  621. throw new ArgumentNullException(nameof(name));
  622. }
  623. if (!IsValidUsername(name))
  624. {
  625. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  626. }
  627. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  628. {
  629. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  630. }
  631. var user = InstantiateNewUser(name);
  632. _users[user.Id] = user;
  633. user.DateLastSaved = DateTime.UtcNow;
  634. _userRepository.CreateUser(user);
  635. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  636. return user;
  637. }
  638. /// <inheritdoc />
  639. /// <exception cref="ArgumentNullException">The <c>user</c> is <c>null</c>.</exception>
  640. /// <exception cref="ArgumentException">The <c>user</c> doesn't exist, or is the last administrator.</exception>
  641. /// <exception cref="InvalidOperationException">The <c>user</c> can't be deleted; there are no other users.</exception>
  642. public void DeleteUser(User user)
  643. {
  644. if (user == null)
  645. {
  646. throw new ArgumentNullException(nameof(user));
  647. }
  648. if (!_users.ContainsKey(user.Id))
  649. {
  650. throw new ArgumentException(string.Format(
  651. CultureInfo.InvariantCulture,
  652. "The user cannot be deleted because there is no user with the Name {0} and Id {1}.",
  653. user.Name,
  654. user.Id));
  655. }
  656. if (_users.Count == 1)
  657. {
  658. throw new InvalidOperationException(string.Format(
  659. CultureInfo.InvariantCulture,
  660. "The user '{0}' cannot be deleted because there must be at least one user in the system.",
  661. user.Name));
  662. }
  663. if (user.Policy.IsAdministrator
  664. && Users.Count(i => i.Policy.IsAdministrator) == 1)
  665. {
  666. throw new ArgumentException(
  667. string.Format(
  668. CultureInfo.InvariantCulture,
  669. "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
  670. user.Name),
  671. nameof(user));
  672. }
  673. var configPath = GetConfigurationFilePath(user);
  674. _userRepository.DeleteUser(user);
  675. // Delete user config dir
  676. lock (_configSyncLock)
  677. lock (_policySyncLock)
  678. {
  679. try
  680. {
  681. Directory.Delete(user.ConfigurationDirectoryPath, true);
  682. }
  683. catch (IOException ex)
  684. {
  685. _logger.LogError(ex, "Error deleting user config dir: {Path}", user.ConfigurationDirectoryPath);
  686. }
  687. }
  688. _users.TryRemove(user.Id, out _);
  689. OnUserDeleted(user);
  690. }
  691. /// <summary>
  692. /// Resets the password by clearing it.
  693. /// </summary>
  694. /// <returns>Task.</returns>
  695. public Task ResetPassword(User user)
  696. {
  697. return ChangePassword(user, string.Empty);
  698. }
  699. public void ResetEasyPassword(User user)
  700. {
  701. ChangeEasyPassword(user, string.Empty, null);
  702. }
  703. public async Task ChangePassword(User user, string newPassword)
  704. {
  705. if (user == null)
  706. {
  707. throw new ArgumentNullException(nameof(user));
  708. }
  709. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  710. UpdateUser(user);
  711. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  712. }
  713. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  714. {
  715. if (user == null)
  716. {
  717. throw new ArgumentNullException(nameof(user));
  718. }
  719. GetAuthenticationProvider(user).ChangeEasyPassword(user, newPassword, newPasswordHash);
  720. UpdateUser(user);
  721. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  722. }
  723. /// <summary>
  724. /// Instantiates the new user.
  725. /// </summary>
  726. /// <param name="name">The name.</param>
  727. /// <returns>User.</returns>
  728. private static User InstantiateNewUser(string name)
  729. {
  730. return new User
  731. {
  732. Name = name,
  733. Id = Guid.NewGuid(),
  734. DateCreated = DateTime.UtcNow,
  735. DateModified = DateTime.UtcNow
  736. };
  737. }
  738. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  739. {
  740. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  741. null :
  742. GetUserByName(enteredUsername);
  743. var action = ForgotPasswordAction.InNetworkRequired;
  744. if (user != null && isInNetwork)
  745. {
  746. var passwordResetProvider = GetPasswordResetProvider(user);
  747. return await passwordResetProvider.StartForgotPasswordProcess(user, isInNetwork).ConfigureAwait(false);
  748. }
  749. else
  750. {
  751. return new ForgotPasswordResult
  752. {
  753. Action = action,
  754. PinFile = string.Empty
  755. };
  756. }
  757. }
  758. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  759. {
  760. foreach (var provider in _passwordResetProviders)
  761. {
  762. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  763. if (result.Success)
  764. {
  765. return result;
  766. }
  767. }
  768. return new PinRedeemResult
  769. {
  770. Success = false,
  771. UsersReset = Array.Empty<string>()
  772. };
  773. }
  774. public UserPolicy GetUserPolicy(User user)
  775. {
  776. var path = GetPolicyFilePath(user);
  777. if (!File.Exists(path))
  778. {
  779. return GetDefaultPolicy();
  780. }
  781. try
  782. {
  783. lock (_policySyncLock)
  784. {
  785. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  786. }
  787. }
  788. catch (Exception ex)
  789. {
  790. _logger.LogError(ex, "Error reading policy file: {Path}", path);
  791. return GetDefaultPolicy();
  792. }
  793. }
  794. private static UserPolicy GetDefaultPolicy()
  795. {
  796. return new UserPolicy
  797. {
  798. EnableContentDownloading = true,
  799. EnableSyncTranscoding = true
  800. };
  801. }
  802. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  803. {
  804. var user = GetUserById(userId);
  805. UpdateUserPolicy(user, userPolicy, true);
  806. }
  807. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  808. {
  809. // The xml serializer will output differently if the type is not exact
  810. if (userPolicy.GetType() != typeof(UserPolicy))
  811. {
  812. var json = _jsonSerializer.SerializeToString(userPolicy);
  813. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  814. }
  815. var path = GetPolicyFilePath(user);
  816. Directory.CreateDirectory(Path.GetDirectoryName(path));
  817. lock (_policySyncLock)
  818. {
  819. _xmlSerializer.SerializeToFile(userPolicy, path);
  820. user.Policy = userPolicy;
  821. }
  822. if (fireEvent)
  823. {
  824. UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  825. }
  826. }
  827. private static string GetPolicyFilePath(User user)
  828. {
  829. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  830. }
  831. private static string GetConfigurationFilePath(User user)
  832. {
  833. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  834. }
  835. public UserConfiguration GetUserConfiguration(User user)
  836. {
  837. var path = GetConfigurationFilePath(user);
  838. if (!File.Exists(path))
  839. {
  840. return new UserConfiguration();
  841. }
  842. try
  843. {
  844. lock (_configSyncLock)
  845. {
  846. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  847. }
  848. }
  849. catch (Exception ex)
  850. {
  851. _logger.LogError(ex, "Error reading policy file: {Path}", path);
  852. return new UserConfiguration();
  853. }
  854. }
  855. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  856. {
  857. var user = GetUserById(userId);
  858. UpdateConfiguration(user, config);
  859. }
  860. public void UpdateConfiguration(User user, UserConfiguration config)
  861. {
  862. UpdateConfiguration(user, config, true);
  863. }
  864. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  865. {
  866. var path = GetConfigurationFilePath(user);
  867. // The xml serializer will output differently if the type is not exact
  868. if (config.GetType() != typeof(UserConfiguration))
  869. {
  870. var json = _jsonSerializer.SerializeToString(config);
  871. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  872. }
  873. Directory.CreateDirectory(Path.GetDirectoryName(path));
  874. lock (_configSyncLock)
  875. {
  876. _xmlSerializer.SerializeToFile(config, path);
  877. user.Configuration = config;
  878. }
  879. if (fireEvent)
  880. {
  881. UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  882. }
  883. }
  884. }
  885. public class DeviceAccessEntryPoint : IServerEntryPoint
  886. {
  887. private IUserManager _userManager;
  888. private IAuthenticationRepository _authRepo;
  889. private IDeviceManager _deviceManager;
  890. private ISessionManager _sessionManager;
  891. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  892. {
  893. _userManager = userManager;
  894. _authRepo = authRepo;
  895. _deviceManager = deviceManager;
  896. _sessionManager = sessionManager;
  897. }
  898. public Task RunAsync()
  899. {
  900. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  901. return Task.CompletedTask;
  902. }
  903. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  904. {
  905. var user = e.Argument;
  906. if (!user.Policy.EnableAllDevices)
  907. {
  908. UpdateDeviceAccess(user);
  909. }
  910. }
  911. private void UpdateDeviceAccess(User user)
  912. {
  913. var existing = _authRepo.Get(new AuthenticationInfoQuery
  914. {
  915. UserId = user.Id
  916. }).Items;
  917. foreach (var authInfo in existing)
  918. {
  919. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  920. {
  921. _sessionManager.Logout(authInfo);
  922. }
  923. }
  924. }
  925. public void Dispose()
  926. {
  927. }
  928. }
  929. }