UserManager.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  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 hasPassword = GetAuthenticationProvider(user).HasPassword(user);
  267. var castReceiverApplications = _serverConfigurationManager.Configuration.CastReceiverApplications;
  268. return new UserDto
  269. {
  270. Name = user.Username,
  271. Id = user.Id,
  272. ServerId = _appHost.SystemId,
  273. HasPassword = hasPassword,
  274. HasConfiguredPassword = hasPassword,
  275. EnableAutoLogin = user.EnableAutoLogin,
  276. LastLoginDate = user.LastLoginDate,
  277. LastActivityDate = user.LastActivityDate,
  278. PrimaryImageTag = user.ProfileImage is not null ? _imageProcessor.GetImageCacheTag(user) : null,
  279. Configuration = new UserConfiguration
  280. {
  281. SubtitleMode = user.SubtitleMode,
  282. HidePlayedInLatest = user.HidePlayedInLatest,
  283. EnableLocalPassword = user.EnableLocalPassword,
  284. PlayDefaultAudioTrack = user.PlayDefaultAudioTrack,
  285. DisplayCollectionsView = user.DisplayCollectionsView,
  286. DisplayMissingEpisodes = user.DisplayMissingEpisodes,
  287. AudioLanguagePreference = user.AudioLanguagePreference,
  288. RememberAudioSelections = user.RememberAudioSelections,
  289. EnableNextEpisodeAutoPlay = user.EnableNextEpisodeAutoPlay,
  290. RememberSubtitleSelections = user.RememberSubtitleSelections,
  291. SubtitleLanguagePreference = user.SubtitleLanguagePreference ?? string.Empty,
  292. OrderedViews = user.GetPreferenceValues<Guid>(PreferenceKind.OrderedViews),
  293. GroupedFolders = user.GetPreferenceValues<Guid>(PreferenceKind.GroupedFolders),
  294. MyMediaExcludes = user.GetPreferenceValues<Guid>(PreferenceKind.MyMediaExcludes),
  295. LatestItemsExcludes = user.GetPreferenceValues<Guid>(PreferenceKind.LatestItemExcludes),
  296. CastReceiverId = string.IsNullOrEmpty(user.CastReceiverId)
  297. ? castReceiverApplications.FirstOrDefault()?.Id
  298. : castReceiverApplications.FirstOrDefault(c => string.Equals(c.Id, user.CastReceiverId, StringComparison.Ordinal))?.Id
  299. ?? castReceiverApplications.FirstOrDefault()?.Id
  300. },
  301. Policy = new UserPolicy
  302. {
  303. MaxParentalRating = user.MaxParentalRatingScore,
  304. MaxParentalSubRating = user.MaxParentalRatingSubScore,
  305. EnableUserPreferenceAccess = user.EnableUserPreferenceAccess,
  306. RemoteClientBitrateLimit = user.RemoteClientBitrateLimit ?? 0,
  307. AuthenticationProviderId = user.AuthenticationProviderId,
  308. PasswordResetProviderId = user.PasswordResetProviderId,
  309. InvalidLoginAttemptCount = user.InvalidLoginAttemptCount,
  310. LoginAttemptsBeforeLockout = user.LoginAttemptsBeforeLockout ?? -1,
  311. MaxActiveSessions = user.MaxActiveSessions,
  312. IsAdministrator = user.HasPermission(PermissionKind.IsAdministrator),
  313. IsHidden = user.HasPermission(PermissionKind.IsHidden),
  314. IsDisabled = user.HasPermission(PermissionKind.IsDisabled),
  315. EnableSharedDeviceControl = user.HasPermission(PermissionKind.EnableSharedDeviceControl),
  316. EnableRemoteAccess = user.HasPermission(PermissionKind.EnableRemoteAccess),
  317. EnableLiveTvManagement = user.HasPermission(PermissionKind.EnableLiveTvManagement),
  318. EnableLiveTvAccess = user.HasPermission(PermissionKind.EnableLiveTvAccess),
  319. EnableMediaPlayback = user.HasPermission(PermissionKind.EnableMediaPlayback),
  320. EnableAudioPlaybackTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding),
  321. EnableVideoPlaybackTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding),
  322. EnableContentDeletion = user.HasPermission(PermissionKind.EnableContentDeletion),
  323. EnableContentDownloading = user.HasPermission(PermissionKind.EnableContentDownloading),
  324. EnableSyncTranscoding = user.HasPermission(PermissionKind.EnableSyncTranscoding),
  325. EnableMediaConversion = user.HasPermission(PermissionKind.EnableMediaConversion),
  326. EnableAllChannels = user.HasPermission(PermissionKind.EnableAllChannels),
  327. EnableAllDevices = user.HasPermission(PermissionKind.EnableAllDevices),
  328. EnableAllFolders = user.HasPermission(PermissionKind.EnableAllFolders),
  329. EnableRemoteControlOfOtherUsers = user.HasPermission(PermissionKind.EnableRemoteControlOfOtherUsers),
  330. EnablePlaybackRemuxing = user.HasPermission(PermissionKind.EnablePlaybackRemuxing),
  331. ForceRemoteSourceTranscoding = user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding),
  332. EnablePublicSharing = user.HasPermission(PermissionKind.EnablePublicSharing),
  333. EnableCollectionManagement = user.HasPermission(PermissionKind.EnableCollectionManagement),
  334. EnableSubtitleManagement = user.HasPermission(PermissionKind.EnableSubtitleManagement),
  335. AccessSchedules = user.AccessSchedules.ToArray(),
  336. BlockedTags = user.GetPreference(PreferenceKind.BlockedTags),
  337. AllowedTags = user.GetPreference(PreferenceKind.AllowedTags),
  338. EnabledChannels = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledChannels),
  339. EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices),
  340. EnabledFolders = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders),
  341. EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders),
  342. SyncPlayAccess = user.SyncPlayAccess,
  343. BlockedChannels = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedChannels),
  344. BlockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders),
  345. BlockUnratedItems = user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems)
  346. }
  347. };
  348. }
  349. /// <inheritdoc/>
  350. public async Task<User?> AuthenticateUser(
  351. string username,
  352. string password,
  353. string remoteEndPoint,
  354. bool isUserSession)
  355. {
  356. if (string.IsNullOrWhiteSpace(username))
  357. {
  358. _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
  359. throw new ArgumentNullException(nameof(username));
  360. }
  361. var user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  362. var authResult = await AuthenticateLocalUser(username, password, user)
  363. .ConfigureAwait(false);
  364. var authenticationProvider = authResult.AuthenticationProvider;
  365. var success = authResult.Success;
  366. if (user is null)
  367. {
  368. string updatedUsername = authResult.Username;
  369. if (success
  370. && authenticationProvider is not null
  371. && authenticationProvider is not DefaultAuthenticationProvider)
  372. {
  373. // Trust the username returned by the authentication provider
  374. username = updatedUsername;
  375. // Search the database for the user again
  376. // the authentication provider might have created it
  377. user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  378. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy && user is not null)
  379. {
  380. await UpdatePolicyAsync(user.Id, hasNewUserPolicy.GetNewUserPolicy()).ConfigureAwait(false);
  381. }
  382. }
  383. }
  384. if (success && user is not null && authenticationProvider is not null)
  385. {
  386. var providerId = authenticationProvider.GetType().FullName;
  387. if (providerId is not null && !string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  388. {
  389. user.AuthenticationProviderId = providerId;
  390. await UpdateUserAsync(user).ConfigureAwait(false);
  391. }
  392. }
  393. if (user is null)
  394. {
  395. _logger.LogInformation(
  396. "Authentication request for {UserName} has been denied (IP: {IP}).",
  397. username,
  398. remoteEndPoint);
  399. throw new AuthenticationException("Invalid username or password entered.");
  400. }
  401. if (user.HasPermission(PermissionKind.IsDisabled))
  402. {
  403. _logger.LogInformation(
  404. "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
  405. username,
  406. remoteEndPoint);
  407. throw new SecurityException(
  408. $"The {user.Username} account is currently disabled. Please consult with your administrator.");
  409. }
  410. if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
  411. !_networkManager.IsInLocalNetwork(remoteEndPoint))
  412. {
  413. _logger.LogInformation(
  414. "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
  415. username,
  416. remoteEndPoint);
  417. throw new SecurityException("Forbidden.");
  418. }
  419. if (!user.IsParentalScheduleAllowed())
  420. {
  421. _logger.LogInformation(
  422. "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
  423. username,
  424. remoteEndPoint);
  425. throw new SecurityException("User is not allowed access at this time.");
  426. }
  427. // Update LastActivityDate and LastLoginDate, then save
  428. if (success)
  429. {
  430. if (isUserSession)
  431. {
  432. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  433. }
  434. user.InvalidLoginAttemptCount = 0;
  435. await UpdateUserAsync(user).ConfigureAwait(false);
  436. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
  437. }
  438. else
  439. {
  440. await IncrementInvalidLoginAttemptCount(user).ConfigureAwait(false);
  441. _logger.LogInformation(
  442. "Authentication request for {UserName} has been denied (IP: {IP}).",
  443. user.Username,
  444. remoteEndPoint);
  445. }
  446. return success ? user : null;
  447. }
  448. /// <inheritdoc/>
  449. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  450. {
  451. var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
  452. var passwordResetProvider = GetPasswordResetProvider(user);
  453. var result = await passwordResetProvider
  454. .StartForgotPasswordProcess(user, enteredUsername, isInNetwork)
  455. .ConfigureAwait(false);
  456. if (user is not null && isInNetwork)
  457. {
  458. await UpdateUserAsync(user).ConfigureAwait(false);
  459. }
  460. return result;
  461. }
  462. /// <inheritdoc/>
  463. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  464. {
  465. foreach (var provider in _passwordResetProviders)
  466. {
  467. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  468. if (result.Success)
  469. {
  470. return result;
  471. }
  472. }
  473. return new PinRedeemResult();
  474. }
  475. /// <inheritdoc />
  476. public async Task InitializeAsync()
  477. {
  478. // TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
  479. if (_users.Any())
  480. {
  481. return;
  482. }
  483. var defaultName = Environment.UserName;
  484. if (string.IsNullOrWhiteSpace(defaultName) || !ValidUsernameRegex().IsMatch(defaultName))
  485. {
  486. defaultName = "MyJellyfinUser";
  487. }
  488. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  489. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  490. await using (dbContext.ConfigureAwait(false))
  491. {
  492. var newUser = await CreateUserInternalAsync(defaultName, dbContext).ConfigureAwait(false);
  493. newUser.SetPermission(PermissionKind.IsAdministrator, true);
  494. newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
  495. newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
  496. dbContext.Users.Add(newUser);
  497. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  498. _users.Add(newUser.Id, newUser);
  499. }
  500. }
  501. /// <inheritdoc/>
  502. public NameIdPair[] GetAuthenticationProviders()
  503. {
  504. return _authenticationProviders
  505. .Where(provider => provider.IsEnabled)
  506. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  507. .ThenBy(i => i.Name)
  508. .Select(i => new NameIdPair
  509. {
  510. Name = i.Name,
  511. Id = i.GetType().FullName
  512. })
  513. .ToArray();
  514. }
  515. /// <inheritdoc/>
  516. public NameIdPair[] GetPasswordResetProviders()
  517. {
  518. return _passwordResetProviders
  519. .Where(provider => provider.IsEnabled)
  520. .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
  521. .ThenBy(i => i.Name)
  522. .Select(i => new NameIdPair
  523. {
  524. Name = i.Name,
  525. Id = i.GetType().FullName
  526. })
  527. .ToArray();
  528. }
  529. /// <inheritdoc/>
  530. public async Task UpdateConfigurationAsync(Guid userId, UserConfiguration config)
  531. {
  532. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  533. await using (dbContext.ConfigureAwait(false))
  534. {
  535. var user = dbContext.Users
  536. .Include(u => u.Permissions)
  537. .Include(u => u.Preferences)
  538. .Include(u => u.AccessSchedules)
  539. .Include(u => u.ProfileImage)
  540. .FirstOrDefault(u => u.Id.Equals(userId))
  541. ?? throw new ArgumentException("No user exists with given Id!");
  542. user.SubtitleMode = config.SubtitleMode;
  543. user.HidePlayedInLatest = config.HidePlayedInLatest;
  544. user.EnableLocalPassword = config.EnableLocalPassword;
  545. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  546. user.DisplayCollectionsView = config.DisplayCollectionsView;
  547. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  548. user.AudioLanguagePreference = config.AudioLanguagePreference;
  549. user.RememberAudioSelections = config.RememberAudioSelections;
  550. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  551. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  552. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  553. // Only set cast receiver id if it is passed in and it exists in the server config.
  554. if (!string.IsNullOrEmpty(config.CastReceiverId)
  555. && _serverConfigurationManager.Configuration.CastReceiverApplications.Any(c => string.Equals(c.Id, config.CastReceiverId, StringComparison.Ordinal)))
  556. {
  557. user.CastReceiverId = config.CastReceiverId;
  558. }
  559. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  560. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  561. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  562. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  563. dbContext.Update(user);
  564. _users[user.Id] = user;
  565. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  566. }
  567. }
  568. /// <inheritdoc/>
  569. public async Task UpdatePolicyAsync(Guid userId, UserPolicy policy)
  570. {
  571. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  572. await using (dbContext.ConfigureAwait(false))
  573. {
  574. var user = dbContext.Users
  575. .Include(u => u.Permissions)
  576. .Include(u => u.Preferences)
  577. .Include(u => u.AccessSchedules)
  578. .Include(u => u.ProfileImage)
  579. .FirstOrDefault(u => u.Id.Equals(userId))
  580. ?? throw new ArgumentException("No user exists with given Id!");
  581. // The default number of login attempts is 3, but for some god forsaken reason it's sent to the server as "0"
  582. int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
  583. {
  584. -1 => null,
  585. 0 => 3,
  586. _ => policy.LoginAttemptsBeforeLockout
  587. };
  588. user.MaxParentalRatingScore = policy.MaxParentalRating;
  589. user.MaxParentalRatingSubScore = policy.MaxParentalSubRating;
  590. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  591. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  592. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  593. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  594. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  595. user.LoginAttemptsBeforeLockout = maxLoginAttempts;
  596. user.MaxActiveSessions = policy.MaxActiveSessions;
  597. user.SyncPlayAccess = policy.SyncPlayAccess;
  598. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  599. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  600. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  601. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  602. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  603. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  604. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  605. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  606. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  607. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  608. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  609. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  610. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  611. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  612. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  613. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  614. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  615. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  616. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  617. user.SetPermission(PermissionKind.EnableCollectionManagement, policy.EnableCollectionManagement);
  618. user.SetPermission(PermissionKind.EnableSubtitleManagement, policy.EnableSubtitleManagement);
  619. user.SetPermission(PermissionKind.EnableLyricManagement, policy.EnableLyricManagement);
  620. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  621. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  622. user.AccessSchedules.Clear();
  623. foreach (var policyAccessSchedule in policy.AccessSchedules)
  624. {
  625. user.AccessSchedules.Add(policyAccessSchedule);
  626. }
  627. // TODO: fix this at some point
  628. user.SetPreference(PreferenceKind.BlockUnratedItems, policy.BlockUnratedItems ?? Array.Empty<UnratedItem>());
  629. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  630. user.SetPreference(PreferenceKind.AllowedTags, policy.AllowedTags);
  631. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  632. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  633. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  634. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  635. dbContext.Update(user);
  636. _users[user.Id] = user;
  637. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  638. }
  639. }
  640. /// <inheritdoc/>
  641. public async Task ClearProfileImageAsync(User user)
  642. {
  643. if (user.ProfileImage is null)
  644. {
  645. return;
  646. }
  647. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  648. await using (dbContext.ConfigureAwait(false))
  649. {
  650. dbContext.Remove(user.ProfileImage);
  651. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  652. }
  653. user.ProfileImage = null;
  654. _users[user.Id] = user;
  655. }
  656. internal static void ThrowIfInvalidUsername(string name)
  657. {
  658. if (!string.IsNullOrWhiteSpace(name) && ValidUsernameRegex().IsMatch(name))
  659. {
  660. return;
  661. }
  662. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)", nameof(name));
  663. }
  664. private IAuthenticationProvider GetAuthenticationProvider(User user)
  665. {
  666. return GetAuthenticationProviders(user)[0];
  667. }
  668. private IPasswordResetProvider GetPasswordResetProvider(User? user)
  669. {
  670. if (user is null)
  671. {
  672. return _defaultPasswordResetProvider;
  673. }
  674. return GetPasswordResetProviders(user)[0];
  675. }
  676. private List<IAuthenticationProvider> GetAuthenticationProviders(User? user)
  677. {
  678. var authenticationProviderId = user?.AuthenticationProviderId;
  679. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();
  680. if (!string.IsNullOrEmpty(authenticationProviderId))
  681. {
  682. providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
  683. }
  684. if (providers.Count == 0)
  685. {
  686. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  687. _logger.LogWarning(
  688. "User {Username} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
  689. user?.Username,
  690. user?.AuthenticationProviderId);
  691. providers = new List<IAuthenticationProvider>
  692. {
  693. _invalidAuthProvider
  694. };
  695. }
  696. return providers;
  697. }
  698. private IPasswordResetProvider[] GetPasswordResetProviders(User user)
  699. {
  700. var passwordResetProviderId = user.PasswordResetProviderId;
  701. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  702. if (!string.IsNullOrEmpty(passwordResetProviderId))
  703. {
  704. providers = providers.Where(i =>
  705. string.Equals(passwordResetProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase))
  706. .ToArray();
  707. }
  708. if (providers.Length == 0)
  709. {
  710. providers = new IPasswordResetProvider[]
  711. {
  712. _defaultPasswordResetProvider
  713. };
  714. }
  715. return providers;
  716. }
  717. private async Task<(IAuthenticationProvider? AuthenticationProvider, string Username, bool Success)> AuthenticateLocalUser(
  718. string username,
  719. string password,
  720. User? user)
  721. {
  722. bool success = false;
  723. IAuthenticationProvider? authenticationProvider = null;
  724. foreach (var provider in GetAuthenticationProviders(user))
  725. {
  726. var providerAuthResult =
  727. await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  728. var updatedUsername = providerAuthResult.Username;
  729. success = providerAuthResult.Success;
  730. if (success)
  731. {
  732. authenticationProvider = provider;
  733. username = updatedUsername;
  734. break;
  735. }
  736. }
  737. return (authenticationProvider, username, success);
  738. }
  739. private async Task<(string Username, bool Success)> AuthenticateWithProvider(
  740. IAuthenticationProvider provider,
  741. string username,
  742. string password,
  743. User? resolvedUser)
  744. {
  745. try
  746. {
  747. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  748. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  749. : await provider.Authenticate(username, password).ConfigureAwait(false);
  750. if (authenticationResult.Username != username)
  751. {
  752. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  753. username = authenticationResult.Username;
  754. }
  755. return (username, true);
  756. }
  757. catch (AuthenticationException ex)
  758. {
  759. _logger.LogDebug(ex, "Error authenticating with provider {Provider}", provider.Name);
  760. return (username, false);
  761. }
  762. }
  763. private async Task IncrementInvalidLoginAttemptCount(User user)
  764. {
  765. user.InvalidLoginAttemptCount++;
  766. int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
  767. if (maxInvalidLogins.HasValue && user.InvalidLoginAttemptCount >= maxInvalidLogins)
  768. {
  769. user.SetPermission(PermissionKind.IsDisabled, true);
  770. await _eventManager.PublishAsync(new UserLockedOutEventArgs(user)).ConfigureAwait(false);
  771. _logger.LogWarning(
  772. "Disabling user {Username} due to {Attempts} unsuccessful login attempts.",
  773. user.Username,
  774. user.InvalidLoginAttemptCount);
  775. }
  776. await UpdateUserAsync(user).ConfigureAwait(false);
  777. }
  778. private async Task UpdateUserInternalAsync(JellyfinDbContext dbContext, User user)
  779. {
  780. dbContext.Users.Attach(user);
  781. dbContext.Entry(user).State = EntityState.Modified;
  782. _users[user.Id] = user;
  783. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  784. }
  785. }
  786. }