UserManager.cs 39 KB

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