UserManager.cs 39 KB

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