UserManager.cs 38 KB

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