UserManager.cs 39 KB

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