UserManager.cs 41 KB

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