UserManager.cs 38 KB

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