UserManager.cs 38 KB

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