UserManager.cs 39 KB

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