UserManager.cs 41 KB

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