UserManager.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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.Remove(user);
  240. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  241. }
  242. _users.Remove(userId);
  243. await _eventManager.PublishAsync(new UserDeletedEventArgs(user)).ConfigureAwait(false);
  244. }
  245. /// <inheritdoc/>
  246. public Task ResetPassword(User user)
  247. {
  248. return ChangePassword(user, string.Empty);
  249. }
  250. /// <inheritdoc/>
  251. public async Task ChangePassword(User user, string newPassword)
  252. {
  253. ArgumentNullException.ThrowIfNull(user);
  254. if (user.HasPermission(PermissionKind.IsAdministrator) && string.IsNullOrWhiteSpace(newPassword))
  255. {
  256. throw new ArgumentException("Admin user passwords must not be empty", nameof(newPassword));
  257. }
  258. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  259. await UpdateUserAsync(user).ConfigureAwait(false);
  260. await _eventManager.PublishAsync(new UserPasswordChangedEventArgs(user)).ConfigureAwait(false);
  261. }
  262. /// <inheritdoc/>
  263. public UserDto GetUserDto(User user, string? remoteEndPoint = null)
  264. {
  265. var hasPassword = GetAuthenticationProvider(user).HasPassword(user);
  266. var castReceiverApplications = _serverConfigurationManager.Configuration.CastReceiverApplications;
  267. return new UserDto
  268. {
  269. Name = user.Username,
  270. Id = user.Id,
  271. ServerId = _appHost.SystemId,
  272. HasPassword = hasPassword,
  273. HasConfiguredPassword = hasPassword,
  274. EnableAutoLogin = user.EnableAutoLogin,
  275. LastLoginDate = user.LastLoginDate,
  276. LastActivityDate = user.LastActivityDate,
  277. PrimaryImageTag = user.ProfileImage is not null ? _imageProcessor.GetImageCacheTag(user) : null,
  278. Configuration = new UserConfiguration
  279. {
  280. SubtitleMode = user.SubtitleMode,
  281. HidePlayedInLatest = user.HidePlayedInLatest,
  282. EnableLocalPassword = user.EnableLocalPassword,
  283. PlayDefaultAudioTrack = user.PlayDefaultAudioTrack,
  284. DisplayCollectionsView = user.DisplayCollectionsView,
  285. DisplayMissingEpisodes = user.DisplayMissingEpisodes,
  286. AudioLanguagePreference = user.AudioLanguagePreference,
  287. RememberAudioSelections = user.RememberAudioSelections,
  288. EnableNextEpisodeAutoPlay = user.EnableNextEpisodeAutoPlay,
  289. RememberSubtitleSelections = user.RememberSubtitleSelections,
  290. SubtitleLanguagePreference = user.SubtitleLanguagePreference ?? string.Empty,
  291. OrderedViews = user.GetPreferenceValues<Guid>(PreferenceKind.OrderedViews),
  292. GroupedFolders = user.GetPreferenceValues<Guid>(PreferenceKind.GroupedFolders),
  293. MyMediaExcludes = user.GetPreferenceValues<Guid>(PreferenceKind.MyMediaExcludes),
  294. LatestItemsExcludes = user.GetPreferenceValues<Guid>(PreferenceKind.LatestItemExcludes),
  295. CastReceiverId = string.IsNullOrEmpty(user.CastReceiverId)
  296. ? castReceiverApplications.FirstOrDefault()?.Id
  297. : castReceiverApplications.FirstOrDefault(c => string.Equals(c.Id, user.CastReceiverId, StringComparison.Ordinal))?.Id
  298. ?? castReceiverApplications.FirstOrDefault()?.Id
  299. },
  300. Policy = new UserPolicy
  301. {
  302. MaxParentalRating = user.MaxParentalRatingScore,
  303. MaxParentalSubRating = user.MaxParentalRatingSubScore,
  304. EnableUserPreferenceAccess = user.EnableUserPreferenceAccess,
  305. RemoteClientBitrateLimit = user.RemoteClientBitrateLimit ?? 0,
  306. AuthenticationProviderId = user.AuthenticationProviderId,
  307. PasswordResetProviderId = user.PasswordResetProviderId,
  308. InvalidLoginAttemptCount = user.InvalidLoginAttemptCount,
  309. LoginAttemptsBeforeLockout = user.LoginAttemptsBeforeLockout ?? -1,
  310. MaxActiveSessions = user.MaxActiveSessions,
  311. IsAdministrator = user.HasPermission(PermissionKind.IsAdministrator),
  312. IsHidden = user.HasPermission(PermissionKind.IsHidden),
  313. IsDisabled = user.HasPermission(PermissionKind.IsDisabled),
  314. EnableSharedDeviceControl = user.HasPermission(PermissionKind.EnableSharedDeviceControl),
  315. EnableRemoteAccess = user.HasPermission(PermissionKind.EnableRemoteAccess),
  316. EnableLiveTvManagement = user.HasPermission(PermissionKind.EnableLiveTvManagement),
  317. EnableLiveTvAccess = user.HasPermission(PermissionKind.EnableLiveTvAccess),
  318. EnableMediaPlayback = user.HasPermission(PermissionKind.EnableMediaPlayback),
  319. EnableAudioPlaybackTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding),
  320. EnableVideoPlaybackTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding),
  321. EnableContentDeletion = user.HasPermission(PermissionKind.EnableContentDeletion),
  322. EnableContentDownloading = user.HasPermission(PermissionKind.EnableContentDownloading),
  323. EnableSyncTranscoding = user.HasPermission(PermissionKind.EnableSyncTranscoding),
  324. EnableMediaConversion = user.HasPermission(PermissionKind.EnableMediaConversion),
  325. EnableAllChannels = user.HasPermission(PermissionKind.EnableAllChannels),
  326. EnableAllDevices = user.HasPermission(PermissionKind.EnableAllDevices),
  327. EnableAllFolders = user.HasPermission(PermissionKind.EnableAllFolders),
  328. EnableRemoteControlOfOtherUsers = user.HasPermission(PermissionKind.EnableRemoteControlOfOtherUsers),
  329. EnablePlaybackRemuxing = user.HasPermission(PermissionKind.EnablePlaybackRemuxing),
  330. ForceRemoteSourceTranscoding = user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding),
  331. EnablePublicSharing = user.HasPermission(PermissionKind.EnablePublicSharing),
  332. EnableCollectionManagement = user.HasPermission(PermissionKind.EnableCollectionManagement),
  333. EnableSubtitleManagement = user.HasPermission(PermissionKind.EnableSubtitleManagement),
  334. AccessSchedules = user.AccessSchedules.ToArray(),
  335. BlockedTags = user.GetPreference(PreferenceKind.BlockedTags),
  336. AllowedTags = user.GetPreference(PreferenceKind.AllowedTags),
  337. EnabledChannels = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledChannels),
  338. EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices),
  339. EnabledFolders = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders),
  340. EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders),
  341. SyncPlayAccess = user.SyncPlayAccess,
  342. BlockedChannels = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedChannels),
  343. BlockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders),
  344. BlockUnratedItems = user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems)
  345. }
  346. };
  347. }
  348. /// <inheritdoc/>
  349. public async Task<User?> AuthenticateUser(
  350. string username,
  351. string password,
  352. string remoteEndPoint,
  353. bool isUserSession)
  354. {
  355. if (string.IsNullOrWhiteSpace(username))
  356. {
  357. _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
  358. throw new ArgumentNullException(nameof(username));
  359. }
  360. var user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  361. var authResult = await AuthenticateLocalUser(username, password, user)
  362. .ConfigureAwait(false);
  363. var authenticationProvider = authResult.AuthenticationProvider;
  364. var success = authResult.Success;
  365. if (user is null)
  366. {
  367. string updatedUsername = authResult.Username;
  368. if (success
  369. && authenticationProvider is not null
  370. && authenticationProvider is not DefaultAuthenticationProvider)
  371. {
  372. // Trust the username returned by the authentication provider
  373. username = updatedUsername;
  374. // Search the database for the user again
  375. // the authentication provider might have created it
  376. user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  377. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy && user is not null)
  378. {
  379. await UpdatePolicyAsync(user.Id, hasNewUserPolicy.GetNewUserPolicy()).ConfigureAwait(false);
  380. }
  381. }
  382. }
  383. if (success && user is not null && authenticationProvider is not null)
  384. {
  385. var providerId = authenticationProvider.GetType().FullName;
  386. if (providerId is not null && !string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  387. {
  388. user.AuthenticationProviderId = providerId;
  389. await UpdateUserAsync(user).ConfigureAwait(false);
  390. }
  391. }
  392. if (user is null)
  393. {
  394. _logger.LogInformation(
  395. "Authentication request for {UserName} has been denied (IP: {IP}).",
  396. username,
  397. remoteEndPoint);
  398. throw new AuthenticationException("Invalid username or password entered.");
  399. }
  400. if (user.HasPermission(PermissionKind.IsDisabled))
  401. {
  402. _logger.LogInformation(
  403. "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
  404. username,
  405. remoteEndPoint);
  406. throw new SecurityException(
  407. $"The {user.Username} account is currently disabled. Please consult with your administrator.");
  408. }
  409. if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
  410. !_networkManager.IsInLocalNetwork(remoteEndPoint))
  411. {
  412. _logger.LogInformation(
  413. "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
  414. username,
  415. remoteEndPoint);
  416. throw new SecurityException("Forbidden.");
  417. }
  418. if (!user.IsParentalScheduleAllowed())
  419. {
  420. _logger.LogInformation(
  421. "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
  422. username,
  423. remoteEndPoint);
  424. throw new SecurityException("User is not allowed access at this time.");
  425. }
  426. // Update LastActivityDate and LastLoginDate, then save
  427. if (success)
  428. {
  429. if (isUserSession)
  430. {
  431. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  432. }
  433. user.InvalidLoginAttemptCount = 0;
  434. await UpdateUserAsync(user).ConfigureAwait(false);
  435. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
  436. }
  437. else
  438. {
  439. await IncrementInvalidLoginAttemptCount(user).ConfigureAwait(false);
  440. _logger.LogInformation(
  441. "Authentication request for {UserName} has been denied (IP: {IP}).",
  442. user.Username,
  443. remoteEndPoint);
  444. }
  445. return success ? user : null;
  446. }
  447. /// <inheritdoc/>
  448. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  449. {
  450. var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
  451. if (user is not null && isInNetwork)
  452. {
  453. var passwordResetProvider = GetPasswordResetProvider(user);
  454. var result = await passwordResetProvider
  455. .StartForgotPasswordProcess(user, isInNetwork)
  456. .ConfigureAwait(false);
  457. await UpdateUserAsync(user).ConfigureAwait(false);
  458. return result;
  459. }
  460. return new ForgotPasswordResult
  461. {
  462. Action = ForgotPasswordAction.InNetworkRequired,
  463. PinFile = string.Empty
  464. };
  465. }
  466. /// <inheritdoc/>
  467. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  468. {
  469. foreach (var provider in _passwordResetProviders)
  470. {
  471. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  472. if (result.Success)
  473. {
  474. return result;
  475. }
  476. }
  477. return new PinRedeemResult();
  478. }
  479. /// <inheritdoc />
  480. public async Task InitializeAsync()
  481. {
  482. // TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
  483. if (_users.Any())
  484. {
  485. return;
  486. }
  487. var defaultName = Environment.UserName;
  488. if (string.IsNullOrWhiteSpace(defaultName) || !ValidUsernameRegex().IsMatch(defaultName))
  489. {
  490. defaultName = "MyJellyfinUser";
  491. }
  492. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  493. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  494. await using (dbContext.ConfigureAwait(false))
  495. {
  496. var newUser = await CreateUserInternalAsync(defaultName, dbContext).ConfigureAwait(false);
  497. newUser.SetPermission(PermissionKind.IsAdministrator, true);
  498. newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
  499. newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
  500. dbContext.Users.Add(newUser);
  501. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  502. _users.Add(newUser.Id, newUser);
  503. }
  504. }
  505. /// <inheritdoc/>
  506. public NameIdPair[] GetAuthenticationProviders()
  507. {
  508. return _authenticationProviders
  509. .Where(provider => provider.IsEnabled)
  510. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  511. .ThenBy(i => i.Name)
  512. .Select(i => new NameIdPair
  513. {
  514. Name = i.Name,
  515. Id = i.GetType().FullName
  516. })
  517. .ToArray();
  518. }
  519. /// <inheritdoc/>
  520. public NameIdPair[] GetPasswordResetProviders()
  521. {
  522. return _passwordResetProviders
  523. .Where(provider => provider.IsEnabled)
  524. .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
  525. .ThenBy(i => i.Name)
  526. .Select(i => new NameIdPair
  527. {
  528. Name = i.Name,
  529. Id = i.GetType().FullName
  530. })
  531. .ToArray();
  532. }
  533. /// <inheritdoc/>
  534. public async Task UpdateConfigurationAsync(Guid userId, UserConfiguration config)
  535. {
  536. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  537. await using (dbContext.ConfigureAwait(false))
  538. {
  539. var user = dbContext.Users
  540. .Include(u => u.Permissions)
  541. .Include(u => u.Preferences)
  542. .Include(u => u.AccessSchedules)
  543. .Include(u => u.ProfileImage)
  544. .FirstOrDefault(u => u.Id.Equals(userId))
  545. ?? throw new ArgumentException("No user exists with given Id!");
  546. user.SubtitleMode = config.SubtitleMode;
  547. user.HidePlayedInLatest = config.HidePlayedInLatest;
  548. user.EnableLocalPassword = config.EnableLocalPassword;
  549. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  550. user.DisplayCollectionsView = config.DisplayCollectionsView;
  551. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  552. user.AudioLanguagePreference = config.AudioLanguagePreference;
  553. user.RememberAudioSelections = config.RememberAudioSelections;
  554. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  555. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  556. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  557. // Only set cast receiver id if it is passed in and it exists in the server config.
  558. if (!string.IsNullOrEmpty(config.CastReceiverId)
  559. && _serverConfigurationManager.Configuration.CastReceiverApplications.Any(c => string.Equals(c.Id, config.CastReceiverId, StringComparison.Ordinal)))
  560. {
  561. user.CastReceiverId = config.CastReceiverId;
  562. }
  563. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  564. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  565. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  566. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  567. dbContext.Update(user);
  568. _users[user.Id] = user;
  569. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  570. }
  571. }
  572. /// <inheritdoc/>
  573. public async Task UpdatePolicyAsync(Guid userId, UserPolicy policy)
  574. {
  575. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  576. await using (dbContext.ConfigureAwait(false))
  577. {
  578. var user = dbContext.Users
  579. .Include(u => u.Permissions)
  580. .Include(u => u.Preferences)
  581. .Include(u => u.AccessSchedules)
  582. .Include(u => u.ProfileImage)
  583. .FirstOrDefault(u => u.Id.Equals(userId))
  584. ?? throw new ArgumentException("No user exists with given Id!");
  585. // The default number of login attempts is 3, but for some god forsaken reason it's sent to the server as "0"
  586. int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
  587. {
  588. -1 => null,
  589. 0 => 3,
  590. _ => policy.LoginAttemptsBeforeLockout
  591. };
  592. user.MaxParentalRatingScore = policy.MaxParentalRating;
  593. user.MaxParentalRatingSubScore = policy.MaxParentalSubRating;
  594. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  595. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  596. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  597. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  598. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  599. user.LoginAttemptsBeforeLockout = maxLoginAttempts;
  600. user.MaxActiveSessions = policy.MaxActiveSessions;
  601. user.SyncPlayAccess = policy.SyncPlayAccess;
  602. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  603. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  604. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  605. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  606. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  607. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  608. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  609. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  610. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  611. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  612. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  613. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  614. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  615. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  616. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  617. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  618. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  619. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  620. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  621. user.SetPermission(PermissionKind.EnableCollectionManagement, policy.EnableCollectionManagement);
  622. user.SetPermission(PermissionKind.EnableSubtitleManagement, policy.EnableSubtitleManagement);
  623. user.SetPermission(PermissionKind.EnableLyricManagement, policy.EnableLyricManagement);
  624. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  625. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  626. user.AccessSchedules.Clear();
  627. foreach (var policyAccessSchedule in policy.AccessSchedules)
  628. {
  629. user.AccessSchedules.Add(policyAccessSchedule);
  630. }
  631. // TODO: fix this at some point
  632. user.SetPreference(PreferenceKind.BlockUnratedItems, policy.BlockUnratedItems ?? Array.Empty<UnratedItem>());
  633. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  634. user.SetPreference(PreferenceKind.AllowedTags, policy.AllowedTags);
  635. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  636. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  637. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  638. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  639. dbContext.Update(user);
  640. _users[user.Id] = user;
  641. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  642. }
  643. }
  644. /// <inheritdoc/>
  645. public async Task ClearProfileImageAsync(User user)
  646. {
  647. if (user.ProfileImage is null)
  648. {
  649. return;
  650. }
  651. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  652. await using (dbContext.ConfigureAwait(false))
  653. {
  654. dbContext.Remove(user.ProfileImage);
  655. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  656. }
  657. user.ProfileImage = null;
  658. _users[user.Id] = user;
  659. }
  660. internal static void ThrowIfInvalidUsername(string name)
  661. {
  662. if (!string.IsNullOrWhiteSpace(name) && ValidUsernameRegex().IsMatch(name))
  663. {
  664. return;
  665. }
  666. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)", nameof(name));
  667. }
  668. private IAuthenticationProvider GetAuthenticationProvider(User user)
  669. {
  670. return GetAuthenticationProviders(user)[0];
  671. }
  672. private IPasswordResetProvider GetPasswordResetProvider(User user)
  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.Update(user);
  781. _users[user.Id] = user;
  782. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  783. }
  784. }
  785. }