UserManager.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  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 _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> { Argument = 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> { Argument = 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 PublicUserDto GetPublicUserDto(User user, string remoteEndPoint = null)
  508. {
  509. if (user == null)
  510. {
  511. throw new ArgumentNullException(nameof(user));
  512. }
  513. IAuthenticationProvider authenticationProvider = GetAuthenticationProvider(user);
  514. bool hasConfiguredPassword = authenticationProvider.HasPassword(user);
  515. bool hasConfiguredEasyPassword = !string.IsNullOrEmpty(authenticationProvider.GetEasyPasswordHash(user));
  516. bool hasPassword = user.Configuration.EnableLocalPassword &&
  517. !string.IsNullOrEmpty(remoteEndPoint) &&
  518. _networkManager.IsInLocalNetwork(remoteEndPoint) ? hasConfiguredEasyPassword : hasConfiguredPassword;
  519. PublicUserDto dto = new PublicUserDto
  520. {
  521. Name = user.Name,
  522. HasPassword = hasPassword,
  523. HasConfiguredPassword = hasConfiguredPassword,
  524. };
  525. return dto;
  526. }
  527. public UserDto GetOfflineUserDto(User user)
  528. {
  529. var dto = GetUserDto(user);
  530. dto.ServerName = _appHost.FriendlyName;
  531. return dto;
  532. }
  533. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  534. {
  535. try
  536. {
  537. return _imageProcessor.GetImageCacheTag(item, image);
  538. }
  539. catch (Exception ex)
  540. {
  541. _logger.LogError(ex, "Error getting {ImageType} image info for {ImagePath}", image.Type, image.Path);
  542. return null;
  543. }
  544. }
  545. /// <summary>
  546. /// Refreshes metadata for each user
  547. /// </summary>
  548. /// <param name="cancellationToken">The cancellation token.</param>
  549. /// <returns>Task.</returns>
  550. public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
  551. {
  552. foreach (var user in Users)
  553. {
  554. await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)), cancellationToken).ConfigureAwait(false);
  555. }
  556. }
  557. /// <summary>
  558. /// Renames the user.
  559. /// </summary>
  560. /// <param name="user">The user.</param>
  561. /// <param name="newName">The new name.</param>
  562. /// <returns>Task.</returns>
  563. /// <exception cref="ArgumentNullException">user</exception>
  564. /// <exception cref="ArgumentException"></exception>
  565. public async Task RenameUser(User user, string newName)
  566. {
  567. if (user == null)
  568. {
  569. throw new ArgumentNullException(nameof(user));
  570. }
  571. if (string.IsNullOrWhiteSpace(newName))
  572. {
  573. throw new ArgumentException("Invalid username", nameof(newName));
  574. }
  575. if (user.Name.Equals(newName, StringComparison.Ordinal))
  576. {
  577. throw new ArgumentException("The new and old names must be different.");
  578. }
  579. if (Users.Any(
  580. u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  581. {
  582. throw new ArgumentException(string.Format(
  583. CultureInfo.InvariantCulture,
  584. "A user with the name '{0}' already exists.",
  585. newName));
  586. }
  587. await user.Rename(newName).ConfigureAwait(false);
  588. OnUserUpdated(user);
  589. }
  590. /// <summary>
  591. /// Updates the user.
  592. /// </summary>
  593. /// <param name="user">The user.</param>
  594. /// <exception cref="ArgumentNullException">user</exception>
  595. /// <exception cref="ArgumentException"></exception>
  596. public void UpdateUser(User user)
  597. {
  598. if (user == null)
  599. {
  600. throw new ArgumentNullException(nameof(user));
  601. }
  602. if (user.Id == Guid.Empty)
  603. {
  604. throw new ArgumentException("Id can't be empty.", nameof(user));
  605. }
  606. if (!_users.ContainsKey(user.Id))
  607. {
  608. throw new ArgumentException(
  609. string.Format(
  610. CultureInfo.InvariantCulture,
  611. "A user '{0}' with Id {1} does not exist.",
  612. user.Name,
  613. user.Id),
  614. nameof(user));
  615. }
  616. user.DateModified = DateTime.UtcNow;
  617. user.DateLastSaved = DateTime.UtcNow;
  618. _userRepository.UpdateUser(user);
  619. OnUserUpdated(user);
  620. }
  621. /// <summary>
  622. /// Creates the user.
  623. /// </summary>
  624. /// <param name="name">The name.</param>
  625. /// <returns>User.</returns>
  626. /// <exception cref="ArgumentNullException">name</exception>
  627. /// <exception cref="ArgumentException"></exception>
  628. public User CreateUser(string name)
  629. {
  630. if (string.IsNullOrWhiteSpace(name))
  631. {
  632. throw new ArgumentNullException(nameof(name));
  633. }
  634. if (!IsValidUsername(name))
  635. {
  636. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  637. }
  638. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  639. {
  640. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  641. }
  642. var user = InstantiateNewUser(name);
  643. _users[user.Id] = user;
  644. user.DateLastSaved = DateTime.UtcNow;
  645. _userRepository.CreateUser(user);
  646. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  647. return user;
  648. }
  649. /// <inheritdoc />
  650. /// <exception cref="ArgumentNullException">The <c>user</c> is <c>null</c>.</exception>
  651. /// <exception cref="ArgumentException">The <c>user</c> doesn't exist, or is the last administrator.</exception>
  652. /// <exception cref="InvalidOperationException">The <c>user</c> can't be deleted; there are no other users.</exception>
  653. public void DeleteUser(User user)
  654. {
  655. if (user == null)
  656. {
  657. throw new ArgumentNullException(nameof(user));
  658. }
  659. if (!_users.ContainsKey(user.Id))
  660. {
  661. throw new ArgumentException(string.Format(
  662. CultureInfo.InvariantCulture,
  663. "The user cannot be deleted because there is no user with the Name {0} and Id {1}.",
  664. user.Name,
  665. user.Id));
  666. }
  667. if (_users.Count == 1)
  668. {
  669. throw new InvalidOperationException(string.Format(
  670. CultureInfo.InvariantCulture,
  671. "The user '{0}' cannot be deleted because there must be at least one user in the system.",
  672. user.Name));
  673. }
  674. if (user.Policy.IsAdministrator
  675. && Users.Count(i => i.Policy.IsAdministrator) == 1)
  676. {
  677. throw new ArgumentException(
  678. string.Format(
  679. CultureInfo.InvariantCulture,
  680. "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
  681. user.Name),
  682. nameof(user));
  683. }
  684. var configPath = GetConfigurationFilePath(user);
  685. _userRepository.DeleteUser(user);
  686. // Delete user config dir
  687. lock (_configSyncLock)
  688. lock (_policySyncLock)
  689. {
  690. try
  691. {
  692. Directory.Delete(user.ConfigurationDirectoryPath, true);
  693. }
  694. catch (IOException ex)
  695. {
  696. _logger.LogError(ex, "Error deleting user config dir: {Path}", user.ConfigurationDirectoryPath);
  697. }
  698. }
  699. _users.TryRemove(user.Id, out _);
  700. OnUserDeleted(user);
  701. }
  702. /// <summary>
  703. /// Resets the password by clearing it.
  704. /// </summary>
  705. /// <returns>Task.</returns>
  706. public Task ResetPassword(User user)
  707. {
  708. return ChangePassword(user, string.Empty);
  709. }
  710. public void ResetEasyPassword(User user)
  711. {
  712. ChangeEasyPassword(user, string.Empty, null);
  713. }
  714. public async Task ChangePassword(User user, string newPassword)
  715. {
  716. if (user == null)
  717. {
  718. throw new ArgumentNullException(nameof(user));
  719. }
  720. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  721. UpdateUser(user);
  722. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  723. }
  724. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  725. {
  726. if (user == null)
  727. {
  728. throw new ArgumentNullException(nameof(user));
  729. }
  730. GetAuthenticationProvider(user).ChangeEasyPassword(user, newPassword, newPasswordHash);
  731. UpdateUser(user);
  732. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  733. }
  734. /// <summary>
  735. /// Instantiates the new user.
  736. /// </summary>
  737. /// <param name="name">The name.</param>
  738. /// <returns>User.</returns>
  739. private static User InstantiateNewUser(string name)
  740. {
  741. return new User
  742. {
  743. Name = name,
  744. Id = Guid.NewGuid(),
  745. DateCreated = DateTime.UtcNow,
  746. DateModified = DateTime.UtcNow
  747. };
  748. }
  749. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  750. {
  751. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  752. null :
  753. GetUserByName(enteredUsername);
  754. var action = ForgotPasswordAction.InNetworkRequired;
  755. if (user != null && isInNetwork)
  756. {
  757. var passwordResetProvider = GetPasswordResetProvider(user);
  758. return await passwordResetProvider.StartForgotPasswordProcess(user, isInNetwork).ConfigureAwait(false);
  759. }
  760. else
  761. {
  762. return new ForgotPasswordResult
  763. {
  764. Action = action,
  765. PinFile = string.Empty
  766. };
  767. }
  768. }
  769. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  770. {
  771. foreach (var provider in _passwordResetProviders)
  772. {
  773. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  774. if (result.Success)
  775. {
  776. return result;
  777. }
  778. }
  779. return new PinRedeemResult
  780. {
  781. Success = false,
  782. UsersReset = Array.Empty<string>()
  783. };
  784. }
  785. public UserPolicy GetUserPolicy(User user)
  786. {
  787. var path = GetPolicyFilePath(user);
  788. if (!File.Exists(path))
  789. {
  790. return GetDefaultPolicy();
  791. }
  792. try
  793. {
  794. lock (_policySyncLock)
  795. {
  796. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  797. }
  798. }
  799. catch (Exception ex)
  800. {
  801. _logger.LogError(ex, "Error reading policy file: {Path}", path);
  802. return GetDefaultPolicy();
  803. }
  804. }
  805. private static UserPolicy GetDefaultPolicy()
  806. {
  807. return new UserPolicy
  808. {
  809. EnableContentDownloading = true,
  810. EnableSyncTranscoding = true
  811. };
  812. }
  813. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  814. {
  815. var user = GetUserById(userId);
  816. UpdateUserPolicy(user, userPolicy, true);
  817. }
  818. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  819. {
  820. // The xml serializer will output differently if the type is not exact
  821. if (userPolicy.GetType() != typeof(UserPolicy))
  822. {
  823. var json = _jsonSerializer.SerializeToString(userPolicy);
  824. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  825. }
  826. var path = GetPolicyFilePath(user);
  827. Directory.CreateDirectory(Path.GetDirectoryName(path));
  828. lock (_policySyncLock)
  829. {
  830. _xmlSerializer.SerializeToFile(userPolicy, path);
  831. user.Policy = userPolicy;
  832. }
  833. if (fireEvent)
  834. {
  835. UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  836. }
  837. }
  838. private static string GetPolicyFilePath(User user)
  839. {
  840. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  841. }
  842. private static string GetConfigurationFilePath(User user)
  843. {
  844. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  845. }
  846. public UserConfiguration GetUserConfiguration(User user)
  847. {
  848. var path = GetConfigurationFilePath(user);
  849. if (!File.Exists(path))
  850. {
  851. return new UserConfiguration();
  852. }
  853. try
  854. {
  855. lock (_configSyncLock)
  856. {
  857. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  858. }
  859. }
  860. catch (Exception ex)
  861. {
  862. _logger.LogError(ex, "Error reading policy file: {Path}", path);
  863. return new UserConfiguration();
  864. }
  865. }
  866. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  867. {
  868. var user = GetUserById(userId);
  869. UpdateConfiguration(user, config);
  870. }
  871. public void UpdateConfiguration(User user, UserConfiguration config)
  872. {
  873. UpdateConfiguration(user, config, true);
  874. }
  875. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  876. {
  877. var path = GetConfigurationFilePath(user);
  878. // The xml serializer will output differently if the type is not exact
  879. if (config.GetType() != typeof(UserConfiguration))
  880. {
  881. var json = _jsonSerializer.SerializeToString(config);
  882. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  883. }
  884. Directory.CreateDirectory(Path.GetDirectoryName(path));
  885. lock (_configSyncLock)
  886. {
  887. _xmlSerializer.SerializeToFile(config, path);
  888. user.Configuration = config;
  889. }
  890. if (fireEvent)
  891. {
  892. UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  893. }
  894. }
  895. }
  896. public class DeviceAccessEntryPoint : IServerEntryPoint
  897. {
  898. private IUserManager _userManager;
  899. private IAuthenticationRepository _authRepo;
  900. private IDeviceManager _deviceManager;
  901. private ISessionManager _sessionManager;
  902. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  903. {
  904. _userManager = userManager;
  905. _authRepo = authRepo;
  906. _deviceManager = deviceManager;
  907. _sessionManager = sessionManager;
  908. }
  909. public Task RunAsync()
  910. {
  911. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  912. return Task.CompletedTask;
  913. }
  914. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  915. {
  916. var user = e.Argument;
  917. if (!user.Policy.EnableAllDevices)
  918. {
  919. UpdateDeviceAccess(user);
  920. }
  921. }
  922. private void UpdateDeviceAccess(User user)
  923. {
  924. var existing = _authRepo.Get(new AuthenticationInfoQuery
  925. {
  926. UserId = user.Id
  927. }).Items;
  928. foreach (var authInfo in existing)
  929. {
  930. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  931. {
  932. _sessionManager.Logout(authInfo);
  933. }
  934. }
  935. }
  936. public void Dispose()
  937. {
  938. }
  939. }
  940. }