UserManager.cs 41 KB

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