UserManager.cs 41 KB

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