UserManager.cs 40 KB

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