UserManager.cs 42 KB

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