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