UserManager.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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. AccessSchedules = user.AccessSchedules.ToArray(),
  319. BlockedTags = user.GetPreference(PreferenceKind.BlockedTags),
  320. AllowedTags = user.GetPreference(PreferenceKind.AllowedTags),
  321. EnabledChannels = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledChannels),
  322. EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices),
  323. EnabledFolders = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders),
  324. EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders),
  325. SyncPlayAccess = user.SyncPlayAccess,
  326. BlockedChannels = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedChannels),
  327. BlockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders),
  328. BlockUnratedItems = user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems)
  329. }
  330. };
  331. }
  332. /// <inheritdoc/>
  333. public async Task<User?> AuthenticateUser(
  334. string username,
  335. string password,
  336. string passwordSha1,
  337. string remoteEndPoint,
  338. bool isUserSession)
  339. {
  340. if (string.IsNullOrWhiteSpace(username))
  341. {
  342. _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
  343. throw new ArgumentNullException(nameof(username));
  344. }
  345. var user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  346. var authResult = await AuthenticateLocalUser(username, password, user)
  347. .ConfigureAwait(false);
  348. var authenticationProvider = authResult.AuthenticationProvider;
  349. var success = authResult.Success;
  350. if (user is null)
  351. {
  352. string updatedUsername = authResult.Username;
  353. if (success
  354. && authenticationProvider is not null
  355. && authenticationProvider is not DefaultAuthenticationProvider)
  356. {
  357. // Trust the username returned by the authentication provider
  358. username = updatedUsername;
  359. // Search the database for the user again
  360. // the authentication provider might have created it
  361. user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  362. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy && user is not null)
  363. {
  364. await UpdatePolicyAsync(user.Id, hasNewUserPolicy.GetNewUserPolicy()).ConfigureAwait(false);
  365. }
  366. }
  367. }
  368. if (success && user is not null && authenticationProvider is not null)
  369. {
  370. var providerId = authenticationProvider.GetType().FullName;
  371. if (providerId is not null && !string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  372. {
  373. user.AuthenticationProviderId = providerId;
  374. await UpdateUserAsync(user).ConfigureAwait(false);
  375. }
  376. }
  377. if (user is null)
  378. {
  379. _logger.LogInformation(
  380. "Authentication request for {UserName} has been denied (IP: {IP}).",
  381. username,
  382. remoteEndPoint);
  383. throw new AuthenticationException("Invalid username or password entered.");
  384. }
  385. if (user.HasPermission(PermissionKind.IsDisabled))
  386. {
  387. _logger.LogInformation(
  388. "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
  389. username,
  390. remoteEndPoint);
  391. throw new SecurityException(
  392. $"The {user.Username} account is currently disabled. Please consult with your administrator.");
  393. }
  394. if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
  395. !_networkManager.IsInLocalNetwork(remoteEndPoint))
  396. {
  397. _logger.LogInformation(
  398. "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
  399. username,
  400. remoteEndPoint);
  401. throw new SecurityException("Forbidden.");
  402. }
  403. if (!user.IsParentalScheduleAllowed())
  404. {
  405. _logger.LogInformation(
  406. "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
  407. username,
  408. remoteEndPoint);
  409. throw new SecurityException("User is not allowed access at this time.");
  410. }
  411. // Update LastActivityDate and LastLoginDate, then save
  412. if (success)
  413. {
  414. if (isUserSession)
  415. {
  416. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  417. }
  418. user.InvalidLoginAttemptCount = 0;
  419. await UpdateUserAsync(user).ConfigureAwait(false);
  420. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
  421. }
  422. else
  423. {
  424. await IncrementInvalidLoginAttemptCount(user).ConfigureAwait(false);
  425. _logger.LogInformation(
  426. "Authentication request for {UserName} has been denied (IP: {IP}).",
  427. user.Username,
  428. remoteEndPoint);
  429. }
  430. return success ? user : null;
  431. }
  432. /// <inheritdoc/>
  433. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  434. {
  435. var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
  436. if (user is not null && isInNetwork)
  437. {
  438. var passwordResetProvider = GetPasswordResetProvider(user);
  439. var result = await passwordResetProvider
  440. .StartForgotPasswordProcess(user, isInNetwork)
  441. .ConfigureAwait(false);
  442. await UpdateUserAsync(user).ConfigureAwait(false);
  443. return result;
  444. }
  445. return new ForgotPasswordResult
  446. {
  447. Action = ForgotPasswordAction.InNetworkRequired,
  448. PinFile = string.Empty
  449. };
  450. }
  451. /// <inheritdoc/>
  452. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  453. {
  454. foreach (var provider in _passwordResetProviders)
  455. {
  456. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  457. if (result.Success)
  458. {
  459. return result;
  460. }
  461. }
  462. return new PinRedeemResult();
  463. }
  464. /// <inheritdoc />
  465. public async Task InitializeAsync()
  466. {
  467. // TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
  468. if (_users.Any())
  469. {
  470. return;
  471. }
  472. var defaultName = Environment.UserName;
  473. if (string.IsNullOrWhiteSpace(defaultName) || !ValidUsernameRegex().IsMatch(defaultName))
  474. {
  475. defaultName = "MyJellyfinUser";
  476. }
  477. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  478. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  479. await using (dbContext.ConfigureAwait(false))
  480. {
  481. var newUser = await CreateUserInternalAsync(defaultName, dbContext).ConfigureAwait(false);
  482. newUser.SetPermission(PermissionKind.IsAdministrator, true);
  483. newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
  484. newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
  485. dbContext.Users.Add(newUser);
  486. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  487. }
  488. }
  489. /// <inheritdoc/>
  490. public NameIdPair[] GetAuthenticationProviders()
  491. {
  492. return _authenticationProviders
  493. .Where(provider => provider.IsEnabled)
  494. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  495. .ThenBy(i => i.Name)
  496. .Select(i => new NameIdPair
  497. {
  498. Name = i.Name,
  499. Id = i.GetType().FullName
  500. })
  501. .ToArray();
  502. }
  503. /// <inheritdoc/>
  504. public NameIdPair[] GetPasswordResetProviders()
  505. {
  506. return _passwordResetProviders
  507. .Where(provider => provider.IsEnabled)
  508. .OrderBy(i => i is DefaultPasswordResetProvider ? 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 async Task UpdateConfigurationAsync(Guid userId, UserConfiguration config)
  519. {
  520. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  521. await using (dbContext.ConfigureAwait(false))
  522. {
  523. var user = dbContext.Users
  524. .Include(u => u.Permissions)
  525. .Include(u => u.Preferences)
  526. .Include(u => u.AccessSchedules)
  527. .Include(u => u.ProfileImage)
  528. .FirstOrDefault(u => u.Id.Equals(userId))
  529. ?? throw new ArgumentException("No user exists with given Id!");
  530. user.SubtitleMode = config.SubtitleMode;
  531. user.HidePlayedInLatest = config.HidePlayedInLatest;
  532. user.EnableLocalPassword = config.EnableLocalPassword;
  533. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  534. user.DisplayCollectionsView = config.DisplayCollectionsView;
  535. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  536. user.AudioLanguagePreference = config.AudioLanguagePreference;
  537. user.RememberAudioSelections = config.RememberAudioSelections;
  538. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  539. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  540. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  541. // Only set cast receiver id if it is passed in and it exists in the server config.
  542. if (!string.IsNullOrEmpty(config.CastReceiverId)
  543. && _serverConfigurationManager.Configuration.CastReceiverApplications.Any(c => string.Equals(c.Id, config.CastReceiverId, StringComparison.Ordinal)))
  544. {
  545. user.CastReceiverId = config.CastReceiverId;
  546. }
  547. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  548. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  549. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  550. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  551. dbContext.Update(user);
  552. _users[user.Id] = user;
  553. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  554. }
  555. }
  556. /// <inheritdoc/>
  557. public async Task UpdatePolicyAsync(Guid userId, UserPolicy policy)
  558. {
  559. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  560. await using (dbContext.ConfigureAwait(false))
  561. {
  562. var user = dbContext.Users
  563. .Include(u => u.Permissions)
  564. .Include(u => u.Preferences)
  565. .Include(u => u.AccessSchedules)
  566. .Include(u => u.ProfileImage)
  567. .FirstOrDefault(u => u.Id.Equals(userId))
  568. ?? throw new ArgumentException("No user exists with given Id!");
  569. // The default number of login attempts is 3, but for some god forsaken reason it's sent to the server as "0"
  570. int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
  571. {
  572. -1 => null,
  573. 0 => 3,
  574. _ => policy.LoginAttemptsBeforeLockout
  575. };
  576. user.MaxParentalAgeRating = policy.MaxParentalRating;
  577. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  578. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  579. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  580. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  581. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  582. user.LoginAttemptsBeforeLockout = maxLoginAttempts;
  583. user.MaxActiveSessions = policy.MaxActiveSessions;
  584. user.SyncPlayAccess = policy.SyncPlayAccess;
  585. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  586. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  587. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  588. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  589. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  590. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  591. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  592. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  593. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  594. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  595. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  596. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  597. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  598. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  599. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  600. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  601. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  602. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  603. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  604. user.SetPermission(PermissionKind.EnableCollectionManagement, policy.EnableCollectionManagement);
  605. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  606. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  607. user.AccessSchedules.Clear();
  608. foreach (var policyAccessSchedule in policy.AccessSchedules)
  609. {
  610. user.AccessSchedules.Add(policyAccessSchedule);
  611. }
  612. // TODO: fix this at some point
  613. user.SetPreference(PreferenceKind.BlockUnratedItems, policy.BlockUnratedItems ?? Array.Empty<UnratedItem>());
  614. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  615. user.SetPreference(PreferenceKind.AllowedTags, policy.AllowedTags);
  616. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  617. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  618. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  619. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  620. dbContext.Update(user);
  621. _users[user.Id] = user;
  622. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  623. }
  624. }
  625. /// <inheritdoc/>
  626. public async Task ClearProfileImageAsync(User user)
  627. {
  628. if (user.ProfileImage is null)
  629. {
  630. return;
  631. }
  632. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  633. await using (dbContext.ConfigureAwait(false))
  634. {
  635. dbContext.Remove(user.ProfileImage);
  636. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  637. }
  638. user.ProfileImage = null;
  639. _users[user.Id] = user;
  640. }
  641. internal static void ThrowIfInvalidUsername(string name)
  642. {
  643. if (!string.IsNullOrWhiteSpace(name) && ValidUsernameRegex().IsMatch(name))
  644. {
  645. return;
  646. }
  647. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)", nameof(name));
  648. }
  649. private IAuthenticationProvider GetAuthenticationProvider(User user)
  650. {
  651. return GetAuthenticationProviders(user)[0];
  652. }
  653. private IPasswordResetProvider GetPasswordResetProvider(User user)
  654. {
  655. return GetPasswordResetProviders(user)[0];
  656. }
  657. private IList<IAuthenticationProvider> GetAuthenticationProviders(User? user)
  658. {
  659. var authenticationProviderId = user?.AuthenticationProviderId;
  660. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();
  661. if (!string.IsNullOrEmpty(authenticationProviderId))
  662. {
  663. providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
  664. }
  665. if (providers.Count == 0)
  666. {
  667. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  668. _logger.LogWarning(
  669. "User {Username} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
  670. user?.Username,
  671. user?.AuthenticationProviderId);
  672. providers = new List<IAuthenticationProvider>
  673. {
  674. _invalidAuthProvider
  675. };
  676. }
  677. return providers;
  678. }
  679. private IList<IPasswordResetProvider> GetPasswordResetProviders(User user)
  680. {
  681. var passwordResetProviderId = user.PasswordResetProviderId;
  682. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  683. if (!string.IsNullOrEmpty(passwordResetProviderId))
  684. {
  685. providers = providers.Where(i =>
  686. string.Equals(passwordResetProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase))
  687. .ToArray();
  688. }
  689. if (providers.Length == 0)
  690. {
  691. providers = new IPasswordResetProvider[]
  692. {
  693. _defaultPasswordResetProvider
  694. };
  695. }
  696. return providers;
  697. }
  698. private async Task<(IAuthenticationProvider? AuthenticationProvider, string Username, bool Success)> AuthenticateLocalUser(
  699. string username,
  700. string password,
  701. User? user)
  702. {
  703. bool success = false;
  704. IAuthenticationProvider? authenticationProvider = null;
  705. foreach (var provider in GetAuthenticationProviders(user))
  706. {
  707. var providerAuthResult =
  708. await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  709. var updatedUsername = providerAuthResult.Username;
  710. success = providerAuthResult.Success;
  711. if (success)
  712. {
  713. authenticationProvider = provider;
  714. username = updatedUsername;
  715. break;
  716. }
  717. }
  718. return (authenticationProvider, username, success);
  719. }
  720. private async Task<(string Username, bool Success)> AuthenticateWithProvider(
  721. IAuthenticationProvider provider,
  722. string username,
  723. string password,
  724. User? resolvedUser)
  725. {
  726. try
  727. {
  728. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  729. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  730. : await provider.Authenticate(username, password).ConfigureAwait(false);
  731. if (authenticationResult.Username != username)
  732. {
  733. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  734. username = authenticationResult.Username;
  735. }
  736. return (username, true);
  737. }
  738. catch (AuthenticationException ex)
  739. {
  740. _logger.LogDebug(ex, "Error authenticating with provider {Provider}", provider.Name);
  741. return (username, false);
  742. }
  743. }
  744. private async Task IncrementInvalidLoginAttemptCount(User user)
  745. {
  746. user.InvalidLoginAttemptCount++;
  747. int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
  748. if (maxInvalidLogins.HasValue && user.InvalidLoginAttemptCount >= maxInvalidLogins)
  749. {
  750. user.SetPermission(PermissionKind.IsDisabled, true);
  751. await _eventManager.PublishAsync(new UserLockedOutEventArgs(user)).ConfigureAwait(false);
  752. _logger.LogWarning(
  753. "Disabling user {Username} due to {Attempts} unsuccessful login attempts.",
  754. user.Username,
  755. user.InvalidLoginAttemptCount);
  756. }
  757. await UpdateUserAsync(user).ConfigureAwait(false);
  758. }
  759. private async Task UpdateUserInternalAsync(JellyfinDbContext dbContext, User user)
  760. {
  761. dbContext.Users.Update(user);
  762. _users[user.Id] = user;
  763. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  764. }
  765. }
  766. }