UserManager.cs 38 KB

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