2
0

UserManager.cs 38 KB

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