UserManager.cs 41 KB

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