UserManager.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  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> { Argument = 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> { Argument = 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. // We should trust the user that the authprovider says, not what was typed
  249. username = updatedUsername;
  250. // Search the database for the user again; the authprovider might have created it
  251. user = Users
  252. .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  253. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy)
  254. {
  255. var policy = hasNewUserPolicy.GetNewUserPolicy();
  256. UpdateUserPolicy(user, policy, true);
  257. }
  258. }
  259. }
  260. if (success && user != null && authenticationProvider != null)
  261. {
  262. var providerId = GetAuthenticationProviderId(authenticationProvider);
  263. if (!string.Equals(providerId, user.Policy.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  264. {
  265. user.Policy.AuthenticationProviderId = providerId;
  266. UpdateUserPolicy(user, user.Policy, true);
  267. }
  268. }
  269. if (user == null)
  270. {
  271. throw new AuthenticationException("Invalid username or password entered.");
  272. }
  273. if (user.Policy.IsDisabled)
  274. {
  275. throw new AuthenticationException(
  276. string.Format(
  277. CultureInfo.InvariantCulture,
  278. "The {0} account is currently disabled. Please consult with your administrator.",
  279. user.Name));
  280. }
  281. if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint))
  282. {
  283. throw new AuthenticationException("Forbidden.");
  284. }
  285. if (!user.IsParentalScheduleAllowed())
  286. {
  287. throw new AuthenticationException("User is not allowed access at this time.");
  288. }
  289. // Update LastActivityDate and LastLoginDate, then save
  290. if (success)
  291. {
  292. if (isUserSession)
  293. {
  294. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  295. UpdateUser(user);
  296. }
  297. ResetInvalidLoginAttemptCount(user);
  298. }
  299. else
  300. {
  301. IncrementInvalidLoginAttemptCount(user);
  302. }
  303. _logger.LogInformation("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
  304. return success ? user : null;
  305. }
  306. #nullable enable
  307. private static string GetAuthenticationProviderId(IAuthenticationProvider provider)
  308. {
  309. return provider.GetType().FullName;
  310. }
  311. private static string GetPasswordResetProviderId(IPasswordResetProvider provider)
  312. {
  313. return provider.GetType().FullName;
  314. }
  315. private IAuthenticationProvider GetAuthenticationProvider(User user)
  316. {
  317. return GetAuthenticationProviders(user)[0];
  318. }
  319. private IPasswordResetProvider GetPasswordResetProvider(User user)
  320. {
  321. return GetPasswordResetProviders(user)[0];
  322. }
  323. private IAuthenticationProvider[] GetAuthenticationProviders(User? user)
  324. {
  325. var authenticationProviderId = user?.Policy.AuthenticationProviderId;
  326. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToArray();
  327. if (!string.IsNullOrEmpty(authenticationProviderId))
  328. {
  329. providers = providers.Where(i => string.Equals(authenticationProviderId, GetAuthenticationProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  330. }
  331. if (providers.Length == 0)
  332. {
  333. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  334. _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);
  335. providers = new IAuthenticationProvider[] { _invalidAuthProvider };
  336. }
  337. return providers;
  338. }
  339. private IPasswordResetProvider[] GetPasswordResetProviders(User? user)
  340. {
  341. var passwordResetProviderId = user?.Policy.PasswordResetProviderId;
  342. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  343. if (!string.IsNullOrEmpty(passwordResetProviderId))
  344. {
  345. providers = providers.Where(i => string.Equals(passwordResetProviderId, GetPasswordResetProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  346. }
  347. if (providers.Length == 0)
  348. {
  349. providers = new IPasswordResetProvider[] { _defaultPasswordResetProvider };
  350. }
  351. return providers;
  352. }
  353. private async Task<(string username, bool success)> AuthenticateWithProvider(
  354. IAuthenticationProvider provider,
  355. string username,
  356. string password,
  357. User? resolvedUser)
  358. {
  359. try
  360. {
  361. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  362. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  363. : await provider.Authenticate(username, password).ConfigureAwait(false);
  364. if (authenticationResult.Username != username)
  365. {
  366. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  367. username = authenticationResult.Username;
  368. }
  369. return (username, true);
  370. }
  371. catch (AuthenticationException ex)
  372. {
  373. _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
  374. return (username, false);
  375. }
  376. }
  377. private async Task<(IAuthenticationProvider? authenticationProvider, string username, bool success)> AuthenticateLocalUser(
  378. string username,
  379. string password,
  380. string hashedPassword,
  381. User? user,
  382. string remoteEndPoint)
  383. {
  384. bool success = false;
  385. IAuthenticationProvider? authenticationProvider = null;
  386. foreach (var provider in GetAuthenticationProviders(user))
  387. {
  388. var providerAuthResult = await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  389. var updatedUsername = providerAuthResult.username;
  390. success = providerAuthResult.success;
  391. if (success)
  392. {
  393. authenticationProvider = provider;
  394. username = updatedUsername;
  395. break;
  396. }
  397. }
  398. if (!success
  399. && _networkManager.IsInLocalNetwork(remoteEndPoint)
  400. && user?.Configuration.EnableLocalPassword == true
  401. && !string.IsNullOrEmpty(user.EasyPassword))
  402. {
  403. // Check easy password
  404. var passwordHash = PasswordHash.Parse(user.EasyPassword);
  405. var hash = _cryptoProvider.ComputeHash(
  406. passwordHash.Id,
  407. Encoding.UTF8.GetBytes(password),
  408. passwordHash.Salt);
  409. success = passwordHash.Hash.SequenceEqual(hash);
  410. }
  411. return (authenticationProvider, username, success);
  412. }
  413. private void ResetInvalidLoginAttemptCount(User user)
  414. {
  415. user.Policy.InvalidLoginAttemptCount = 0;
  416. UpdateUserPolicy(user, user.Policy, false);
  417. }
  418. private void IncrementInvalidLoginAttemptCount(User user)
  419. {
  420. int invalidLogins = ++user.Policy.InvalidLoginAttemptCount;
  421. int maxInvalidLogins = user.Policy.LoginAttemptsBeforeLockout;
  422. if (maxInvalidLogins > 0
  423. && invalidLogins >= maxInvalidLogins)
  424. {
  425. user.Policy.IsDisabled = true;
  426. UserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
  427. _logger.LogWarning(
  428. "Disabling user {UserName} due to {Attempts} unsuccessful login attempts.",
  429. user.Name,
  430. invalidLogins);
  431. }
  432. UpdateUserPolicy(user, user.Policy, false);
  433. }
  434. /// <summary>
  435. /// Loads the users from the repository.
  436. /// </summary>
  437. private void LoadUsers()
  438. {
  439. var users = _userRepository.RetrieveAllUsers();
  440. // There always has to be at least one user.
  441. if (users.Count != 0)
  442. {
  443. _users = new ConcurrentDictionary<Guid, User>(
  444. users.Select(x => new KeyValuePair<Guid, User>(x.Id, x)));
  445. return;
  446. }
  447. var defaultName = Environment.UserName;
  448. if (string.IsNullOrWhiteSpace(defaultName))
  449. {
  450. defaultName = "MyJellyfinUser";
  451. }
  452. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  453. var name = MakeValidUsername(defaultName);
  454. var user = InstantiateNewUser(name);
  455. user.DateLastSaved = DateTime.UtcNow;
  456. _userRepository.CreateUser(user);
  457. user.Policy.IsAdministrator = true;
  458. user.Policy.EnableContentDeletion = true;
  459. user.Policy.EnableRemoteControlOfOtherUsers = true;
  460. UpdateUserPolicy(user, user.Policy, false);
  461. _users = new ConcurrentDictionary<Guid, User>();
  462. _users[user.Id] = user;
  463. }
  464. #nullable restore
  465. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  466. {
  467. if (user == null)
  468. {
  469. throw new ArgumentNullException(nameof(user));
  470. }
  471. bool hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user);
  472. bool hasConfiguredEasyPassword = !string.IsNullOrEmpty(GetAuthenticationProvider(user).GetEasyPasswordHash(user));
  473. bool hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  474. hasConfiguredEasyPassword :
  475. hasConfiguredPassword;
  476. UserDto dto = new UserDto
  477. {
  478. Id = user.Id,
  479. Name = user.Name,
  480. HasPassword = hasPassword,
  481. HasConfiguredPassword = hasConfiguredPassword,
  482. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  483. LastActivityDate = user.LastActivityDate,
  484. LastLoginDate = user.LastLoginDate,
  485. Configuration = user.Configuration,
  486. ServerId = _appHost.SystemId,
  487. Policy = user.Policy
  488. };
  489. if (!hasPassword && _users.Count == 1)
  490. {
  491. dto.EnableAutoLogin = true;
  492. }
  493. ItemImageInfo image = user.GetImageInfo(ImageType.Primary, 0);
  494. if (image != null)
  495. {
  496. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  497. try
  498. {
  499. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  500. }
  501. catch (Exception ex)
  502. {
  503. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  504. _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {User}", user.Name);
  505. }
  506. }
  507. return dto;
  508. }
  509. public UserDto GetOfflineUserDto(User user)
  510. {
  511. var dto = GetUserDto(user);
  512. dto.ServerName = _appHost.FriendlyName;
  513. return dto;
  514. }
  515. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  516. {
  517. try
  518. {
  519. return _imageProcessorFactory().GetImageCacheTag(item, image);
  520. }
  521. catch (Exception ex)
  522. {
  523. _logger.LogError(ex, "Error getting {ImageType} image info for {ImagePath}", image.Type, image.Path);
  524. return null;
  525. }
  526. }
  527. /// <summary>
  528. /// Refreshes metadata for each user
  529. /// </summary>
  530. /// <param name="cancellationToken">The cancellation token.</param>
  531. /// <returns>Task.</returns>
  532. public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
  533. {
  534. foreach (var user in Users)
  535. {
  536. await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)), cancellationToken).ConfigureAwait(false);
  537. }
  538. }
  539. /// <summary>
  540. /// Renames the user.
  541. /// </summary>
  542. /// <param name="user">The user.</param>
  543. /// <param name="newName">The new name.</param>
  544. /// <returns>Task.</returns>
  545. /// <exception cref="ArgumentNullException">user</exception>
  546. /// <exception cref="ArgumentException"></exception>
  547. public async Task RenameUser(User user, string newName)
  548. {
  549. if (user == null)
  550. {
  551. throw new ArgumentNullException(nameof(user));
  552. }
  553. if (string.IsNullOrWhiteSpace(newName))
  554. {
  555. throw new ArgumentException("Invalid username", nameof(newName));
  556. }
  557. if (user.Name.Equals(newName, StringComparison.OrdinalIgnoreCase))
  558. {
  559. throw new ArgumentException("The new and old names must be different.");
  560. }
  561. if (Users.Any(
  562. u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  563. {
  564. throw new ArgumentException(string.Format(
  565. CultureInfo.InvariantCulture,
  566. "A user with the name '{0}' already exists.",
  567. newName));
  568. }
  569. await user.Rename(newName).ConfigureAwait(false);
  570. OnUserUpdated(user);
  571. }
  572. /// <summary>
  573. /// Updates the user.
  574. /// </summary>
  575. /// <param name="user">The user.</param>
  576. /// <exception cref="ArgumentNullException">user</exception>
  577. /// <exception cref="ArgumentException"></exception>
  578. public void UpdateUser(User user)
  579. {
  580. if (user == null)
  581. {
  582. throw new ArgumentNullException(nameof(user));
  583. }
  584. if (user.Id == Guid.Empty)
  585. {
  586. throw new ArgumentException("Id can't be empty.", nameof(user));
  587. }
  588. if (!_users.ContainsKey(user.Id))
  589. {
  590. throw new ArgumentException(
  591. string.Format(
  592. CultureInfo.InvariantCulture,
  593. "A user '{0}' with Id {1} does not exist.",
  594. user.Name,
  595. user.Id),
  596. nameof(user));
  597. }
  598. user.DateModified = DateTime.UtcNow;
  599. user.DateLastSaved = DateTime.UtcNow;
  600. _userRepository.UpdateUser(user);
  601. OnUserUpdated(user);
  602. }
  603. /// <summary>
  604. /// Creates the user.
  605. /// </summary>
  606. /// <param name="name">The name.</param>
  607. /// <returns>User.</returns>
  608. /// <exception cref="ArgumentNullException">name</exception>
  609. /// <exception cref="ArgumentException"></exception>
  610. public User CreateUser(string name)
  611. {
  612. if (string.IsNullOrWhiteSpace(name))
  613. {
  614. throw new ArgumentNullException(nameof(name));
  615. }
  616. if (!IsValidUsername(name))
  617. {
  618. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  619. }
  620. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  621. {
  622. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  623. }
  624. var user = InstantiateNewUser(name);
  625. _users[user.Id] = user;
  626. user.DateLastSaved = DateTime.UtcNow;
  627. _userRepository.CreateUser(user);
  628. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  629. return user;
  630. }
  631. /// <inheritdoc />
  632. /// <exception cref="ArgumentNullException">The <c>user</c> is <c>null</c>.</exception>
  633. /// <exception cref="ArgumentException">The <c>user</c> doesn't exist, or is the last administrator.</exception>
  634. /// <exception cref="InvalidOperationException">The <c>user</c> can't be deleted; there are no other users.</exception>
  635. public void DeleteUser(User user)
  636. {
  637. if (user == null)
  638. {
  639. throw new ArgumentNullException(nameof(user));
  640. }
  641. if (!_users.ContainsKey(user.Id))
  642. {
  643. throw new ArgumentException(string.Format(
  644. CultureInfo.InvariantCulture,
  645. "The user cannot be deleted because there is no user with the Name {0} and Id {1}.",
  646. user.Name,
  647. user.Id));
  648. }
  649. if (_users.Count == 1)
  650. {
  651. throw new InvalidOperationException(string.Format(
  652. CultureInfo.InvariantCulture,
  653. "The user '{0}' cannot be deleted because there must be at least one user in the system.",
  654. user.Name));
  655. }
  656. if (user.Policy.IsAdministrator
  657. && Users.Count(i => i.Policy.IsAdministrator) == 1)
  658. {
  659. throw new ArgumentException(
  660. string.Format(
  661. CultureInfo.InvariantCulture,
  662. "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
  663. user.Name),
  664. nameof(user));
  665. }
  666. var configPath = GetConfigurationFilePath(user);
  667. _userRepository.DeleteUser(user);
  668. // Delete user config dir
  669. lock (_configSyncLock)
  670. lock (_policySyncLock)
  671. {
  672. try
  673. {
  674. Directory.Delete(user.ConfigurationDirectoryPath, true);
  675. }
  676. catch (IOException ex)
  677. {
  678. _logger.LogError(ex, "Error deleting user config dir: {Path}", user.ConfigurationDirectoryPath);
  679. }
  680. }
  681. _users.TryRemove(user.Id, out _);
  682. OnUserDeleted(user);
  683. }
  684. /// <summary>
  685. /// Resets the password by clearing it.
  686. /// </summary>
  687. /// <returns>Task.</returns>
  688. public Task ResetPassword(User user)
  689. {
  690. return ChangePassword(user, string.Empty);
  691. }
  692. public void ResetEasyPassword(User user)
  693. {
  694. ChangeEasyPassword(user, string.Empty, null);
  695. }
  696. public async Task ChangePassword(User user, string newPassword)
  697. {
  698. if (user == null)
  699. {
  700. throw new ArgumentNullException(nameof(user));
  701. }
  702. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  703. UpdateUser(user);
  704. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  705. }
  706. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  707. {
  708. if (user == null)
  709. {
  710. throw new ArgumentNullException(nameof(user));
  711. }
  712. GetAuthenticationProvider(user).ChangeEasyPassword(user, newPassword, newPasswordHash);
  713. UpdateUser(user);
  714. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  715. }
  716. /// <summary>
  717. /// Instantiates the new user.
  718. /// </summary>
  719. /// <param name="name">The name.</param>
  720. /// <returns>User.</returns>
  721. private static User InstantiateNewUser(string name)
  722. {
  723. return new User
  724. {
  725. Name = name,
  726. Id = Guid.NewGuid(),
  727. DateCreated = DateTime.UtcNow,
  728. DateModified = DateTime.UtcNow
  729. };
  730. }
  731. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  732. {
  733. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  734. null :
  735. GetUserByName(enteredUsername);
  736. var action = ForgotPasswordAction.InNetworkRequired;
  737. if (user != null && isInNetwork)
  738. {
  739. var passwordResetProvider = GetPasswordResetProvider(user);
  740. return await passwordResetProvider.StartForgotPasswordProcess(user, isInNetwork).ConfigureAwait(false);
  741. }
  742. else
  743. {
  744. return new ForgotPasswordResult
  745. {
  746. Action = action,
  747. PinFile = string.Empty
  748. };
  749. }
  750. }
  751. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  752. {
  753. foreach (var provider in _passwordResetProviders)
  754. {
  755. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  756. if (result.Success)
  757. {
  758. return result;
  759. }
  760. }
  761. return new PinRedeemResult
  762. {
  763. Success = false,
  764. UsersReset = Array.Empty<string>()
  765. };
  766. }
  767. public UserPolicy GetUserPolicy(User user)
  768. {
  769. var path = GetPolicyFilePath(user);
  770. if (!File.Exists(path))
  771. {
  772. return GetDefaultPolicy();
  773. }
  774. try
  775. {
  776. lock (_policySyncLock)
  777. {
  778. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  779. }
  780. }
  781. catch (Exception ex)
  782. {
  783. _logger.LogError(ex, "Error reading policy file: {Path}", path);
  784. return GetDefaultPolicy();
  785. }
  786. }
  787. private static UserPolicy GetDefaultPolicy()
  788. {
  789. return new UserPolicy
  790. {
  791. EnableContentDownloading = true,
  792. EnableSyncTranscoding = true
  793. };
  794. }
  795. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  796. {
  797. var user = GetUserById(userId);
  798. UpdateUserPolicy(user, userPolicy, true);
  799. }
  800. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  801. {
  802. // The xml serializer will output differently if the type is not exact
  803. if (userPolicy.GetType() != typeof(UserPolicy))
  804. {
  805. var json = _jsonSerializer.SerializeToString(userPolicy);
  806. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  807. }
  808. var path = GetPolicyFilePath(user);
  809. Directory.CreateDirectory(Path.GetDirectoryName(path));
  810. lock (_policySyncLock)
  811. {
  812. _xmlSerializer.SerializeToFile(userPolicy, path);
  813. user.Policy = userPolicy;
  814. }
  815. if (fireEvent)
  816. {
  817. UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  818. }
  819. }
  820. private static string GetPolicyFilePath(User user)
  821. {
  822. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  823. }
  824. private static string GetConfigurationFilePath(User user)
  825. {
  826. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  827. }
  828. public UserConfiguration GetUserConfiguration(User user)
  829. {
  830. var path = GetConfigurationFilePath(user);
  831. if (!File.Exists(path))
  832. {
  833. return new UserConfiguration();
  834. }
  835. try
  836. {
  837. lock (_configSyncLock)
  838. {
  839. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  840. }
  841. }
  842. catch (Exception ex)
  843. {
  844. _logger.LogError(ex, "Error reading policy file: {Path}", path);
  845. return new UserConfiguration();
  846. }
  847. }
  848. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  849. {
  850. var user = GetUserById(userId);
  851. UpdateConfiguration(user, config);
  852. }
  853. public void UpdateConfiguration(User user, UserConfiguration config)
  854. {
  855. UpdateConfiguration(user, config, true);
  856. }
  857. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  858. {
  859. var path = GetConfigurationFilePath(user);
  860. // The xml serializer will output differently if the type is not exact
  861. if (config.GetType() != typeof(UserConfiguration))
  862. {
  863. var json = _jsonSerializer.SerializeToString(config);
  864. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  865. }
  866. Directory.CreateDirectory(Path.GetDirectoryName(path));
  867. lock (_configSyncLock)
  868. {
  869. _xmlSerializer.SerializeToFile(config, path);
  870. user.Configuration = config;
  871. }
  872. if (fireEvent)
  873. {
  874. UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  875. }
  876. }
  877. }
  878. public class DeviceAccessEntryPoint : IServerEntryPoint
  879. {
  880. private IUserManager _userManager;
  881. private IAuthenticationRepository _authRepo;
  882. private IDeviceManager _deviceManager;
  883. private ISessionManager _sessionManager;
  884. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  885. {
  886. _userManager = userManager;
  887. _authRepo = authRepo;
  888. _deviceManager = deviceManager;
  889. _sessionManager = sessionManager;
  890. }
  891. public Task RunAsync()
  892. {
  893. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  894. return Task.CompletedTask;
  895. }
  896. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  897. {
  898. var user = e.Argument;
  899. if (!user.Policy.EnableAllDevices)
  900. {
  901. UpdateDeviceAccess(user);
  902. }
  903. }
  904. private void UpdateDeviceAccess(User user)
  905. {
  906. var existing = _authRepo.Get(new AuthenticationInfoQuery
  907. {
  908. UserId = user.Id
  909. }).Items;
  910. foreach (var authInfo in existing)
  911. {
  912. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  913. {
  914. _sessionManager.Logout(authInfo);
  915. }
  916. }
  917. }
  918. public void Dispose()
  919. {
  920. }
  921. }
  922. }