UserManager.cs 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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. /// <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 SecurityException($"The {user.Name} account is currently disabled. Please consult with your administrator.");
  278. }
  279. if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint))
  280. {
  281. throw new SecurityException("Forbidden.");
  282. }
  283. if (!user.IsParentalScheduleAllowed())
  284. {
  285. throw new SecurityException("User is not allowed access at this time.");
  286. }
  287. // Update LastActivityDate and LastLoginDate, then save
  288. if (success)
  289. {
  290. if (isUserSession)
  291. {
  292. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  293. UpdateUser(user);
  294. }
  295. ResetInvalidLoginAttemptCount(user);
  296. }
  297. else
  298. {
  299. IncrementInvalidLoginAttemptCount(user);
  300. }
  301. _logger.LogInformation("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
  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. _dtoServiceFactory().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 _imageProcessorFactory().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> { Argument = 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> { Argument = 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> { Argument = 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. }