UserManager.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  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. using static MediaBrowser.Common.HexHelper;
  36. namespace Emby.Server.Implementations.Library
  37. {
  38. /// <summary>
  39. /// Class UserManager
  40. /// </summary>
  41. public class UserManager : IUserManager
  42. {
  43. /// <summary>
  44. /// The _logger
  45. /// </summary>
  46. private readonly ILogger _logger;
  47. private readonly object _policySyncLock = new object();
  48. /// <summary>
  49. /// Gets the active user repository
  50. /// </summary>
  51. /// <value>The user repository.</value>
  52. private readonly IUserRepository _userRepository;
  53. private readonly IXmlSerializer _xmlSerializer;
  54. private readonly IJsonSerializer _jsonSerializer;
  55. private readonly INetworkManager _networkManager;
  56. private readonly Func<IImageProcessor> _imageProcessorFactory;
  57. private readonly Func<IDtoService> _dtoServiceFactory;
  58. private readonly IServerApplicationHost _appHost;
  59. private readonly IFileSystem _fileSystem;
  60. private readonly ICryptoProvider _cryptoProvider;
  61. private ConcurrentDictionary<Guid, User> _users;
  62. private IAuthenticationProvider[] _authenticationProviders;
  63. private DefaultAuthenticationProvider _defaultAuthenticationProvider;
  64. private InvalidAuthProvider _invalidAuthProvider;
  65. private IPasswordResetProvider[] _passwordResetProviders;
  66. private DefaultPasswordResetProvider _defaultPasswordResetProvider;
  67. public UserManager(
  68. ILogger<UserManager> logger,
  69. IUserRepository userRepository,
  70. IXmlSerializer xmlSerializer,
  71. INetworkManager networkManager,
  72. Func<IImageProcessor> imageProcessorFactory,
  73. Func<IDtoService> dtoServiceFactory,
  74. IServerApplicationHost appHost,
  75. IJsonSerializer jsonSerializer,
  76. IFileSystem fileSystem,
  77. ICryptoProvider cryptoProvider)
  78. {
  79. _logger = logger;
  80. _userRepository = userRepository;
  81. _xmlSerializer = xmlSerializer;
  82. _networkManager = networkManager;
  83. _imageProcessorFactory = imageProcessorFactory;
  84. _dtoServiceFactory = dtoServiceFactory;
  85. _appHost = appHost;
  86. _jsonSerializer = jsonSerializer;
  87. _fileSystem = fileSystem;
  88. _cryptoProvider = cryptoProvider;
  89. _users = null;
  90. }
  91. public event EventHandler<GenericEventArgs<User>> UserPasswordChanged;
  92. /// <summary>
  93. /// Occurs when [user updated].
  94. /// </summary>
  95. public event EventHandler<GenericEventArgs<User>> UserUpdated;
  96. public event EventHandler<GenericEventArgs<User>> UserPolicyUpdated;
  97. public event EventHandler<GenericEventArgs<User>> UserConfigurationUpdated;
  98. public event EventHandler<GenericEventArgs<User>> UserLockedOut;
  99. public event EventHandler<GenericEventArgs<User>> UserCreated;
  100. /// <summary>
  101. /// Occurs when [user deleted].
  102. /// </summary>
  103. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  104. /// <inheritdoc />
  105. public IEnumerable<User> Users => _users.Values;
  106. /// <inheritdoc />
  107. public IEnumerable<Guid> UsersIds => _users.Keys;
  108. /// <summary>
  109. /// Called when [user updated].
  110. /// </summary>
  111. /// <param name="user">The user.</param>
  112. private void OnUserUpdated(User user)
  113. {
  114. UserUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  115. }
  116. /// <summary>
  117. /// Called when [user deleted].
  118. /// </summary>
  119. /// <param name="user">The user.</param>
  120. private void OnUserDeleted(User user)
  121. {
  122. UserDeleted?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  123. }
  124. public NameIdPair[] GetAuthenticationProviders()
  125. {
  126. return _authenticationProviders
  127. .Where(i => i.IsEnabled)
  128. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  129. .ThenBy(i => i.Name)
  130. .Select(i => new NameIdPair
  131. {
  132. Name = i.Name,
  133. Id = GetAuthenticationProviderId(i)
  134. })
  135. .ToArray();
  136. }
  137. public NameIdPair[] GetPasswordResetProviders()
  138. {
  139. return _passwordResetProviders
  140. .Where(i => i.IsEnabled)
  141. .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
  142. .ThenBy(i => i.Name)
  143. .Select(i => new NameIdPair
  144. {
  145. Name = i.Name,
  146. Id = GetPasswordResetProviderId(i)
  147. })
  148. .ToArray();
  149. }
  150. public void AddParts(IEnumerable<IAuthenticationProvider> authenticationProviders, IEnumerable<IPasswordResetProvider> passwordResetProviders)
  151. {
  152. _authenticationProviders = authenticationProviders.ToArray();
  153. _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
  154. _invalidAuthProvider = _authenticationProviders.OfType<InvalidAuthProvider>().First();
  155. _passwordResetProviders = passwordResetProviders.ToArray();
  156. _defaultPasswordResetProvider = passwordResetProviders.OfType<DefaultPasswordResetProvider>().First();
  157. }
  158. /// <summary>
  159. /// Gets a User by Id.
  160. /// </summary>
  161. /// <param name="id">The id.</param>
  162. /// <returns>User.</returns>
  163. /// <exception cref="ArgumentException"></exception>
  164. public User GetUserById(Guid id)
  165. {
  166. if (id == Guid.Empty)
  167. {
  168. throw new ArgumentException("Guid can't be empty", nameof(id));
  169. }
  170. _users.TryGetValue(id, out User user);
  171. return user;
  172. }
  173. /// <summary>
  174. /// Gets the user by identifier.
  175. /// </summary>
  176. /// <param name="id">The identifier.</param>
  177. /// <returns>User.</returns>
  178. public User GetUserById(string id)
  179. => GetUserById(new Guid(id));
  180. public User GetUserByName(string name)
  181. {
  182. if (string.IsNullOrWhiteSpace(name))
  183. {
  184. throw new ArgumentException("Invalid username", nameof(name));
  185. }
  186. return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));
  187. }
  188. public void Initialize()
  189. {
  190. LoadUsers();
  191. var users = Users;
  192. // If there are no local users with admin rights, make them all admins
  193. if (!users.Any(i => i.Policy.IsAdministrator))
  194. {
  195. foreach (var user in users)
  196. {
  197. user.Policy.IsAdministrator = true;
  198. UpdateUserPolicy(user, user.Policy, false);
  199. }
  200. }
  201. }
  202. public static bool IsValidUsername(string username)
  203. {
  204. // This is some regex that matches only on unicode "word" characters, as well as -, _ and @
  205. // In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
  206. // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), and periods (.)
  207. return Regex.IsMatch(username, @"^[\w\-'._@]*$");
  208. }
  209. private static bool IsValidUsernameCharacter(char i)
  210. => IsValidUsername(i.ToString(CultureInfo.InvariantCulture));
  211. public string MakeValidUsername(string username)
  212. {
  213. if (IsValidUsername(username))
  214. {
  215. return username;
  216. }
  217. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  218. var builder = new StringBuilder();
  219. foreach (var c in username)
  220. {
  221. if (IsValidUsernameCharacter(c))
  222. {
  223. builder.Append(c);
  224. }
  225. }
  226. return builder.ToString();
  227. }
  228. public async Task<User> AuthenticateUser(string username, string password, string hashedPassword, string remoteEndPoint, bool isUserSession)
  229. {
  230. if (string.IsNullOrWhiteSpace(username))
  231. {
  232. throw new ArgumentNullException(nameof(username));
  233. }
  234. var user = Users.FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  235. var success = false;
  236. IAuthenticationProvider authenticationProvider = null;
  237. if (user != null)
  238. {
  239. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, user, remoteEndPoint).ConfigureAwait(false);
  240. authenticationProvider = authResult.authenticationProvider;
  241. success = authResult.success;
  242. }
  243. else
  244. {
  245. // user is null
  246. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, null, remoteEndPoint).ConfigureAwait(false);
  247. authenticationProvider = authResult.authenticationProvider;
  248. string updatedUsername = authResult.username;
  249. success = authResult.success;
  250. if (success
  251. && authenticationProvider != null
  252. && !(authenticationProvider is DefaultAuthenticationProvider))
  253. {
  254. // We should trust the user that the authprovider says, not what was typed
  255. username = updatedUsername;
  256. // Search the database for the user again; the authprovider might have created it
  257. user = Users
  258. .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  259. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy)
  260. {
  261. var policy = hasNewUserPolicy.GetNewUserPolicy();
  262. UpdateUserPolicy(user, policy, true);
  263. }
  264. }
  265. }
  266. if (success && user != null && authenticationProvider != null)
  267. {
  268. var providerId = GetAuthenticationProviderId(authenticationProvider);
  269. if (!string.Equals(providerId, user.Policy.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  270. {
  271. user.Policy.AuthenticationProviderId = providerId;
  272. UpdateUserPolicy(user, user.Policy, true);
  273. }
  274. }
  275. if (user == null)
  276. {
  277. throw new AuthenticationException("Invalid username or password entered.");
  278. }
  279. if (user.Policy.IsDisabled)
  280. {
  281. throw new AuthenticationException(
  282. string.Format(
  283. CultureInfo.InvariantCulture,
  284. "The {0} account is currently disabled. Please consult with your administrator.",
  285. user.Name));
  286. }
  287. if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint))
  288. {
  289. throw new AuthenticationException("Forbidden.");
  290. }
  291. if (!user.IsParentalScheduleAllowed())
  292. {
  293. throw new AuthenticationException("User is not allowed access at this time.");
  294. }
  295. // Update LastActivityDate and LastLoginDate, then save
  296. if (success)
  297. {
  298. if (isUserSession)
  299. {
  300. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  301. UpdateUser(user);
  302. }
  303. ResetInvalidLoginAttemptCount(user);
  304. }
  305. else
  306. {
  307. IncrementInvalidLoginAttemptCount(user);
  308. }
  309. _logger.LogInformation("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
  310. return success ? user : null;
  311. }
  312. private static string GetAuthenticationProviderId(IAuthenticationProvider provider)
  313. {
  314. return provider.GetType().FullName;
  315. }
  316. private static string GetPasswordResetProviderId(IPasswordResetProvider provider)
  317. {
  318. return provider.GetType().FullName;
  319. }
  320. private IAuthenticationProvider GetAuthenticationProvider(User user)
  321. {
  322. return GetAuthenticationProviders(user)[0];
  323. }
  324. private IPasswordResetProvider GetPasswordResetProvider(User user)
  325. {
  326. return GetPasswordResetProviders(user)[0];
  327. }
  328. private IAuthenticationProvider[] GetAuthenticationProviders(User user)
  329. {
  330. var authenticationProviderId = user?.Policy.AuthenticationProviderId;
  331. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToArray();
  332. if (!string.IsNullOrEmpty(authenticationProviderId))
  333. {
  334. providers = providers.Where(i => string.Equals(authenticationProviderId, GetAuthenticationProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  335. }
  336. if (providers.Length == 0)
  337. {
  338. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  339. _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);
  340. providers = new IAuthenticationProvider[] { _invalidAuthProvider };
  341. }
  342. return providers;
  343. }
  344. private IPasswordResetProvider[] GetPasswordResetProviders(User user)
  345. {
  346. var passwordResetProviderId = user?.Policy.PasswordResetProviderId;
  347. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  348. if (!string.IsNullOrEmpty(passwordResetProviderId))
  349. {
  350. providers = providers.Where(i => string.Equals(passwordResetProviderId, GetPasswordResetProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  351. }
  352. if (providers.Length == 0)
  353. {
  354. providers = new IPasswordResetProvider[] { _defaultPasswordResetProvider };
  355. }
  356. return providers;
  357. }
  358. private async Task<(string username, bool success)> AuthenticateWithProvider(IAuthenticationProvider provider, string username, string password, User resolvedUser)
  359. {
  360. try
  361. {
  362. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  363. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  364. : await provider.Authenticate(username, password).ConfigureAwait(false);
  365. if (authenticationResult.Username != username)
  366. {
  367. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  368. username = authenticationResult.Username;
  369. }
  370. return (username, true);
  371. }
  372. catch (AuthenticationException ex)
  373. {
  374. _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
  375. return (username, false);
  376. }
  377. }
  378. private async Task<(IAuthenticationProvider authenticationProvider, string username, bool success)> AuthenticateLocalUser(
  379. string username,
  380. string password,
  381. string hashedPassword,
  382. User user,
  383. string remoteEndPoint)
  384. {
  385. bool success = false;
  386. IAuthenticationProvider authenticationProvider = null;
  387. foreach (var provider in GetAuthenticationProviders(user))
  388. {
  389. var providerAuthResult = await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  390. var updatedUsername = providerAuthResult.username;
  391. success = providerAuthResult.success;
  392. if (success)
  393. {
  394. authenticationProvider = provider;
  395. username = updatedUsername;
  396. break;
  397. }
  398. }
  399. if (!success
  400. && _networkManager.IsInLocalNetwork(remoteEndPoint)
  401. && user.Configuration.EnableLocalPassword
  402. && !string.IsNullOrEmpty(user.EasyPassword))
  403. {
  404. // Check easy password
  405. var passwordHash = PasswordHash.Parse(user.EasyPassword);
  406. var hash = _cryptoProvider.ComputeHash(
  407. passwordHash.Id,
  408. Encoding.UTF8.GetBytes(password),
  409. passwordHash.Salt);
  410. success = passwordHash.Hash.SequenceEqual(hash);
  411. }
  412. return (authenticationProvider, username, success);
  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. }