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