UserManager.cs 39 KB

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