UserManager.cs 40 KB

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