2
0

UserManager.cs 39 KB

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