UserManager.cs 40 KB

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