UserManager.cs 40 KB

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