UserManager.cs 40 KB

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