UserManager.cs 42 KB

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