UserManager.cs 41 KB

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