UserManager.cs 39 KB

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