UserManager.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  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. UpdateInvalidLoginAttemptCount(user, 0);
  301. }
  302. else
  303. {
  304. UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1);
  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 UpdateInvalidLoginAttemptCount(User user, int newValue)
  428. {
  429. if (user.Policy.InvalidLoginAttemptCount == newValue || newValue <= 0)
  430. {
  431. return;
  432. }
  433. user.Policy.InvalidLoginAttemptCount = newValue;
  434. // Check for users without a value here and then fill in the default value
  435. // also protect from an always lockout if misconfigured
  436. if (user.Policy.LoginAttemptsBeforeLockout == null || user.Policy.LoginAttemptsBeforeLockout == 0)
  437. {
  438. user.Policy.LoginAttemptsBeforeLockout = user.Policy.IsAdministrator ? 5 : 3;
  439. }
  440. var maxCount = user.Policy.LoginAttemptsBeforeLockout;
  441. var fireLockout = false;
  442. // -1 can be used to specify no lockout value
  443. if (maxCount != -1 && newValue >= maxCount)
  444. {
  445. _logger.LogDebug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue);
  446. user.Policy.IsDisabled = true;
  447. fireLockout = true;
  448. }
  449. UpdateUserPolicy(user, user.Policy, false);
  450. if (fireLockout)
  451. {
  452. UserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
  453. }
  454. }
  455. /// <summary>
  456. /// Loads the users from the repository.
  457. /// </summary>
  458. private void LoadUsers()
  459. {
  460. var users = _userRepository.RetrieveAllUsers();
  461. // There always has to be at least one user.
  462. if (users.Count != 0)
  463. {
  464. _users = new ConcurrentDictionary<Guid, User>(
  465. users.Select(x => new KeyValuePair<Guid, User>(x.Id, x)));
  466. }
  467. var defaultName = Environment.UserName;
  468. if (string.IsNullOrWhiteSpace(defaultName))
  469. {
  470. defaultName = "MyJellyfinUser";
  471. }
  472. var name = MakeValidUsername(defaultName);
  473. var user = InstantiateNewUser(name);
  474. user.DateLastSaved = DateTime.UtcNow;
  475. _userRepository.CreateUser(user);
  476. user.Policy.IsAdministrator = true;
  477. user.Policy.EnableContentDeletion = true;
  478. user.Policy.EnableRemoteControlOfOtherUsers = true;
  479. UpdateUserPolicy(user, user.Policy, false);
  480. _users = new ConcurrentDictionary<Guid, User>();
  481. _users[user.Id] = user;
  482. }
  483. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  484. {
  485. if (user == null)
  486. {
  487. throw new ArgumentNullException(nameof(user));
  488. }
  489. bool hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user);
  490. bool hasConfiguredEasyPassword = !string.IsNullOrEmpty(GetAuthenticationProvider(user).GetEasyPasswordHash(user));
  491. bool hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  492. hasConfiguredEasyPassword :
  493. hasConfiguredPassword;
  494. UserDto dto = new UserDto
  495. {
  496. Id = user.Id,
  497. Name = user.Name,
  498. HasPassword = hasPassword,
  499. HasConfiguredPassword = hasConfiguredPassword,
  500. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  501. LastActivityDate = user.LastActivityDate,
  502. LastLoginDate = user.LastLoginDate,
  503. Configuration = user.Configuration,
  504. ServerId = _appHost.SystemId,
  505. Policy = user.Policy
  506. };
  507. if (!hasPassword && _users.Count == 1)
  508. {
  509. dto.EnableAutoLogin = true;
  510. }
  511. ItemImageInfo image = user.GetImageInfo(ImageType.Primary, 0);
  512. if (image != null)
  513. {
  514. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  515. try
  516. {
  517. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  518. }
  519. catch (Exception ex)
  520. {
  521. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  522. _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {user}", user.Name);
  523. }
  524. }
  525. return dto;
  526. }
  527. public UserDto GetOfflineUserDto(User user)
  528. {
  529. var dto = GetUserDto(user);
  530. dto.ServerName = _appHost.FriendlyName;
  531. return dto;
  532. }
  533. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  534. {
  535. try
  536. {
  537. return _imageProcessorFactory().GetImageCacheTag(item, image);
  538. }
  539. catch (Exception ex)
  540. {
  541. _logger.LogError(ex, "Error getting {imageType} image info for {imagePath}", image.Type, image.Path);
  542. return null;
  543. }
  544. }
  545. /// <summary>
  546. /// Refreshes metadata for each user
  547. /// </summary>
  548. /// <param name="cancellationToken">The cancellation token.</param>
  549. /// <returns>Task.</returns>
  550. public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
  551. {
  552. foreach (var user in Users)
  553. {
  554. await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
  555. }
  556. }
  557. /// <summary>
  558. /// Renames the user.
  559. /// </summary>
  560. /// <param name="user">The user.</param>
  561. /// <param name="newName">The new name.</param>
  562. /// <returns>Task.</returns>
  563. /// <exception cref="ArgumentNullException">user</exception>
  564. /// <exception cref="ArgumentException"></exception>
  565. public async Task RenameUser(User user, string newName)
  566. {
  567. if (user == null)
  568. {
  569. throw new ArgumentNullException(nameof(user));
  570. }
  571. if (string.IsNullOrWhiteSpace(newName))
  572. {
  573. throw new ArgumentException("Invalid username", nameof(newName));
  574. }
  575. if (user.Name.Equals(newName, StringComparison.OrdinalIgnoreCase))
  576. {
  577. throw new ArgumentException("The new and old names must be different.");
  578. }
  579. if (Users.Any(
  580. u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  581. {
  582. throw new ArgumentException(string.Format(
  583. CultureInfo.InvariantCulture,
  584. "A user with the name '{0}' already exists.",
  585. newName));
  586. }
  587. await user.Rename(newName).ConfigureAwait(false);
  588. OnUserUpdated(user);
  589. }
  590. /// <summary>
  591. /// Updates the user.
  592. /// </summary>
  593. /// <param name="user">The user.</param>
  594. /// <exception cref="ArgumentNullException">user</exception>
  595. /// <exception cref="ArgumentException"></exception>
  596. public void UpdateUser(User user)
  597. {
  598. if (user == null)
  599. {
  600. throw new ArgumentNullException(nameof(user));
  601. }
  602. if (user.Id == Guid.Empty)
  603. {
  604. throw new ArgumentException("Id can't be empty.", nameof(user));
  605. }
  606. if (!_users.ContainsKey(user.Id))
  607. {
  608. throw new ArgumentException(
  609. string.Format(
  610. CultureInfo.InvariantCulture,
  611. "A user '{0}' with Id {1} does not exist.",
  612. user.Name,
  613. user.Id),
  614. nameof(user));
  615. }
  616. user.DateModified = DateTime.UtcNow;
  617. user.DateLastSaved = DateTime.UtcNow;
  618. _userRepository.UpdateUser(user);
  619. OnUserUpdated(user);
  620. }
  621. /// <summary>
  622. /// Creates the user.
  623. /// </summary>
  624. /// <param name="name">The name.</param>
  625. /// <returns>User.</returns>
  626. /// <exception cref="ArgumentNullException">name</exception>
  627. /// <exception cref="ArgumentException"></exception>
  628. public User CreateUser(string name)
  629. {
  630. if (string.IsNullOrWhiteSpace(name))
  631. {
  632. throw new ArgumentNullException(nameof(name));
  633. }
  634. if (!IsValidUsername(name))
  635. {
  636. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  637. }
  638. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  639. {
  640. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  641. }
  642. var user = InstantiateNewUser(name);
  643. _users[user.Id] = user;
  644. user.DateLastSaved = DateTime.UtcNow;
  645. _userRepository.CreateUser(user);
  646. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  647. return user;
  648. }
  649. /// <summary>
  650. /// Deletes the user.
  651. /// </summary>
  652. /// <param name="user">The user.</param>
  653. /// <returns>Task.</returns>
  654. /// <exception cref="ArgumentNullException">user</exception>
  655. /// <exception cref="ArgumentException"></exception>
  656. public void DeleteUser(User user)
  657. {
  658. if (user == null)
  659. {
  660. throw new ArgumentNullException(nameof(user));
  661. }
  662. if (!_users.ContainsKey(user.Id))
  663. {
  664. throw new ArgumentException(string.Format(
  665. CultureInfo.InvariantCulture,
  666. "The user cannot be deleted because there is no user with the Name {0} and Id {1}.",
  667. user.Name,
  668. user.Id));
  669. }
  670. if (_users.Count == 1)
  671. {
  672. throw new ArgumentException(string.Format(
  673. CultureInfo.InvariantCulture,
  674. "The user '{0}' cannot be deleted because there must be at least one user in the system.",
  675. user.Name));
  676. }
  677. if (user.Policy.IsAdministrator
  678. && Users.Count(i => i.Policy.IsAdministrator) == 1)
  679. {
  680. throw new ArgumentException(
  681. string.Format(
  682. CultureInfo.InvariantCulture,
  683. "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
  684. user.Name),
  685. nameof(user));
  686. }
  687. var configPath = GetConfigurationFilePath(user);
  688. _userRepository.DeleteUser(user);
  689. try
  690. {
  691. _fileSystem.DeleteFile(configPath);
  692. }
  693. catch (IOException ex)
  694. {
  695. _logger.LogError(ex, "Error deleting file {path}", configPath);
  696. }
  697. DeleteUserPolicy(user);
  698. _users.TryRemove(user.Id, out _);
  699. OnUserDeleted(user);
  700. }
  701. /// <summary>
  702. /// Resets the password by clearing it.
  703. /// </summary>
  704. /// <returns>Task.</returns>
  705. public Task ResetPassword(User user)
  706. {
  707. return ChangePassword(user, string.Empty);
  708. }
  709. public void ResetEasyPassword(User user)
  710. {
  711. ChangeEasyPassword(user, string.Empty, null);
  712. }
  713. public async Task ChangePassword(User user, string newPassword)
  714. {
  715. if (user == null)
  716. {
  717. throw new ArgumentNullException(nameof(user));
  718. }
  719. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  720. UpdateUser(user);
  721. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  722. }
  723. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  724. {
  725. if (user == null)
  726. {
  727. throw new ArgumentNullException(nameof(user));
  728. }
  729. GetAuthenticationProvider(user).ChangeEasyPassword(user, newPassword, newPasswordHash);
  730. UpdateUser(user);
  731. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  732. }
  733. /// <summary>
  734. /// Instantiates the new user.
  735. /// </summary>
  736. /// <param name="name">The name.</param>
  737. /// <returns>User.</returns>
  738. private static User InstantiateNewUser(string name)
  739. {
  740. return new User
  741. {
  742. Name = name,
  743. Id = Guid.NewGuid(),
  744. DateCreated = DateTime.UtcNow,
  745. DateModified = DateTime.UtcNow
  746. };
  747. }
  748. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  749. {
  750. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  751. null :
  752. GetUserByName(enteredUsername);
  753. var action = ForgotPasswordAction.InNetworkRequired;
  754. if (user != null && isInNetwork)
  755. {
  756. var passwordResetProvider = GetPasswordResetProvider(user);
  757. return await passwordResetProvider.StartForgotPasswordProcess(user, isInNetwork).ConfigureAwait(false);
  758. }
  759. else
  760. {
  761. return new ForgotPasswordResult
  762. {
  763. Action = action,
  764. PinFile = string.Empty
  765. };
  766. }
  767. }
  768. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  769. {
  770. foreach (var provider in _passwordResetProviders)
  771. {
  772. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  773. if (result.Success)
  774. {
  775. return result;
  776. }
  777. }
  778. return new PinRedeemResult
  779. {
  780. Success = false,
  781. UsersReset = Array.Empty<string>()
  782. };
  783. }
  784. public UserPolicy GetUserPolicy(User user)
  785. {
  786. var path = GetPolicyFilePath(user);
  787. if (!File.Exists(path))
  788. {
  789. return GetDefaultPolicy(user);
  790. }
  791. try
  792. {
  793. lock (_policySyncLock)
  794. {
  795. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  796. }
  797. }
  798. catch (IOException)
  799. {
  800. return GetDefaultPolicy(user);
  801. }
  802. catch (Exception ex)
  803. {
  804. _logger.LogError(ex, "Error reading policy file: {path}", path);
  805. return GetDefaultPolicy(user);
  806. }
  807. }
  808. private static UserPolicy GetDefaultPolicy(User user)
  809. {
  810. return new UserPolicy
  811. {
  812. EnableContentDownloading = true,
  813. EnableSyncTranscoding = true
  814. };
  815. }
  816. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  817. {
  818. var user = GetUserById(userId);
  819. UpdateUserPolicy(user, userPolicy, true);
  820. }
  821. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  822. {
  823. // The xml serializer will output differently if the type is not exact
  824. if (userPolicy.GetType() != typeof(UserPolicy))
  825. {
  826. var json = _jsonSerializer.SerializeToString(userPolicy);
  827. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  828. }
  829. var path = GetPolicyFilePath(user);
  830. Directory.CreateDirectory(Path.GetDirectoryName(path));
  831. lock (_policySyncLock)
  832. {
  833. _xmlSerializer.SerializeToFile(userPolicy, path);
  834. user.Policy = userPolicy;
  835. }
  836. if (fireEvent)
  837. {
  838. UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  839. }
  840. }
  841. private void DeleteUserPolicy(User user)
  842. {
  843. var path = GetPolicyFilePath(user);
  844. try
  845. {
  846. lock (_policySyncLock)
  847. {
  848. _fileSystem.DeleteFile(path);
  849. }
  850. }
  851. catch (IOException)
  852. {
  853. }
  854. catch (Exception ex)
  855. {
  856. _logger.LogError(ex, "Error deleting policy file");
  857. }
  858. }
  859. private static string GetPolicyFilePath(User user)
  860. {
  861. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  862. }
  863. private static string GetConfigurationFilePath(User user)
  864. {
  865. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  866. }
  867. public UserConfiguration GetUserConfiguration(User user)
  868. {
  869. var path = GetConfigurationFilePath(user);
  870. if (!File.Exists(path))
  871. {
  872. return new UserConfiguration();
  873. }
  874. try
  875. {
  876. lock (_configSyncLock)
  877. {
  878. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  879. }
  880. }
  881. catch (IOException)
  882. {
  883. return new UserConfiguration();
  884. }
  885. catch (Exception ex)
  886. {
  887. _logger.LogError(ex, "Error reading policy file: {path}", path);
  888. return new UserConfiguration();
  889. }
  890. }
  891. private readonly object _configSyncLock = new object();
  892. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  893. {
  894. var user = GetUserById(userId);
  895. UpdateConfiguration(user, config);
  896. }
  897. public void UpdateConfiguration(User user, UserConfiguration config)
  898. {
  899. UpdateConfiguration(user, config, true);
  900. }
  901. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  902. {
  903. var path = GetConfigurationFilePath(user);
  904. // The xml serializer will output differently if the type is not exact
  905. if (config.GetType() != typeof(UserConfiguration))
  906. {
  907. var json = _jsonSerializer.SerializeToString(config);
  908. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  909. }
  910. Directory.CreateDirectory(Path.GetDirectoryName(path));
  911. lock (_configSyncLock)
  912. {
  913. _xmlSerializer.SerializeToFile(config, path);
  914. user.Configuration = config;
  915. }
  916. if (fireEvent)
  917. {
  918. UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  919. }
  920. }
  921. }
  922. public class DeviceAccessEntryPoint : IServerEntryPoint
  923. {
  924. private IUserManager _userManager;
  925. private IAuthenticationRepository _authRepo;
  926. private IDeviceManager _deviceManager;
  927. private ISessionManager _sessionManager;
  928. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  929. {
  930. _userManager = userManager;
  931. _authRepo = authRepo;
  932. _deviceManager = deviceManager;
  933. _sessionManager = sessionManager;
  934. }
  935. public Task RunAsync()
  936. {
  937. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  938. return Task.CompletedTask;
  939. }
  940. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  941. {
  942. var user = e.Argument;
  943. if (!user.Policy.EnableAllDevices)
  944. {
  945. UpdateDeviceAccess(user);
  946. }
  947. }
  948. private void UpdateDeviceAccess(User user)
  949. {
  950. var existing = _authRepo.Get(new AuthenticationInfoQuery
  951. {
  952. UserId = user.Id
  953. }).Items;
  954. foreach (var authInfo in existing)
  955. {
  956. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  957. {
  958. _sessionManager.Logout(authInfo);
  959. }
  960. }
  961. }
  962. public void Dispose()
  963. {
  964. }
  965. }
  966. }