UserManager.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  1. #pragma warning disable CS1591
  2. #pragma warning disable SA1600
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Text.RegularExpressions;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using MediaBrowser.Common.Cryptography;
  14. using MediaBrowser.Common.Events;
  15. using MediaBrowser.Common.Net;
  16. using MediaBrowser.Controller;
  17. using MediaBrowser.Controller.Authentication;
  18. using MediaBrowser.Controller.Devices;
  19. using MediaBrowser.Controller.Drawing;
  20. using MediaBrowser.Controller.Dto;
  21. using MediaBrowser.Controller.Entities;
  22. using MediaBrowser.Controller.Library;
  23. using MediaBrowser.Controller.Persistence;
  24. using MediaBrowser.Controller.Plugins;
  25. using MediaBrowser.Controller.Providers;
  26. using MediaBrowser.Controller.Security;
  27. using MediaBrowser.Controller.Session;
  28. using MediaBrowser.Model.Configuration;
  29. using MediaBrowser.Model.Cryptography;
  30. using MediaBrowser.Model.Dto;
  31. using MediaBrowser.Model.Entities;
  32. using MediaBrowser.Model.Events;
  33. using MediaBrowser.Model.IO;
  34. using MediaBrowser.Model.Serialization;
  35. using MediaBrowser.Model.Users;
  36. using Microsoft.Extensions.Logging;
  37. namespace Emby.Server.Implementations.Library
  38. {
  39. /// <summary>
  40. /// Class UserManager.
  41. /// </summary>
  42. public class UserManager : IUserManager
  43. {
  44. /// <summary>
  45. /// The logger.
  46. /// </summary>
  47. private readonly ILogger _logger;
  48. private readonly object _policySyncLock = new object();
  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(string username, string password, string hashedPassword, string remoteEndPoint, bool isUserSession)
  218. {
  219. if (string.IsNullOrWhiteSpace(username))
  220. {
  221. throw new ArgumentNullException(nameof(username));
  222. }
  223. var user = Users.FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  224. var success = false;
  225. IAuthenticationProvider authenticationProvider = null;
  226. if (user != null)
  227. {
  228. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, user, remoteEndPoint).ConfigureAwait(false);
  229. authenticationProvider = authResult.authenticationProvider;
  230. success = authResult.success;
  231. }
  232. else
  233. {
  234. // user is null
  235. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, null, remoteEndPoint).ConfigureAwait(false);
  236. authenticationProvider = authResult.authenticationProvider;
  237. string updatedUsername = authResult.username;
  238. success = authResult.success;
  239. if (success
  240. && authenticationProvider != null
  241. && !(authenticationProvider is DefaultAuthenticationProvider))
  242. {
  243. // We should trust the user that the authprovider says, not what was typed
  244. username = updatedUsername;
  245. // Search the database for the user again; the authprovider 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
  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. _dtoServiceFactory().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 _imageProcessorFactory().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.OrdinalIgnoreCase))
  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. /// <summary>
  627. /// Deletes the user.
  628. /// </summary>
  629. /// <param name="user">The user.</param>
  630. /// <returns>Task.</returns>
  631. /// <exception cref="ArgumentNullException">user</exception>
  632. /// <exception cref="ArgumentException"></exception>
  633. public void DeleteUser(User user)
  634. {
  635. if (user == null)
  636. {
  637. throw new ArgumentNullException(nameof(user));
  638. }
  639. if (!_users.ContainsKey(user.Id))
  640. {
  641. throw new ArgumentException(string.Format(
  642. CultureInfo.InvariantCulture,
  643. "The user cannot be deleted because there is no user with the Name {0} and Id {1}.",
  644. user.Name,
  645. user.Id));
  646. }
  647. if (_users.Count == 1)
  648. {
  649. throw new ArgumentException(string.Format(
  650. CultureInfo.InvariantCulture,
  651. "The user '{0}' cannot be deleted because there must be at least one user in the system.",
  652. user.Name));
  653. }
  654. if (user.Policy.IsAdministrator
  655. && Users.Count(i => i.Policy.IsAdministrator) == 1)
  656. {
  657. throw new ArgumentException(
  658. string.Format(
  659. CultureInfo.InvariantCulture,
  660. "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
  661. user.Name),
  662. nameof(user));
  663. }
  664. var configPath = GetConfigurationFilePath(user);
  665. _userRepository.DeleteUser(user);
  666. try
  667. {
  668. _fileSystem.DeleteFile(configPath);
  669. }
  670. catch (IOException ex)
  671. {
  672. _logger.LogError(ex, "Error deleting file {path}", configPath);
  673. }
  674. DeleteUserPolicy(user);
  675. _users.TryRemove(user.Id, out _);
  676. OnUserDeleted(user);
  677. }
  678. /// <summary>
  679. /// Resets the password by clearing it.
  680. /// </summary>
  681. /// <returns>Task.</returns>
  682. public Task ResetPassword(User user)
  683. {
  684. return ChangePassword(user, string.Empty);
  685. }
  686. public void ResetEasyPassword(User user)
  687. {
  688. ChangeEasyPassword(user, string.Empty, null);
  689. }
  690. public async Task ChangePassword(User user, string newPassword)
  691. {
  692. if (user == null)
  693. {
  694. throw new ArgumentNullException(nameof(user));
  695. }
  696. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  697. UpdateUser(user);
  698. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  699. }
  700. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  701. {
  702. if (user == null)
  703. {
  704. throw new ArgumentNullException(nameof(user));
  705. }
  706. GetAuthenticationProvider(user).ChangeEasyPassword(user, newPassword, newPasswordHash);
  707. UpdateUser(user);
  708. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  709. }
  710. /// <summary>
  711. /// Instantiates the new user.
  712. /// </summary>
  713. /// <param name="name">The name.</param>
  714. /// <returns>User.</returns>
  715. private static User InstantiateNewUser(string name)
  716. {
  717. return new User
  718. {
  719. Name = name,
  720. Id = Guid.NewGuid(),
  721. DateCreated = DateTime.UtcNow,
  722. DateModified = DateTime.UtcNow
  723. };
  724. }
  725. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  726. {
  727. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  728. null :
  729. GetUserByName(enteredUsername);
  730. var action = ForgotPasswordAction.InNetworkRequired;
  731. if (user != null && isInNetwork)
  732. {
  733. var passwordResetProvider = GetPasswordResetProvider(user);
  734. return await passwordResetProvider.StartForgotPasswordProcess(user, isInNetwork).ConfigureAwait(false);
  735. }
  736. else
  737. {
  738. return new ForgotPasswordResult
  739. {
  740. Action = action,
  741. PinFile = string.Empty
  742. };
  743. }
  744. }
  745. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  746. {
  747. foreach (var provider in _passwordResetProviders)
  748. {
  749. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  750. if (result.Success)
  751. {
  752. return result;
  753. }
  754. }
  755. return new PinRedeemResult
  756. {
  757. Success = false,
  758. UsersReset = Array.Empty<string>()
  759. };
  760. }
  761. public UserPolicy GetUserPolicy(User user)
  762. {
  763. var path = GetPolicyFilePath(user);
  764. if (!File.Exists(path))
  765. {
  766. return GetDefaultPolicy(user);
  767. }
  768. try
  769. {
  770. lock (_policySyncLock)
  771. {
  772. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  773. }
  774. }
  775. catch (IOException)
  776. {
  777. return GetDefaultPolicy(user);
  778. }
  779. catch (Exception ex)
  780. {
  781. _logger.LogError(ex, "Error reading policy file: {path}", path);
  782. return GetDefaultPolicy(user);
  783. }
  784. }
  785. private static UserPolicy GetDefaultPolicy(User user)
  786. {
  787. return new UserPolicy
  788. {
  789. EnableContentDownloading = true,
  790. EnableSyncTranscoding = true
  791. };
  792. }
  793. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  794. {
  795. var user = GetUserById(userId);
  796. UpdateUserPolicy(user, userPolicy, true);
  797. }
  798. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  799. {
  800. // The xml serializer will output differently if the type is not exact
  801. if (userPolicy.GetType() != typeof(UserPolicy))
  802. {
  803. var json = _jsonSerializer.SerializeToString(userPolicy);
  804. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  805. }
  806. var path = GetPolicyFilePath(user);
  807. Directory.CreateDirectory(Path.GetDirectoryName(path));
  808. lock (_policySyncLock)
  809. {
  810. _xmlSerializer.SerializeToFile(userPolicy, path);
  811. user.Policy = userPolicy;
  812. }
  813. if (fireEvent)
  814. {
  815. UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  816. }
  817. }
  818. private void DeleteUserPolicy(User user)
  819. {
  820. var path = GetPolicyFilePath(user);
  821. try
  822. {
  823. lock (_policySyncLock)
  824. {
  825. _fileSystem.DeleteFile(path);
  826. }
  827. }
  828. catch (IOException)
  829. {
  830. }
  831. catch (Exception ex)
  832. {
  833. _logger.LogError(ex, "Error deleting policy file");
  834. }
  835. }
  836. private static string GetPolicyFilePath(User user)
  837. {
  838. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  839. }
  840. private static string GetConfigurationFilePath(User user)
  841. {
  842. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  843. }
  844. public UserConfiguration GetUserConfiguration(User user)
  845. {
  846. var path = GetConfigurationFilePath(user);
  847. if (!File.Exists(path))
  848. {
  849. return new UserConfiguration();
  850. }
  851. try
  852. {
  853. lock (_configSyncLock)
  854. {
  855. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  856. }
  857. }
  858. catch (IOException)
  859. {
  860. return new UserConfiguration();
  861. }
  862. catch (Exception ex)
  863. {
  864. _logger.LogError(ex, "Error reading policy file: {path}", path);
  865. return new UserConfiguration();
  866. }
  867. }
  868. private readonly object _configSyncLock = new object();
  869. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  870. {
  871. var user = GetUserById(userId);
  872. UpdateConfiguration(user, config);
  873. }
  874. public void UpdateConfiguration(User user, UserConfiguration config)
  875. {
  876. UpdateConfiguration(user, config, true);
  877. }
  878. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  879. {
  880. var path = GetConfigurationFilePath(user);
  881. // The xml serializer will output differently if the type is not exact
  882. if (config.GetType() != typeof(UserConfiguration))
  883. {
  884. var json = _jsonSerializer.SerializeToString(config);
  885. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  886. }
  887. Directory.CreateDirectory(Path.GetDirectoryName(path));
  888. lock (_configSyncLock)
  889. {
  890. _xmlSerializer.SerializeToFile(config, path);
  891. user.Configuration = config;
  892. }
  893. if (fireEvent)
  894. {
  895. UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  896. }
  897. }
  898. }
  899. public class DeviceAccessEntryPoint : IServerEntryPoint
  900. {
  901. private IUserManager _userManager;
  902. private IAuthenticationRepository _authRepo;
  903. private IDeviceManager _deviceManager;
  904. private ISessionManager _sessionManager;
  905. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  906. {
  907. _userManager = userManager;
  908. _authRepo = authRepo;
  909. _deviceManager = deviceManager;
  910. _sessionManager = sessionManager;
  911. }
  912. public Task RunAsync()
  913. {
  914. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  915. return Task.CompletedTask;
  916. }
  917. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  918. {
  919. var user = e.Argument;
  920. if (!user.Policy.EnableAllDevices)
  921. {
  922. UpdateDeviceAccess(user);
  923. }
  924. }
  925. private void UpdateDeviceAccess(User user)
  926. {
  927. var existing = _authRepo.Get(new AuthenticationInfoQuery
  928. {
  929. UserId = user.Id
  930. }).Items;
  931. foreach (var authInfo in existing)
  932. {
  933. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  934. {
  935. _sessionManager.Logout(authInfo);
  936. }
  937. }
  938. }
  939. public void Dispose()
  940. {
  941. }
  942. }
  943. }