UserManager.cs 39 KB

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