UserManager.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. #pragma warning disable CA1307
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Threading.Tasks;
  9. using Jellyfin.Data.Entities;
  10. using Jellyfin.Data.Enums;
  11. using MediaBrowser.Common;
  12. using MediaBrowser.Common.Cryptography;
  13. using MediaBrowser.Common.Net;
  14. using MediaBrowser.Controller.Authentication;
  15. using MediaBrowser.Controller.Drawing;
  16. using MediaBrowser.Controller.Library;
  17. using MediaBrowser.Controller.Net;
  18. using MediaBrowser.Model.Configuration;
  19. using MediaBrowser.Model.Cryptography;
  20. using MediaBrowser.Model.Dto;
  21. using MediaBrowser.Model.Events;
  22. using MediaBrowser.Model.Users;
  23. using Microsoft.Extensions.Logging;
  24. namespace Jellyfin.Server.Implementations.Users
  25. {
  26. /// <summary>
  27. /// Manages the creation and retrieval of <see cref="User"/> instances.
  28. /// </summary>
  29. public class UserManager : IUserManager
  30. {
  31. private readonly JellyfinDbProvider _dbProvider;
  32. private readonly ICryptoProvider _cryptoProvider;
  33. private readonly INetworkManager _networkManager;
  34. private readonly IApplicationHost _appHost;
  35. private readonly IImageProcessor _imageProcessor;
  36. private readonly ILogger<UserManager> _logger;
  37. private IAuthenticationProvider[] _authenticationProviders;
  38. private DefaultAuthenticationProvider _defaultAuthenticationProvider;
  39. private InvalidAuthProvider _invalidAuthProvider;
  40. private IPasswordResetProvider[] _passwordResetProviders;
  41. private DefaultPasswordResetProvider _defaultPasswordResetProvider;
  42. /// <summary>
  43. /// Initializes a new instance of the <see cref="UserManager"/> class.
  44. /// </summary>
  45. /// <param name="dbProvider">The database provider.</param>
  46. /// <param name="cryptoProvider">The cryptography provider.</param>
  47. /// <param name="networkManager">The network manager.</param>
  48. /// <param name="appHost">The application host.</param>
  49. /// <param name="imageProcessor">The image processor.</param>
  50. /// <param name="logger">The logger.</param>
  51. public UserManager(
  52. JellyfinDbProvider dbProvider,
  53. ICryptoProvider cryptoProvider,
  54. INetworkManager networkManager,
  55. IApplicationHost appHost,
  56. IImageProcessor imageProcessor,
  57. ILogger<UserManager> logger)
  58. {
  59. _dbProvider = dbProvider;
  60. _cryptoProvider = cryptoProvider;
  61. _networkManager = networkManager;
  62. _appHost = appHost;
  63. _imageProcessor = imageProcessor;
  64. _logger = logger;
  65. }
  66. /// <inheritdoc/>
  67. public event EventHandler<GenericEventArgs<User>> OnUserPasswordChanged;
  68. /// <inheritdoc/>
  69. public event EventHandler<GenericEventArgs<User>> OnUserUpdated;
  70. /// <inheritdoc/>
  71. public event EventHandler<GenericEventArgs<User>> OnUserCreated;
  72. /// <inheritdoc/>
  73. public event EventHandler<GenericEventArgs<User>> OnUserDeleted;
  74. /// <inheritdoc/>
  75. public event EventHandler<GenericEventArgs<User>> OnUserLockedOut;
  76. /// <inheritdoc/>
  77. public IEnumerable<User> Users
  78. {
  79. get
  80. {
  81. var dbContext = _dbProvider.CreateContext();
  82. return dbContext.Users;
  83. }
  84. }
  85. /// <inheritdoc/>
  86. public IEnumerable<Guid> UsersIds
  87. {
  88. get
  89. {
  90. var dbContext = _dbProvider.CreateContext();
  91. return dbContext.Users.Select(u => u.Id);
  92. }
  93. }
  94. /// <inheritdoc/>
  95. public User GetUserById(Guid id)
  96. {
  97. if (id == Guid.Empty)
  98. {
  99. throw new ArgumentException("Guid can't be empty", nameof(id));
  100. }
  101. var dbContext = _dbProvider.CreateContext();
  102. return dbContext.Users.Find(id);
  103. }
  104. /// <inheritdoc/>
  105. public User GetUserByName(string name)
  106. {
  107. if (string.IsNullOrWhiteSpace(name))
  108. {
  109. throw new ArgumentException("Invalid username", nameof(name));
  110. }
  111. var dbContext = _dbProvider.CreateContext();
  112. // This can't use an overload with StringComparer because that would cause the query to
  113. // have to be evaluated client-side.
  114. return dbContext.Users.FirstOrDefault(u => string.Equals(u.Username, name));
  115. }
  116. /// <inheritdoc/>
  117. public async Task RenameUser(User user, string newName)
  118. {
  119. if (user == null)
  120. {
  121. throw new ArgumentNullException(nameof(user));
  122. }
  123. if (string.IsNullOrWhiteSpace(newName))
  124. {
  125. throw new ArgumentException("Invalid username", nameof(newName));
  126. }
  127. if (user.Username.Equals(newName, StringComparison.Ordinal))
  128. {
  129. throw new ArgumentException("The new and old names must be different.");
  130. }
  131. if (Users.Any(u => u.Id != user.Id && u.Username.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  132. {
  133. throw new ArgumentException(string.Format(
  134. CultureInfo.InvariantCulture,
  135. "A user with the name '{0}' already exists.",
  136. newName));
  137. }
  138. user.Username = newName;
  139. await UpdateUserAsync(user).ConfigureAwait(false);
  140. OnUserUpdated?.Invoke(this, new GenericEventArgs<User>(user));
  141. }
  142. /// <inheritdoc/>
  143. public void UpdateUser(User user)
  144. {
  145. var dbContext = _dbProvider.CreateContext();
  146. dbContext.Users.Update(user);
  147. dbContext.SaveChanges();
  148. }
  149. /// <inheritdoc/>
  150. public async Task UpdateUserAsync(User user)
  151. {
  152. var dbContext = _dbProvider.CreateContext();
  153. dbContext.Users.Update(user);
  154. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  155. }
  156. /// <inheritdoc/>
  157. public User CreateUser(string name)
  158. {
  159. if (!IsValidUsername(name))
  160. {
  161. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  162. }
  163. var dbContext = _dbProvider.CreateContext();
  164. // TODO: Remove after user item data is migrated.
  165. var max = dbContext.Users.Select(u => u.InternalId).Max();
  166. var newUser = new User(
  167. name,
  168. _defaultAuthenticationProvider.GetType().FullName,
  169. _defaultPasswordResetProvider.GetType().FullName)
  170. {
  171. InternalId = max + 1
  172. };
  173. dbContext.Users.Add(newUser);
  174. dbContext.SaveChanges();
  175. OnUserCreated?.Invoke(this, new GenericEventArgs<User>(newUser));
  176. return newUser;
  177. }
  178. /// <inheritdoc/>
  179. public void DeleteUser(User user)
  180. {
  181. if (user == null)
  182. {
  183. throw new ArgumentNullException(nameof(user));
  184. }
  185. var dbContext = _dbProvider.CreateContext();
  186. if (!dbContext.Users.Contains(user))
  187. {
  188. throw new ArgumentException(string.Format(
  189. CultureInfo.InvariantCulture,
  190. "The user cannot be deleted because there is no user with the Name {0} and Id {1}.",
  191. user.Username,
  192. user.Id));
  193. }
  194. if (dbContext.Users.Count() == 1)
  195. {
  196. throw new InvalidOperationException(string.Format(
  197. CultureInfo.InvariantCulture,
  198. "The user '{0}' cannot be deleted because there must be at least one user in the system.",
  199. user.Username));
  200. }
  201. if (user.HasPermission(PermissionKind.IsAdministrator)
  202. && Users.Count(i => i.HasPermission(PermissionKind.IsAdministrator)) == 1)
  203. {
  204. throw new ArgumentException(
  205. string.Format(
  206. CultureInfo.InvariantCulture,
  207. "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
  208. user.Username),
  209. nameof(user));
  210. }
  211. dbContext.Users.Remove(user);
  212. dbContext.SaveChanges();
  213. OnUserDeleted?.Invoke(this, new GenericEventArgs<User>(user));
  214. }
  215. /// <inheritdoc/>
  216. public Task ResetPassword(User user)
  217. {
  218. return ChangePassword(user, string.Empty);
  219. }
  220. /// <inheritdoc/>
  221. public void ResetEasyPassword(User user)
  222. {
  223. ChangeEasyPassword(user, string.Empty, null);
  224. }
  225. /// <inheritdoc/>
  226. public async Task ChangePassword(User user, string newPassword)
  227. {
  228. if (user == null)
  229. {
  230. throw new ArgumentNullException(nameof(user));
  231. }
  232. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  233. await UpdateUserAsync(user).ConfigureAwait(false);
  234. OnUserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  235. }
  236. /// <inheritdoc/>
  237. public void ChangeEasyPassword(User user, string newPassword, string newPasswordSha1)
  238. {
  239. GetAuthenticationProvider(user).ChangeEasyPassword(user, newPassword, newPasswordSha1);
  240. UpdateUser(user);
  241. OnUserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  242. }
  243. /// <inheritdoc/>
  244. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  245. {
  246. return new UserDto
  247. {
  248. Name = user.Username,
  249. Id = user.Id,
  250. ServerId = _appHost.SystemId,
  251. HasPassword = user.Password != null,
  252. EnableAutoLogin = user.EnableAutoLogin,
  253. LastLoginDate = user.LastLoginDate,
  254. LastActivityDate = user.LastActivityDate,
  255. PrimaryImageTag = user.ProfileImage != null ? _imageProcessor.GetImageCacheTag(user) : null,
  256. Configuration = new UserConfiguration
  257. {
  258. SubtitleMode = user.SubtitleMode,
  259. HidePlayedInLatest = user.HidePlayedInLatest,
  260. EnableLocalPassword = user.EnableLocalPassword,
  261. PlayDefaultAudioTrack = user.PlayDefaultAudioTrack,
  262. DisplayCollectionsView = user.DisplayCollectionsView,
  263. DisplayMissingEpisodes = user.DisplayMissingEpisodes,
  264. AudioLanguagePreference = user.AudioLanguagePreference,
  265. RememberAudioSelections = user.RememberAudioSelections,
  266. EnableNextEpisodeAutoPlay = user.EnableNextEpisodeAutoPlay,
  267. RememberSubtitleSelections = user.RememberSubtitleSelections,
  268. SubtitleLanguagePreference = user.SubtitleLanguagePreference ?? string.Empty,
  269. OrderedViews = user.GetPreference(PreferenceKind.OrderedViews),
  270. GroupedFolders = user.GetPreference(PreferenceKind.GroupedFolders),
  271. MyMediaExcludes = user.GetPreference(PreferenceKind.MyMediaExcludes),
  272. LatestItemsExcludes = user.GetPreference(PreferenceKind.LatestItemExcludes)
  273. },
  274. Policy = new UserPolicy
  275. {
  276. MaxParentalRating = user.MaxParentalAgeRating,
  277. EnableUserPreferenceAccess = user.EnableUserPreferenceAccess,
  278. RemoteClientBitrateLimit = user.RemoteClientBitrateLimit.GetValueOrDefault(),
  279. AuthenticationProviderId = user.AuthenticationProviderId,
  280. PasswordResetProviderId = user.PasswordResetProviderId,
  281. InvalidLoginAttemptCount = user.InvalidLoginAttemptCount,
  282. LoginAttemptsBeforeLockout = user.LoginAttemptsBeforeLockout.GetValueOrDefault(),
  283. IsAdministrator = user.HasPermission(PermissionKind.IsAdministrator),
  284. IsHidden = user.HasPermission(PermissionKind.IsHidden),
  285. IsDisabled = user.HasPermission(PermissionKind.IsDisabled),
  286. EnableSharedDeviceControl = user.HasPermission(PermissionKind.EnableSharedDeviceControl),
  287. EnableRemoteAccess = user.HasPermission(PermissionKind.EnableRemoteAccess),
  288. EnableLiveTvManagement = user.HasPermission(PermissionKind.EnableLiveTvManagement),
  289. EnableLiveTvAccess = user.HasPermission(PermissionKind.EnableLiveTvAccess),
  290. EnableMediaPlayback = user.HasPermission(PermissionKind.EnableMediaPlayback),
  291. EnableAudioPlaybackTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding),
  292. EnableVideoPlaybackTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding),
  293. EnableContentDeletion = user.HasPermission(PermissionKind.EnableContentDeletion),
  294. EnableContentDownloading = user.HasPermission(PermissionKind.EnableContentDownloading),
  295. EnableSyncTranscoding = user.HasPermission(PermissionKind.EnableSyncTranscoding),
  296. EnableMediaConversion = user.HasPermission(PermissionKind.EnableMediaConversion),
  297. EnableAllChannels = user.HasPermission(PermissionKind.EnableAllChannels),
  298. EnableAllDevices = user.HasPermission(PermissionKind.EnableAllDevices),
  299. EnableAllFolders = user.HasPermission(PermissionKind.EnableAllFolders),
  300. EnableRemoteControlOfOtherUsers = user.HasPermission(PermissionKind.EnableRemoteControlOfOtherUsers),
  301. EnablePlaybackRemuxing = user.HasPermission(PermissionKind.EnablePlaybackRemuxing),
  302. ForceRemoteSourceTranscoding = user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding),
  303. EnablePublicSharing = user.HasPermission(PermissionKind.EnablePublicSharing),
  304. AccessSchedules = user.AccessSchedules.ToArray(),
  305. BlockedTags = user.GetPreference(PreferenceKind.BlockedTags),
  306. EnabledChannels = user.GetPreference(PreferenceKind.EnabledChannels),
  307. EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices),
  308. EnabledFolders = user.GetPreference(PreferenceKind.EnabledFolders),
  309. EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders)
  310. }
  311. };
  312. }
  313. /// <inheritdoc/>
  314. public PublicUserDto GetPublicUserDto(User user, string remoteEndPoint = null)
  315. {
  316. if (user == null)
  317. {
  318. throw new ArgumentNullException(nameof(user));
  319. }
  320. bool hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user);
  321. bool hasConfiguredEasyPassword = !string.IsNullOrEmpty(GetAuthenticationProvider(user).GetEasyPasswordHash(user));
  322. bool hasPassword = user.EnableLocalPassword &&
  323. !string.IsNullOrEmpty(remoteEndPoint) &&
  324. _networkManager.IsInLocalNetwork(remoteEndPoint) ? hasConfiguredEasyPassword : hasConfiguredPassword;
  325. return new PublicUserDto
  326. {
  327. Name = user.Username,
  328. HasPassword = hasPassword,
  329. HasConfiguredPassword = hasConfiguredPassword
  330. };
  331. }
  332. /// <inheritdoc/>
  333. public async Task<User> AuthenticateUser(
  334. string username,
  335. string password,
  336. string passwordSha1,
  337. string remoteEndPoint,
  338. bool isUserSession)
  339. {
  340. if (string.IsNullOrWhiteSpace(username))
  341. {
  342. _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
  343. throw new ArgumentNullException(nameof(username));
  344. }
  345. var user = Users.ToList().FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  346. bool success;
  347. IAuthenticationProvider authenticationProvider;
  348. if (user != null)
  349. {
  350. var authResult = await AuthenticateLocalUser(username, password, user, remoteEndPoint)
  351. .ConfigureAwait(false);
  352. authenticationProvider = authResult.authenticationProvider;
  353. success = authResult.success;
  354. }
  355. else
  356. {
  357. var authResult = await AuthenticateLocalUser(username, password, null, remoteEndPoint)
  358. .ConfigureAwait(false);
  359. authenticationProvider = authResult.authenticationProvider;
  360. string updatedUsername = authResult.username;
  361. success = authResult.success;
  362. if (success
  363. && authenticationProvider != null
  364. && !(authenticationProvider is DefaultAuthenticationProvider))
  365. {
  366. // Trust the username returned by the authentication provider
  367. username = updatedUsername;
  368. // Search the database for the user again
  369. // the authentication provider might have created it
  370. user = Users
  371. .ToList().FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  372. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy)
  373. {
  374. UpdatePolicy(user.Id, hasNewUserPolicy.GetNewUserPolicy());
  375. await UpdateUserAsync(user).ConfigureAwait(false);
  376. }
  377. }
  378. }
  379. if (success && user != null && authenticationProvider != null)
  380. {
  381. var providerId = authenticationProvider.GetType().FullName;
  382. if (!string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  383. {
  384. user.AuthenticationProviderId = providerId;
  385. await UpdateUserAsync(user).ConfigureAwait(false);
  386. }
  387. }
  388. if (user == null)
  389. {
  390. _logger.LogInformation(
  391. "Authentication request for {UserName} has been denied (IP: {IP}).",
  392. username,
  393. remoteEndPoint);
  394. throw new AuthenticationException("Invalid username or password entered.");
  395. }
  396. if (user.HasPermission(PermissionKind.IsDisabled))
  397. {
  398. _logger.LogInformation(
  399. "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
  400. username,
  401. remoteEndPoint);
  402. throw new SecurityException(
  403. $"The {user.Username} account is currently disabled. Please consult with your administrator.");
  404. }
  405. if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
  406. !_networkManager.IsInLocalNetwork(remoteEndPoint))
  407. {
  408. _logger.LogInformation(
  409. "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
  410. username,
  411. remoteEndPoint);
  412. throw new SecurityException("Forbidden.");
  413. }
  414. if (!user.IsParentalScheduleAllowed())
  415. {
  416. _logger.LogInformation(
  417. "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
  418. username,
  419. remoteEndPoint);
  420. throw new SecurityException("User is not allowed access at this time.");
  421. }
  422. // Update LastActivityDate and LastLoginDate, then save
  423. if (success)
  424. {
  425. if (isUserSession)
  426. {
  427. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  428. await UpdateUserAsync(user).ConfigureAwait(false);
  429. }
  430. user.InvalidLoginAttemptCount = 0;
  431. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
  432. }
  433. else
  434. {
  435. IncrementInvalidLoginAttemptCount(user);
  436. _logger.LogInformation(
  437. "Authentication request for {UserName} has been denied (IP: {IP}).",
  438. user.Username,
  439. remoteEndPoint);
  440. }
  441. return success ? user : null;
  442. }
  443. /// <inheritdoc/>
  444. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  445. {
  446. var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
  447. var action = ForgotPasswordAction.InNetworkRequired;
  448. if (user != null && isInNetwork)
  449. {
  450. var passwordResetProvider = GetPasswordResetProvider(user);
  451. return await passwordResetProvider.StartForgotPasswordProcess(user, isInNetwork).ConfigureAwait(false);
  452. }
  453. return new ForgotPasswordResult
  454. {
  455. Action = action,
  456. PinFile = string.Empty
  457. };
  458. }
  459. /// <inheritdoc/>
  460. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  461. {
  462. foreach (var provider in _passwordResetProviders)
  463. {
  464. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  465. if (result.Success)
  466. {
  467. return result;
  468. }
  469. }
  470. return new PinRedeemResult
  471. {
  472. Success = false,
  473. UsersReset = Array.Empty<string>()
  474. };
  475. }
  476. /// <inheritdoc/>
  477. public void AddParts(IEnumerable<IAuthenticationProvider> authenticationProviders, IEnumerable<IPasswordResetProvider> passwordResetProviders)
  478. {
  479. _authenticationProviders = authenticationProviders.ToArray();
  480. _passwordResetProviders = passwordResetProviders.ToArray();
  481. _invalidAuthProvider = _authenticationProviders.OfType<InvalidAuthProvider>().First();
  482. _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
  483. _defaultPasswordResetProvider = _passwordResetProviders.OfType<DefaultPasswordResetProvider>().First();
  484. }
  485. /// <inheritdoc/>
  486. public NameIdPair[] GetAuthenticationProviders()
  487. {
  488. return _authenticationProviders
  489. .Where(provider => provider.IsEnabled)
  490. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  491. .ThenBy(i => i.Name)
  492. .Select(i => new NameIdPair
  493. {
  494. Name = i.Name,
  495. Id = i.GetType().FullName
  496. })
  497. .ToArray();
  498. }
  499. /// <inheritdoc/>
  500. public NameIdPair[] GetPasswordResetProviders()
  501. {
  502. return _passwordResetProviders
  503. .Where(provider => provider.IsEnabled)
  504. .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
  505. .ThenBy(i => i.Name)
  506. .Select(i => new NameIdPair
  507. {
  508. Name = i.Name,
  509. Id = i.GetType().FullName
  510. })
  511. .ToArray();
  512. }
  513. /// <inheritdoc/>
  514. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  515. {
  516. var user = GetUserById(userId);
  517. user.SubtitleMode = config.SubtitleMode;
  518. user.HidePlayedInLatest = config.HidePlayedInLatest;
  519. user.EnableLocalPassword = config.EnableLocalPassword;
  520. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  521. user.DisplayCollectionsView = config.DisplayCollectionsView;
  522. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  523. user.AudioLanguagePreference = config.AudioLanguagePreference;
  524. user.RememberAudioSelections = config.RememberAudioSelections;
  525. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  526. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  527. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  528. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  529. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  530. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  531. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  532. UpdateUser(user);
  533. }
  534. /// <inheritdoc/>
  535. public void UpdatePolicy(Guid userId, UserPolicy policy)
  536. {
  537. var user = GetUserById(userId);
  538. int? loginAttempts = policy.LoginAttemptsBeforeLockout switch
  539. {
  540. -1 => null,
  541. 0 => 3,
  542. _ => policy.LoginAttemptsBeforeLockout
  543. };
  544. user.MaxParentalAgeRating = policy.MaxParentalRating;
  545. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  546. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  547. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  548. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  549. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  550. user.LoginAttemptsBeforeLockout = loginAttempts;
  551. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  552. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  553. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  554. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  555. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  556. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  557. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  558. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  559. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  560. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  561. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  562. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  563. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  564. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  565. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  566. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  567. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  568. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  569. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  570. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  571. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  572. user.AccessSchedules.Clear();
  573. foreach (var policyAccessSchedule in policy.AccessSchedules)
  574. {
  575. user.AccessSchedules.Add(policyAccessSchedule);
  576. }
  577. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  578. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  579. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  580. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  581. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  582. }
  583. private bool IsValidUsername(string name)
  584. {
  585. // This is some regex that matches only on unicode "word" characters, as well as -, _ and @
  586. // In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
  587. // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), and periods (.)
  588. return Regex.IsMatch(name, @"^[\w\-'._@]*$");
  589. }
  590. private IAuthenticationProvider GetAuthenticationProvider(User user)
  591. {
  592. return GetAuthenticationProviders(user)[0];
  593. }
  594. private IPasswordResetProvider GetPasswordResetProvider(User user)
  595. {
  596. return GetPasswordResetProviders(user)[0];
  597. }
  598. private IList<IAuthenticationProvider> GetAuthenticationProviders(User user)
  599. {
  600. var authenticationProviderId = user?.AuthenticationProviderId;
  601. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();
  602. if (!string.IsNullOrEmpty(authenticationProviderId))
  603. {
  604. providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
  605. }
  606. if (providers.Count == 0)
  607. {
  608. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  609. _logger.LogWarning(
  610. "User {Username} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
  611. user?.Username,
  612. user?.AuthenticationProviderId);
  613. providers = new List<IAuthenticationProvider>
  614. {
  615. _invalidAuthProvider
  616. };
  617. }
  618. return providers;
  619. }
  620. private IList<IPasswordResetProvider> GetPasswordResetProviders(User user)
  621. {
  622. var passwordResetProviderId = user?.PasswordResetProviderId;
  623. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  624. if (!string.IsNullOrEmpty(passwordResetProviderId))
  625. {
  626. providers = providers.Where(i =>
  627. string.Equals(passwordResetProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase))
  628. .ToArray();
  629. }
  630. if (providers.Length == 0)
  631. {
  632. providers = new IPasswordResetProvider[]
  633. {
  634. _defaultPasswordResetProvider
  635. };
  636. }
  637. return providers;
  638. }
  639. private async Task<(IAuthenticationProvider authenticationProvider, string username, bool success)> AuthenticateLocalUser(
  640. string username,
  641. string password,
  642. User user,
  643. string remoteEndPoint)
  644. {
  645. bool success = false;
  646. IAuthenticationProvider authenticationProvider = null;
  647. foreach (var provider in GetAuthenticationProviders(user))
  648. {
  649. var providerAuthResult =
  650. await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  651. var updatedUsername = providerAuthResult.username;
  652. success = providerAuthResult.success;
  653. if (success)
  654. {
  655. authenticationProvider = provider;
  656. username = updatedUsername;
  657. break;
  658. }
  659. }
  660. if (!success
  661. && _networkManager.IsInLocalNetwork(remoteEndPoint)
  662. && user?.EnableLocalPassword == true
  663. && !string.IsNullOrEmpty(user.EasyPassword))
  664. {
  665. // Check easy password
  666. var passwordHash = PasswordHash.Parse(user.EasyPassword);
  667. var hash = _cryptoProvider.ComputeHash(
  668. passwordHash.Id,
  669. Encoding.UTF8.GetBytes(password),
  670. passwordHash.Salt.ToArray());
  671. success = passwordHash.Hash.SequenceEqual(hash);
  672. }
  673. return (authenticationProvider, username, success);
  674. }
  675. private async Task<(string username, bool success)> AuthenticateWithProvider(
  676. IAuthenticationProvider provider,
  677. string username,
  678. string password,
  679. User resolvedUser)
  680. {
  681. try
  682. {
  683. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  684. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  685. : await provider.Authenticate(username, password).ConfigureAwait(false);
  686. if (authenticationResult.Username != username)
  687. {
  688. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  689. username = authenticationResult.Username;
  690. }
  691. return (username, true);
  692. }
  693. catch (AuthenticationException ex)
  694. {
  695. _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
  696. return (username, false);
  697. }
  698. }
  699. private void IncrementInvalidLoginAttemptCount(User user)
  700. {
  701. user.InvalidLoginAttemptCount++;
  702. int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
  703. if (maxInvalidLogins.HasValue && user.InvalidLoginAttemptCount >= maxInvalidLogins)
  704. {
  705. user.SetPermission(PermissionKind.IsDisabled, true);
  706. OnUserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
  707. _logger.LogWarning(
  708. "Disabling user {Username} due to {Attempts} unsuccessful login attempts.",
  709. user.Username,
  710. user.InvalidLoginAttemptCount);
  711. }
  712. UpdateUser(user);
  713. }
  714. }
  715. }