UserManager.cs 41 KB

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