UserManager.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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 MediaBrowser.Common;
  14. using MediaBrowser.Common.Extensions;
  15. using MediaBrowser.Common.Net;
  16. using MediaBrowser.Controller.Authentication;
  17. using MediaBrowser.Controller.Configuration;
  18. using MediaBrowser.Controller.Drawing;
  19. using MediaBrowser.Controller.Events;
  20. using MediaBrowser.Controller.Library;
  21. using MediaBrowser.Controller.Net;
  22. using MediaBrowser.Model.Configuration;
  23. using MediaBrowser.Model.Dto;
  24. using MediaBrowser.Model.Users;
  25. using Microsoft.EntityFrameworkCore;
  26. using Microsoft.Extensions.Logging;
  27. namespace Jellyfin.Server.Implementations.Users
  28. {
  29. /// <summary>
  30. /// Manages the creation and retrieval of <see cref="User"/> instances.
  31. /// </summary>
  32. public partial class UserManager : IUserManager
  33. {
  34. private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
  35. private readonly IEventManager _eventManager;
  36. private readonly INetworkManager _networkManager;
  37. private readonly IApplicationHost _appHost;
  38. private readonly IImageProcessor _imageProcessor;
  39. private readonly ILogger<UserManager> _logger;
  40. private readonly IReadOnlyCollection<IPasswordResetProvider> _passwordResetProviders;
  41. private readonly IReadOnlyCollection<IAuthenticationProvider> _authenticationProviders;
  42. private readonly InvalidAuthProvider _invalidAuthProvider;
  43. private readonly DefaultAuthenticationProvider _defaultAuthenticationProvider;
  44. private readonly DefaultPasswordResetProvider _defaultPasswordResetProvider;
  45. private readonly IServerConfigurationManager _serverConfigurationManager;
  46. /// <summary>
  47. /// Initializes a new instance of the <see cref="UserManager"/> class.
  48. /// </summary>
  49. /// <param name="dbProvider">The database provider.</param>
  50. /// <param name="eventManager">The event manager.</param>
  51. /// <param name="networkManager">The network manager.</param>
  52. /// <param name="appHost">The application host.</param>
  53. /// <param name="imageProcessor">The image processor.</param>
  54. /// <param name="logger">The logger.</param>
  55. /// <param name="serverConfigurationManager">The system config manager.</param>
  56. /// <param name="passwordResetProviders">The password reset providers.</param>
  57. /// <param name="authenticationProviders">The authentication providers.</param>
  58. public UserManager(
  59. IDbContextFactory<JellyfinDbContext> dbProvider,
  60. IEventManager eventManager,
  61. INetworkManager networkManager,
  62. IApplicationHost appHost,
  63. IImageProcessor imageProcessor,
  64. ILogger<UserManager> logger,
  65. IServerConfigurationManager serverConfigurationManager,
  66. IEnumerable<IPasswordResetProvider> passwordResetProviders,
  67. IEnumerable<IAuthenticationProvider> authenticationProviders)
  68. {
  69. _dbProvider = dbProvider;
  70. _eventManager = eventManager;
  71. _networkManager = networkManager;
  72. _appHost = appHost;
  73. _imageProcessor = imageProcessor;
  74. _logger = logger;
  75. _serverConfigurationManager = serverConfigurationManager;
  76. _passwordResetProviders = passwordResetProviders.ToList();
  77. _authenticationProviders = authenticationProviders.ToList();
  78. _invalidAuthProvider = _authenticationProviders.OfType<InvalidAuthProvider>().First();
  79. _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
  80. _defaultPasswordResetProvider = _passwordResetProviders.OfType<DefaultPasswordResetProvider>().First();
  81. }
  82. /// <inheritdoc/>
  83. public event EventHandler<GenericEventArgs<User>>? OnUserUpdated;
  84. /// <inheritdoc/>
  85. public IEnumerable<User> Users
  86. {
  87. get
  88. {
  89. using var dbContext = _dbProvider.CreateDbContext();
  90. return GetUsersInternal(dbContext).ToList();
  91. }
  92. }
  93. /// <inheritdoc/>
  94. public IEnumerable<Guid> UsersIds
  95. {
  96. get
  97. {
  98. using var dbContext = _dbProvider.CreateDbContext();
  99. return dbContext.Users.Select(u => u.Id).ToList();
  100. }
  101. }
  102. // This is some regex that matches only on unicode "word" characters, as well as -, _ and @
  103. // In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
  104. // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), periods (.) and spaces ( )
  105. [GeneratedRegex(@"^[\w\ \-'._@]+$")]
  106. private static partial Regex ValidUsernameRegex();
  107. /// <inheritdoc/>
  108. public User? GetUserById(Guid id)
  109. {
  110. if (id.Equals(default))
  111. {
  112. throw new ArgumentException("Guid can't be empty", nameof(id));
  113. }
  114. using var dbContext = _dbProvider.CreateDbContext();
  115. return GetUsersInternal(dbContext).FirstOrDefault(u => u.Id.Equals(id));
  116. }
  117. /// <inheritdoc/>
  118. public User? GetUserByName(string name)
  119. {
  120. if (string.IsNullOrWhiteSpace(name))
  121. {
  122. throw new ArgumentException("Invalid username", nameof(name));
  123. }
  124. using var dbContext = _dbProvider.CreateDbContext();
  125. return GetUsersInternal(dbContext)
  126. .FirstOrDefault(u => string.Equals(u.Username, name));
  127. }
  128. /// <inheritdoc/>
  129. public async Task RenameUser(User user, string newName)
  130. {
  131. ArgumentNullException.ThrowIfNull(user);
  132. ThrowIfInvalidUsername(newName);
  133. if (user.Username.Equals(newName, StringComparison.Ordinal))
  134. {
  135. throw new ArgumentException("The new and old names must be different.");
  136. }
  137. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  138. await using (dbContext.ConfigureAwait(false))
  139. {
  140. if (await dbContext.Users
  141. .AnyAsync(u => u.Username == newName && !u.Id.Equals(user.Id))
  142. .ConfigureAwait(false))
  143. {
  144. throw new ArgumentException(string.Format(
  145. CultureInfo.InvariantCulture,
  146. "A user with the name '{0}' already exists.",
  147. newName));
  148. }
  149. user.Username = newName;
  150. await UpdateUserInternalAsync(dbContext, user).ConfigureAwait(false);
  151. }
  152. var eventArgs = new UserUpdatedEventArgs(user);
  153. await _eventManager.PublishAsync(eventArgs).ConfigureAwait(false);
  154. OnUserUpdated?.Invoke(this, eventArgs);
  155. }
  156. /// <inheritdoc/>
  157. public async Task UpdateUserAsync(User user)
  158. {
  159. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  160. await using (dbContext.ConfigureAwait(false))
  161. {
  162. await UpdateUserInternalAsync(dbContext, user).ConfigureAwait(false);
  163. }
  164. }
  165. internal async Task<User> CreateUserInternalAsync(string name, JellyfinDbContext dbContext)
  166. {
  167. // TODO: Remove after user item data is migrated.
  168. var max = await dbContext.Users.AsQueryable().AnyAsync().ConfigureAwait(false)
  169. ? await dbContext.Users.AsQueryable().Select(u => u.InternalId).MaxAsync().ConfigureAwait(false)
  170. : 0;
  171. var user = new User(
  172. name,
  173. _defaultAuthenticationProvider.GetType().FullName!,
  174. _defaultPasswordResetProvider.GetType().FullName!)
  175. {
  176. InternalId = max + 1
  177. };
  178. user.AddDefaultPermissions();
  179. user.AddDefaultPreferences();
  180. return user;
  181. }
  182. /// <inheritdoc/>
  183. public async Task<User> CreateUserAsync(string name)
  184. {
  185. ThrowIfInvalidUsername(name);
  186. if (Users.Any(u => u.Username.Equals(name, StringComparison.OrdinalIgnoreCase)))
  187. {
  188. throw new ArgumentException(string.Format(
  189. CultureInfo.InvariantCulture,
  190. "A user with the name '{0}' already exists.",
  191. name));
  192. }
  193. User newUser;
  194. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  195. await using (dbContext.ConfigureAwait(false))
  196. {
  197. newUser = await CreateUserInternalAsync(name, dbContext).ConfigureAwait(false);
  198. dbContext.Users.Add(newUser);
  199. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  200. }
  201. await _eventManager.PublishAsync(new UserCreatedEventArgs(newUser)).ConfigureAwait(false);
  202. return newUser;
  203. }
  204. /// <inheritdoc/>
  205. public async Task DeleteUserAsync(Guid userId)
  206. {
  207. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  208. await using (dbContext.ConfigureAwait(false))
  209. {
  210. var user = await dbContext.Users
  211. .AsSingleQuery()
  212. .Include(u => u.Permissions)
  213. .FirstOrDefaultAsync(u => u.Id.Equals(userId))
  214. .ConfigureAwait(false);
  215. if (user is null)
  216. {
  217. throw new ResourceNotFoundException(nameof(userId));
  218. }
  219. if (await dbContext.Users.CountAsync().ConfigureAwait(false) == 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. && await dbContext.Users
  228. .CountAsync(u => u.Permissions.Any(p => p.Kind == PermissionKind.IsAdministrator && p.Value))
  229. .ConfigureAwait(false) == 1)
  230. {
  231. throw new ArgumentException(
  232. string.Format(
  233. CultureInfo.InvariantCulture,
  234. "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
  235. user.Username),
  236. nameof(userId));
  237. }
  238. dbContext.Users.Remove(user);
  239. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  240. await _eventManager.PublishAsync(new UserDeletedEventArgs(user)).ConfigureAwait(false);
  241. }
  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 passwordSha1,
  350. string remoteEndPoint,
  351. bool isUserSession)
  352. {
  353. if (string.IsNullOrWhiteSpace(username))
  354. {
  355. _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
  356. throw new ArgumentNullException(nameof(username));
  357. }
  358. var user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  359. var authResult = await AuthenticateLocalUser(username, password, user)
  360. .ConfigureAwait(false);
  361. var authenticationProvider = authResult.AuthenticationProvider;
  362. var success = authResult.Success;
  363. if (user is null)
  364. {
  365. string updatedUsername = authResult.Username;
  366. if (success
  367. && authenticationProvider is not null
  368. && authenticationProvider is not DefaultAuthenticationProvider)
  369. {
  370. // Trust the username returned by the authentication provider
  371. username = updatedUsername;
  372. // Search the database for the user again
  373. // the authentication provider might have created it
  374. user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  375. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy && user is not null)
  376. {
  377. await UpdatePolicyAsync(user.Id, hasNewUserPolicy.GetNewUserPolicy()).ConfigureAwait(false);
  378. }
  379. }
  380. }
  381. if (success && user is not null && authenticationProvider is not null)
  382. {
  383. var providerId = authenticationProvider.GetType().FullName;
  384. if (providerId is not null && !string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  385. {
  386. user.AuthenticationProviderId = providerId;
  387. await UpdateUserAsync(user).ConfigureAwait(false);
  388. }
  389. }
  390. if (user is null)
  391. {
  392. _logger.LogInformation(
  393. "Authentication request for {UserName} has been denied (IP: {IP}).",
  394. username,
  395. remoteEndPoint);
  396. throw new AuthenticationException("Invalid username or password entered.");
  397. }
  398. if (user.HasPermission(PermissionKind.IsDisabled))
  399. {
  400. _logger.LogInformation(
  401. "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
  402. username,
  403. remoteEndPoint);
  404. throw new SecurityException(
  405. $"The {user.Username} account is currently disabled. Please consult with your administrator.");
  406. }
  407. if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
  408. !_networkManager.IsInLocalNetwork(remoteEndPoint))
  409. {
  410. _logger.LogInformation(
  411. "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
  412. username,
  413. remoteEndPoint);
  414. throw new SecurityException("Forbidden.");
  415. }
  416. if (!user.IsParentalScheduleAllowed())
  417. {
  418. _logger.LogInformation(
  419. "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
  420. username,
  421. remoteEndPoint);
  422. throw new SecurityException("User is not allowed access at this time.");
  423. }
  424. // Update LastActivityDate and LastLoginDate, then save
  425. if (success)
  426. {
  427. if (isUserSession)
  428. {
  429. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  430. }
  431. user.InvalidLoginAttemptCount = 0;
  432. await UpdateUserAsync(user).ConfigureAwait(false);
  433. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
  434. }
  435. else
  436. {
  437. await IncrementInvalidLoginAttemptCount(user).ConfigureAwait(false);
  438. _logger.LogInformation(
  439. "Authentication request for {UserName} has been denied (IP: {IP}).",
  440. user.Username,
  441. remoteEndPoint);
  442. }
  443. return success ? user : null;
  444. }
  445. /// <inheritdoc/>
  446. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  447. {
  448. var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
  449. if (user is not null && isInNetwork)
  450. {
  451. var passwordResetProvider = GetPasswordResetProvider(user);
  452. var result = await passwordResetProvider
  453. .StartForgotPasswordProcess(user, isInNetwork)
  454. .ConfigureAwait(false);
  455. await UpdateUserAsync(user).ConfigureAwait(false);
  456. return result;
  457. }
  458. return new ForgotPasswordResult
  459. {
  460. Action = ForgotPasswordAction.InNetworkRequired,
  461. PinFile = string.Empty
  462. };
  463. }
  464. /// <inheritdoc/>
  465. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  466. {
  467. foreach (var provider in _passwordResetProviders)
  468. {
  469. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  470. if (result.Success)
  471. {
  472. return result;
  473. }
  474. }
  475. return new PinRedeemResult();
  476. }
  477. /// <inheritdoc />
  478. public async Task InitializeAsync()
  479. {
  480. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  481. await using (dbContext.ConfigureAwait(false))
  482. {
  483. // TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
  484. if (await dbContext.Users.AnyAsync().ConfigureAwait(false))
  485. {
  486. return;
  487. }
  488. var defaultName = Environment.UserName;
  489. if (string.IsNullOrWhiteSpace(defaultName) || !ValidUsernameRegex().IsMatch(defaultName))
  490. {
  491. defaultName = "MyJellyfinUser";
  492. }
  493. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  494. var newUser = await CreateUserInternalAsync(defaultName, dbContext).ConfigureAwait(false);
  495. newUser.SetPermission(PermissionKind.IsAdministrator, true);
  496. newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
  497. newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
  498. dbContext.Users.Add(newUser);
  499. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  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 = await GetUsersInternal(dbContext)
  537. .FirstOrDefaultAsync(u => u.Id.Equals(userId))
  538. .ConfigureAwait(false)
  539. ?? throw new ArgumentException("No user exists with given Id!");
  540. user.SubtitleMode = config.SubtitleMode;
  541. user.HidePlayedInLatest = config.HidePlayedInLatest;
  542. user.EnableLocalPassword = config.EnableLocalPassword;
  543. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  544. user.DisplayCollectionsView = config.DisplayCollectionsView;
  545. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  546. user.AudioLanguagePreference = config.AudioLanguagePreference;
  547. user.RememberAudioSelections = config.RememberAudioSelections;
  548. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  549. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  550. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  551. // Only set cast receiver id if it is passed in and it exists in the server config.
  552. if (!string.IsNullOrEmpty(config.CastReceiverId)
  553. && _serverConfigurationManager.Configuration.CastReceiverApplications.Any(c => string.Equals(c.Id, config.CastReceiverId, StringComparison.Ordinal)))
  554. {
  555. user.CastReceiverId = config.CastReceiverId;
  556. }
  557. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  558. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  559. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  560. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  561. dbContext.Update(user);
  562. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  563. }
  564. }
  565. /// <inheritdoc/>
  566. public async Task UpdatePolicyAsync(Guid userId, UserPolicy policy)
  567. {
  568. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  569. await using (dbContext.ConfigureAwait(false))
  570. {
  571. var user = await GetUsersInternal(dbContext)
  572. .FirstOrDefaultAsync(u => u.Id.Equals(userId))
  573. .ConfigureAwait(false)
  574. ?? throw new ArgumentException("No user exists with given Id!");
  575. // The default number of login attempts is 3, but for some god forsaken reason it's sent to the server as "0"
  576. int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
  577. {
  578. -1 => null,
  579. 0 => 3,
  580. _ => policy.LoginAttemptsBeforeLockout
  581. };
  582. user.MaxParentalAgeRating = policy.MaxParentalRating;
  583. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  584. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  585. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  586. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  587. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  588. user.LoginAttemptsBeforeLockout = maxLoginAttempts;
  589. user.MaxActiveSessions = policy.MaxActiveSessions;
  590. user.SyncPlayAccess = policy.SyncPlayAccess;
  591. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  592. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  593. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  594. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  595. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  596. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  597. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  598. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  599. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  600. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  601. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  602. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  603. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  604. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  605. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  606. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  607. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  608. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  609. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  610. user.SetPermission(PermissionKind.EnableCollectionManagement, policy.EnableCollectionManagement);
  611. user.SetPermission(PermissionKind.EnableSubtitleManagement, policy.EnableSubtitleManagement);
  612. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  613. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  614. user.AccessSchedules.Clear();
  615. foreach (var policyAccessSchedule in policy.AccessSchedules)
  616. {
  617. user.AccessSchedules.Add(policyAccessSchedule);
  618. }
  619. // TODO: fix this at some point
  620. user.SetPreference(PreferenceKind.BlockUnratedItems, policy.BlockUnratedItems ?? Array.Empty<UnratedItem>());
  621. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  622. user.SetPreference(PreferenceKind.AllowedTags, policy.AllowedTags);
  623. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  624. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  625. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  626. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  627. dbContext.Update(user);
  628. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  629. }
  630. }
  631. /// <inheritdoc/>
  632. public async Task ClearProfileImageAsync(User user)
  633. {
  634. if (user.ProfileImage is null)
  635. {
  636. return;
  637. }
  638. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  639. await using (dbContext.ConfigureAwait(false))
  640. {
  641. dbContext.Remove(user.ProfileImage);
  642. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  643. }
  644. user.ProfileImage = null;
  645. }
  646. internal static void ThrowIfInvalidUsername(string name)
  647. {
  648. if (!string.IsNullOrWhiteSpace(name) && ValidUsernameRegex().IsMatch(name))
  649. {
  650. return;
  651. }
  652. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)", nameof(name));
  653. }
  654. private IAuthenticationProvider GetAuthenticationProvider(User user)
  655. {
  656. return GetAuthenticationProviders(user)[0];
  657. }
  658. private IPasswordResetProvider GetPasswordResetProvider(User user)
  659. {
  660. return GetPasswordResetProviders(user)[0];
  661. }
  662. private List<IAuthenticationProvider> GetAuthenticationProviders(User? user)
  663. {
  664. var authenticationProviderId = user?.AuthenticationProviderId;
  665. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();
  666. if (!string.IsNullOrEmpty(authenticationProviderId))
  667. {
  668. providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
  669. }
  670. if (providers.Count == 0)
  671. {
  672. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  673. _logger.LogWarning(
  674. "User {Username} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
  675. user?.Username,
  676. user?.AuthenticationProviderId);
  677. providers = new List<IAuthenticationProvider>
  678. {
  679. _invalidAuthProvider
  680. };
  681. }
  682. return providers;
  683. }
  684. private IPasswordResetProvider[] GetPasswordResetProviders(User user)
  685. {
  686. var passwordResetProviderId = user.PasswordResetProviderId;
  687. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  688. if (!string.IsNullOrEmpty(passwordResetProviderId))
  689. {
  690. providers = providers.Where(i =>
  691. string.Equals(passwordResetProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase))
  692. .ToArray();
  693. }
  694. if (providers.Length == 0)
  695. {
  696. providers = new IPasswordResetProvider[]
  697. {
  698. _defaultPasswordResetProvider
  699. };
  700. }
  701. return providers;
  702. }
  703. private async Task<(IAuthenticationProvider? AuthenticationProvider, string Username, bool Success)> AuthenticateLocalUser(
  704. string username,
  705. string password,
  706. User? user)
  707. {
  708. bool success = false;
  709. IAuthenticationProvider? authenticationProvider = null;
  710. foreach (var provider in GetAuthenticationProviders(user))
  711. {
  712. var providerAuthResult =
  713. await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  714. var updatedUsername = providerAuthResult.Username;
  715. success = providerAuthResult.Success;
  716. if (success)
  717. {
  718. authenticationProvider = provider;
  719. username = updatedUsername;
  720. break;
  721. }
  722. }
  723. return (authenticationProvider, username, success);
  724. }
  725. private async Task<(string Username, bool Success)> AuthenticateWithProvider(
  726. IAuthenticationProvider provider,
  727. string username,
  728. string password,
  729. User? resolvedUser)
  730. {
  731. try
  732. {
  733. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  734. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  735. : await provider.Authenticate(username, password).ConfigureAwait(false);
  736. if (authenticationResult.Username != username)
  737. {
  738. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  739. username = authenticationResult.Username;
  740. }
  741. return (username, true);
  742. }
  743. catch (AuthenticationException ex)
  744. {
  745. _logger.LogDebug(ex, "Error authenticating with provider {Provider}", provider.Name);
  746. return (username, false);
  747. }
  748. }
  749. private async Task IncrementInvalidLoginAttemptCount(User user)
  750. {
  751. user.InvalidLoginAttemptCount++;
  752. int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
  753. if (maxInvalidLogins.HasValue && user.InvalidLoginAttemptCount >= maxInvalidLogins)
  754. {
  755. user.SetPermission(PermissionKind.IsDisabled, true);
  756. await _eventManager.PublishAsync(new UserLockedOutEventArgs(user)).ConfigureAwait(false);
  757. _logger.LogWarning(
  758. "Disabling user {Username} due to {Attempts} unsuccessful login attempts.",
  759. user.Username,
  760. user.InvalidLoginAttemptCount);
  761. }
  762. await UpdateUserAsync(user).ConfigureAwait(false);
  763. }
  764. private async Task UpdateUserInternalAsync(JellyfinDbContext dbContext, User user)
  765. {
  766. dbContext.Users.Update(user);
  767. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  768. }
  769. private IQueryable<User> GetUsersInternal(JellyfinDbContext dbContext)
  770. => dbContext.Users
  771. .AsSplitQuery()
  772. .Include(user => user.Permissions)
  773. .Include(user => user.Preferences)
  774. .Include(user => user.AccessSchedules)
  775. .Include(user => user.ProfileImage);
  776. }
  777. }