UserManager.cs 39 KB

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