2
0

UserManager.cs 38 KB

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