UserManager.cs 39 KB

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