UserManager.cs 40 KB

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