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. if (user is not null && isInNetwork)
  453. {
  454. var passwordResetProvider = GetPasswordResetProvider(user);
  455. var result = await passwordResetProvider
  456. .StartForgotPasswordProcess(user, isInNetwork)
  457. .ConfigureAwait(false);
  458. await UpdateUserAsync(user).ConfigureAwait(false);
  459. return result;
  460. }
  461. return new ForgotPasswordResult
  462. {
  463. Action = ForgotPasswordAction.InNetworkRequired,
  464. PinFile = string.Empty
  465. };
  466. }
  467. /// <inheritdoc/>
  468. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  469. {
  470. foreach (var provider in _passwordResetProviders)
  471. {
  472. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  473. if (result.Success)
  474. {
  475. return result;
  476. }
  477. }
  478. return new PinRedeemResult();
  479. }
  480. /// <inheritdoc />
  481. public async Task InitializeAsync()
  482. {
  483. // TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
  484. if (_users.Any())
  485. {
  486. return;
  487. }
  488. var defaultName = Environment.UserName;
  489. if (string.IsNullOrWhiteSpace(defaultName) || !ValidUsernameRegex().IsMatch(defaultName))
  490. {
  491. defaultName = "MyJellyfinUser";
  492. }
  493. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  494. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  495. await using (dbContext.ConfigureAwait(false))
  496. {
  497. var newUser = await CreateUserInternalAsync(defaultName, dbContext).ConfigureAwait(false);
  498. newUser.SetPermission(PermissionKind.IsAdministrator, true);
  499. newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
  500. newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
  501. dbContext.Users.Add(newUser);
  502. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  503. _users.Add(newUser.Id, newUser);
  504. }
  505. }
  506. /// <inheritdoc/>
  507. public NameIdPair[] GetAuthenticationProviders()
  508. {
  509. return _authenticationProviders
  510. .Where(provider => provider.IsEnabled)
  511. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  512. .ThenBy(i => i.Name)
  513. .Select(i => new NameIdPair
  514. {
  515. Name = i.Name,
  516. Id = i.GetType().FullName
  517. })
  518. .ToArray();
  519. }
  520. /// <inheritdoc/>
  521. public NameIdPair[] GetPasswordResetProviders()
  522. {
  523. return _passwordResetProviders
  524. .Where(provider => provider.IsEnabled)
  525. .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
  526. .ThenBy(i => i.Name)
  527. .Select(i => new NameIdPair
  528. {
  529. Name = i.Name,
  530. Id = i.GetType().FullName
  531. })
  532. .ToArray();
  533. }
  534. /// <inheritdoc/>
  535. public async Task UpdateConfigurationAsync(Guid userId, UserConfiguration config)
  536. {
  537. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  538. await using (dbContext.ConfigureAwait(false))
  539. {
  540. var user = dbContext.Users
  541. .Include(u => u.Permissions)
  542. .Include(u => u.Preferences)
  543. .Include(u => u.AccessSchedules)
  544. .Include(u => u.ProfileImage)
  545. .FirstOrDefault(u => u.Id.Equals(userId))
  546. ?? throw new ArgumentException("No user exists with given Id!");
  547. user.SubtitleMode = config.SubtitleMode;
  548. user.HidePlayedInLatest = config.HidePlayedInLatest;
  549. user.EnableLocalPassword = config.EnableLocalPassword;
  550. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  551. user.DisplayCollectionsView = config.DisplayCollectionsView;
  552. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  553. user.AudioLanguagePreference = config.AudioLanguagePreference;
  554. user.RememberAudioSelections = config.RememberAudioSelections;
  555. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  556. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  557. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  558. // Only set cast receiver id if it is passed in and it exists in the server config.
  559. if (!string.IsNullOrEmpty(config.CastReceiverId)
  560. && _serverConfigurationManager.Configuration.CastReceiverApplications.Any(c => string.Equals(c.Id, config.CastReceiverId, StringComparison.Ordinal)))
  561. {
  562. user.CastReceiverId = config.CastReceiverId;
  563. }
  564. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  565. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  566. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  567. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  568. dbContext.Update(user);
  569. _users[user.Id] = user;
  570. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  571. }
  572. }
  573. /// <inheritdoc/>
  574. public async Task UpdatePolicyAsync(Guid userId, UserPolicy policy)
  575. {
  576. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  577. await using (dbContext.ConfigureAwait(false))
  578. {
  579. var user = dbContext.Users
  580. .Include(u => u.Permissions)
  581. .Include(u => u.Preferences)
  582. .Include(u => u.AccessSchedules)
  583. .Include(u => u.ProfileImage)
  584. .FirstOrDefault(u => u.Id.Equals(userId))
  585. ?? throw new ArgumentException("No user exists with given Id!");
  586. // The default number of login attempts is 3, but for some god forsaken reason it's sent to the server as "0"
  587. int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
  588. {
  589. -1 => null,
  590. 0 => 3,
  591. _ => policy.LoginAttemptsBeforeLockout
  592. };
  593. user.MaxParentalRatingScore = policy.MaxParentalRating;
  594. user.MaxParentalRatingSubScore = policy.MaxParentalSubRating;
  595. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  596. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  597. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  598. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  599. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  600. user.LoginAttemptsBeforeLockout = maxLoginAttempts;
  601. user.MaxActiveSessions = policy.MaxActiveSessions;
  602. user.SyncPlayAccess = policy.SyncPlayAccess;
  603. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  604. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  605. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  606. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  607. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  608. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  609. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  610. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  611. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  612. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  613. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  614. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  615. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  616. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  617. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  618. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  619. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  620. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  621. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  622. user.SetPermission(PermissionKind.EnableCollectionManagement, policy.EnableCollectionManagement);
  623. user.SetPermission(PermissionKind.EnableSubtitleManagement, policy.EnableSubtitleManagement);
  624. user.SetPermission(PermissionKind.EnableLyricManagement, policy.EnableLyricManagement);
  625. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  626. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  627. user.AccessSchedules.Clear();
  628. foreach (var policyAccessSchedule in policy.AccessSchedules)
  629. {
  630. user.AccessSchedules.Add(policyAccessSchedule);
  631. }
  632. // TODO: fix this at some point
  633. user.SetPreference(PreferenceKind.BlockUnratedItems, policy.BlockUnratedItems ?? Array.Empty<UnratedItem>());
  634. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  635. user.SetPreference(PreferenceKind.AllowedTags, policy.AllowedTags);
  636. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  637. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  638. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  639. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  640. dbContext.Update(user);
  641. _users[user.Id] = user;
  642. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  643. }
  644. }
  645. /// <inheritdoc/>
  646. public async Task ClearProfileImageAsync(User user)
  647. {
  648. if (user.ProfileImage is null)
  649. {
  650. return;
  651. }
  652. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  653. await using (dbContext.ConfigureAwait(false))
  654. {
  655. dbContext.Remove(user.ProfileImage);
  656. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  657. }
  658. user.ProfileImage = null;
  659. _users[user.Id] = user;
  660. }
  661. internal static void ThrowIfInvalidUsername(string name)
  662. {
  663. if (!string.IsNullOrWhiteSpace(name) && ValidUsernameRegex().IsMatch(name))
  664. {
  665. return;
  666. }
  667. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)", nameof(name));
  668. }
  669. private IAuthenticationProvider GetAuthenticationProvider(User user)
  670. {
  671. return GetAuthenticationProviders(user)[0];
  672. }
  673. private IPasswordResetProvider GetPasswordResetProvider(User user)
  674. {
  675. return GetPasswordResetProviders(user)[0];
  676. }
  677. private List<IAuthenticationProvider> GetAuthenticationProviders(User? user)
  678. {
  679. var authenticationProviderId = user?.AuthenticationProviderId;
  680. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();
  681. if (!string.IsNullOrEmpty(authenticationProviderId))
  682. {
  683. providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
  684. }
  685. if (providers.Count == 0)
  686. {
  687. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  688. _logger.LogWarning(
  689. "User {Username} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
  690. user?.Username,
  691. user?.AuthenticationProviderId);
  692. providers = new List<IAuthenticationProvider>
  693. {
  694. _invalidAuthProvider
  695. };
  696. }
  697. return providers;
  698. }
  699. private IPasswordResetProvider[] GetPasswordResetProviders(User user)
  700. {
  701. var passwordResetProviderId = user.PasswordResetProviderId;
  702. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  703. if (!string.IsNullOrEmpty(passwordResetProviderId))
  704. {
  705. providers = providers.Where(i =>
  706. string.Equals(passwordResetProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase))
  707. .ToArray();
  708. }
  709. if (providers.Length == 0)
  710. {
  711. providers = new IPasswordResetProvider[]
  712. {
  713. _defaultPasswordResetProvider
  714. };
  715. }
  716. return providers;
  717. }
  718. private async Task<(IAuthenticationProvider? AuthenticationProvider, string Username, bool Success)> AuthenticateLocalUser(
  719. string username,
  720. string password,
  721. User? user)
  722. {
  723. bool success = false;
  724. IAuthenticationProvider? authenticationProvider = null;
  725. foreach (var provider in GetAuthenticationProviders(user))
  726. {
  727. var providerAuthResult =
  728. await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  729. var updatedUsername = providerAuthResult.Username;
  730. success = providerAuthResult.Success;
  731. if (success)
  732. {
  733. authenticationProvider = provider;
  734. username = updatedUsername;
  735. break;
  736. }
  737. }
  738. return (authenticationProvider, username, success);
  739. }
  740. private async Task<(string Username, bool Success)> AuthenticateWithProvider(
  741. IAuthenticationProvider provider,
  742. string username,
  743. string password,
  744. User? resolvedUser)
  745. {
  746. try
  747. {
  748. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  749. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  750. : await provider.Authenticate(username, password).ConfigureAwait(false);
  751. if (authenticationResult.Username != username)
  752. {
  753. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  754. username = authenticationResult.Username;
  755. }
  756. return (username, true);
  757. }
  758. catch (AuthenticationException ex)
  759. {
  760. _logger.LogDebug(ex, "Error authenticating with provider {Provider}", provider.Name);
  761. return (username, false);
  762. }
  763. }
  764. private async Task IncrementInvalidLoginAttemptCount(User user)
  765. {
  766. user.InvalidLoginAttemptCount++;
  767. int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
  768. if (maxInvalidLogins.HasValue && user.InvalidLoginAttemptCount >= maxInvalidLogins)
  769. {
  770. user.SetPermission(PermissionKind.IsDisabled, true);
  771. await _eventManager.PublishAsync(new UserLockedOutEventArgs(user)).ConfigureAwait(false);
  772. _logger.LogWarning(
  773. "Disabling user {Username} due to {Attempts} unsuccessful login attempts.",
  774. user.Username,
  775. user.InvalidLoginAttemptCount);
  776. }
  777. await UpdateUserAsync(user).ConfigureAwait(false);
  778. }
  779. private async Task UpdateUserInternalAsync(JellyfinDbContext dbContext, User user)
  780. {
  781. dbContext.Users.Attach(user);
  782. dbContext.Entry(user).State = EntityState.Modified;
  783. _users[user.Id] = user;
  784. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  785. }
  786. }
  787. }