UserManager.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  241. await UpdateUserAsync(user).ConfigureAwait(false);
  242. await _eventManager.PublishAsync(new UserPasswordChangedEventArgs(user)).ConfigureAwait(false);
  243. }
  244. /// <inheritdoc/>
  245. public async Task ChangeEasyPassword(User user, string newPassword, string? newPasswordSha1)
  246. {
  247. if (newPassword is not null)
  248. {
  249. newPasswordSha1 = _cryptoProvider.CreatePasswordHash(newPassword).ToString();
  250. }
  251. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  252. {
  253. throw new ArgumentNullException(nameof(newPasswordSha1));
  254. }
  255. user.EasyPassword = newPasswordSha1;
  256. await UpdateUserAsync(user).ConfigureAwait(false);
  257. await _eventManager.PublishAsync(new UserPasswordChangedEventArgs(user)).ConfigureAwait(false);
  258. }
  259. /// <inheritdoc/>
  260. public UserDto GetUserDto(User user, string? remoteEndPoint = null)
  261. {
  262. var hasPassword = GetAuthenticationProvider(user).HasPassword(user);
  263. return new UserDto
  264. {
  265. Name = user.Username,
  266. Id = user.Id,
  267. ServerId = _appHost.SystemId,
  268. HasPassword = hasPassword,
  269. HasConfiguredPassword = hasPassword,
  270. HasConfiguredEasyPassword = !string.IsNullOrEmpty(user.EasyPassword),
  271. EnableAutoLogin = user.EnableAutoLogin,
  272. LastLoginDate = user.LastLoginDate,
  273. LastActivityDate = user.LastActivityDate,
  274. PrimaryImageTag = user.ProfileImage is not null ? _imageProcessor.GetImageCacheTag(user) : null,
  275. Configuration = new UserConfiguration
  276. {
  277. SubtitleMode = user.SubtitleMode,
  278. HidePlayedInLatest = user.HidePlayedInLatest,
  279. EnableLocalPassword = user.EnableLocalPassword,
  280. PlayDefaultAudioTrack = user.PlayDefaultAudioTrack,
  281. DisplayCollectionsView = user.DisplayCollectionsView,
  282. DisplayMissingEpisodes = user.DisplayMissingEpisodes,
  283. AudioLanguagePreference = user.AudioLanguagePreference,
  284. RememberAudioSelections = user.RememberAudioSelections,
  285. EnableNextEpisodeAutoPlay = user.EnableNextEpisodeAutoPlay,
  286. RememberSubtitleSelections = user.RememberSubtitleSelections,
  287. SubtitleLanguagePreference = user.SubtitleLanguagePreference ?? string.Empty,
  288. OrderedViews = user.GetPreferenceValues<Guid>(PreferenceKind.OrderedViews),
  289. GroupedFolders = user.GetPreferenceValues<Guid>(PreferenceKind.GroupedFolders),
  290. MyMediaExcludes = user.GetPreferenceValues<Guid>(PreferenceKind.MyMediaExcludes),
  291. LatestItemsExcludes = user.GetPreferenceValues<Guid>(PreferenceKind.LatestItemExcludes)
  292. },
  293. Policy = new UserPolicy
  294. {
  295. MaxParentalRating = user.MaxParentalAgeRating,
  296. EnableUserPreferenceAccess = user.EnableUserPreferenceAccess,
  297. RemoteClientBitrateLimit = user.RemoteClientBitrateLimit ?? 0,
  298. AuthenticationProviderId = user.AuthenticationProviderId,
  299. PasswordResetProviderId = user.PasswordResetProviderId,
  300. InvalidLoginAttemptCount = user.InvalidLoginAttemptCount,
  301. LoginAttemptsBeforeLockout = user.LoginAttemptsBeforeLockout ?? -1,
  302. MaxActiveSessions = user.MaxActiveSessions,
  303. IsAdministrator = user.HasPermission(PermissionKind.IsAdministrator),
  304. IsHidden = user.HasPermission(PermissionKind.IsHidden),
  305. IsDisabled = user.HasPermission(PermissionKind.IsDisabled),
  306. EnableSharedDeviceControl = user.HasPermission(PermissionKind.EnableSharedDeviceControl),
  307. EnableRemoteAccess = user.HasPermission(PermissionKind.EnableRemoteAccess),
  308. EnableLiveTvManagement = user.HasPermission(PermissionKind.EnableLiveTvManagement),
  309. EnableLiveTvAccess = user.HasPermission(PermissionKind.EnableLiveTvAccess),
  310. EnableMediaPlayback = user.HasPermission(PermissionKind.EnableMediaPlayback),
  311. EnableAudioPlaybackTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding),
  312. EnableVideoPlaybackTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding),
  313. EnableContentDeletion = user.HasPermission(PermissionKind.EnableContentDeletion),
  314. EnableContentDownloading = user.HasPermission(PermissionKind.EnableContentDownloading),
  315. EnableSyncTranscoding = user.HasPermission(PermissionKind.EnableSyncTranscoding),
  316. EnableMediaConversion = user.HasPermission(PermissionKind.EnableMediaConversion),
  317. EnableAllChannels = user.HasPermission(PermissionKind.EnableAllChannels),
  318. EnableAllDevices = user.HasPermission(PermissionKind.EnableAllDevices),
  319. EnableAllFolders = user.HasPermission(PermissionKind.EnableAllFolders),
  320. EnableRemoteControlOfOtherUsers = user.HasPermission(PermissionKind.EnableRemoteControlOfOtherUsers),
  321. EnablePlaybackRemuxing = user.HasPermission(PermissionKind.EnablePlaybackRemuxing),
  322. ForceRemoteSourceTranscoding = user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding),
  323. EnablePublicSharing = user.HasPermission(PermissionKind.EnablePublicSharing),
  324. EnableCollectionManagement = user.HasPermission(PermissionKind.EnableCollectionManagement),
  325. 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 passwordSha1,
  344. string remoteEndPoint,
  345. bool isUserSession)
  346. {
  347. if (string.IsNullOrWhiteSpace(username))
  348. {
  349. _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
  350. throw new ArgumentNullException(nameof(username));
  351. }
  352. var user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  353. var authResult = await AuthenticateLocalUser(username, password, user, remoteEndPoint)
  354. .ConfigureAwait(false);
  355. var authenticationProvider = authResult.AuthenticationProvider;
  356. var success = authResult.Success;
  357. if (user is null)
  358. {
  359. string updatedUsername = authResult.Username;
  360. if (success
  361. && authenticationProvider is not null
  362. && authenticationProvider is not DefaultAuthenticationProvider)
  363. {
  364. // Trust the username returned by the authentication provider
  365. username = updatedUsername;
  366. // Search the database for the user again
  367. // the authentication provider might have created it
  368. user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  369. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy && user is not null)
  370. {
  371. await UpdatePolicyAsync(user.Id, hasNewUserPolicy.GetNewUserPolicy()).ConfigureAwait(false);
  372. }
  373. }
  374. }
  375. if (success && user is not null && authenticationProvider is not null)
  376. {
  377. var providerId = authenticationProvider.GetType().FullName;
  378. if (providerId is not null && !string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  379. {
  380. user.AuthenticationProviderId = providerId;
  381. await UpdateUserAsync(user).ConfigureAwait(false);
  382. }
  383. }
  384. if (user is null)
  385. {
  386. _logger.LogInformation(
  387. "Authentication request for {UserName} has been denied (IP: {IP}).",
  388. username,
  389. remoteEndPoint);
  390. throw new AuthenticationException("Invalid username or password entered.");
  391. }
  392. if (user.HasPermission(PermissionKind.IsDisabled))
  393. {
  394. _logger.LogInformation(
  395. "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
  396. username,
  397. remoteEndPoint);
  398. throw new SecurityException(
  399. $"The {user.Username} account is currently disabled. Please consult with your administrator.");
  400. }
  401. if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
  402. !_networkManager.IsInLocalNetwork(remoteEndPoint))
  403. {
  404. _logger.LogInformation(
  405. "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
  406. username,
  407. remoteEndPoint);
  408. throw new SecurityException("Forbidden.");
  409. }
  410. if (!user.IsParentalScheduleAllowed())
  411. {
  412. _logger.LogInformation(
  413. "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
  414. username,
  415. remoteEndPoint);
  416. throw new SecurityException("User is not allowed access at this time.");
  417. }
  418. // Update LastActivityDate and LastLoginDate, then save
  419. if (success)
  420. {
  421. if (isUserSession)
  422. {
  423. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  424. }
  425. user.InvalidLoginAttemptCount = 0;
  426. await UpdateUserAsync(user).ConfigureAwait(false);
  427. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
  428. }
  429. else
  430. {
  431. await IncrementInvalidLoginAttemptCount(user).ConfigureAwait(false);
  432. _logger.LogInformation(
  433. "Authentication request for {UserName} has been denied (IP: {IP}).",
  434. user.Username,
  435. remoteEndPoint);
  436. }
  437. return success ? user : null;
  438. }
  439. /// <inheritdoc/>
  440. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  441. {
  442. var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
  443. if (user is not null && isInNetwork)
  444. {
  445. var passwordResetProvider = GetPasswordResetProvider(user);
  446. var result = await passwordResetProvider
  447. .StartForgotPasswordProcess(user, isInNetwork)
  448. .ConfigureAwait(false);
  449. await UpdateUserAsync(user).ConfigureAwait(false);
  450. return result;
  451. }
  452. return new ForgotPasswordResult
  453. {
  454. Action = ForgotPasswordAction.InNetworkRequired,
  455. PinFile = string.Empty
  456. };
  457. }
  458. /// <inheritdoc/>
  459. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  460. {
  461. foreach (var provider in _passwordResetProviders)
  462. {
  463. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  464. if (result.Success)
  465. {
  466. return result;
  467. }
  468. }
  469. return new PinRedeemResult();
  470. }
  471. /// <inheritdoc />
  472. public async Task InitializeAsync()
  473. {
  474. // TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
  475. if (_users.Any())
  476. {
  477. return;
  478. }
  479. var defaultName = Environment.UserName;
  480. if (string.IsNullOrWhiteSpace(defaultName) || !IsValidUsername(defaultName))
  481. {
  482. defaultName = "MyJellyfinUser";
  483. }
  484. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  485. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  486. await using (dbContext.ConfigureAwait(false))
  487. {
  488. var newUser = await CreateUserInternalAsync(defaultName, dbContext).ConfigureAwait(false);
  489. newUser.SetPermission(PermissionKind.IsAdministrator, true);
  490. newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
  491. newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
  492. dbContext.Users.Add(newUser);
  493. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  494. }
  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. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  549. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  550. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  551. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  552. dbContext.Update(user);
  553. _users[user.Id] = user;
  554. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  555. }
  556. }
  557. /// <inheritdoc/>
  558. public async Task UpdatePolicyAsync(Guid userId, UserPolicy policy)
  559. {
  560. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  561. await using (dbContext.ConfigureAwait(false))
  562. {
  563. var user = dbContext.Users
  564. .Include(u => u.Permissions)
  565. .Include(u => u.Preferences)
  566. .Include(u => u.AccessSchedules)
  567. .Include(u => u.ProfileImage)
  568. .FirstOrDefault(u => u.Id.Equals(userId))
  569. ?? throw new ArgumentException("No user exists with given Id!");
  570. // The default number of login attempts is 3, but for some god forsaken reason it's sent to the server as "0"
  571. int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
  572. {
  573. -1 => null,
  574. 0 => 3,
  575. _ => policy.LoginAttemptsBeforeLockout
  576. };
  577. user.MaxParentalAgeRating = policy.MaxParentalRating;
  578. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  579. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  580. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  581. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  582. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  583. user.LoginAttemptsBeforeLockout = maxLoginAttempts;
  584. user.MaxActiveSessions = policy.MaxActiveSessions;
  585. user.SyncPlayAccess = policy.SyncPlayAccess;
  586. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  587. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  588. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  589. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  590. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  591. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  592. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  593. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  594. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  595. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  596. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  597. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  598. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  599. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  600. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  601. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  602. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  603. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  604. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  605. user.SetPermission(PermissionKind.EnableCollectionManagement, policy.EnableCollectionManagement);
  606. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  607. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  608. user.AccessSchedules.Clear();
  609. foreach (var policyAccessSchedule in policy.AccessSchedules)
  610. {
  611. user.AccessSchedules.Add(policyAccessSchedule);
  612. }
  613. // TODO: fix this at some point
  614. user.SetPreference(PreferenceKind.BlockUnratedItems, policy.BlockUnratedItems ?? Array.Empty<UnratedItem>());
  615. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  616. user.SetPreference(PreferenceKind.AllowedTags, policy.AllowedTags);
  617. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  618. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  619. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  620. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  621. dbContext.Update(user);
  622. _users[user.Id] = user;
  623. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  624. }
  625. }
  626. /// <inheritdoc/>
  627. public async Task ClearProfileImageAsync(User user)
  628. {
  629. if (user.ProfileImage is null)
  630. {
  631. return;
  632. }
  633. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  634. await using (dbContext.ConfigureAwait(false))
  635. {
  636. dbContext.Remove(user.ProfileImage);
  637. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  638. }
  639. user.ProfileImage = null;
  640. _users[user.Id] = user;
  641. }
  642. internal static void ThrowIfInvalidUsername(string name)
  643. {
  644. if (!string.IsNullOrWhiteSpace(name) && IsValidUsername(name))
  645. {
  646. return;
  647. }
  648. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)", nameof(name));
  649. }
  650. private static bool IsValidUsername(ReadOnlySpan<char> name)
  651. {
  652. // This is some regex that matches only on unicode "word" characters, as well as -, _ and @
  653. // In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
  654. // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), periods (.) and spaces ( )
  655. return Regex.IsMatch(name, @"^[\w\ \-'._@]+$");
  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 IList<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 IList<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. string remoteEndPoint)
  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. if (!success
  728. && _networkManager.IsInLocalNetwork(remoteEndPoint)
  729. && user?.EnableLocalPassword == true
  730. && !string.IsNullOrEmpty(user.EasyPassword))
  731. {
  732. // Check easy password
  733. var passwordHash = PasswordHash.Parse(user.EasyPassword);
  734. success = _cryptoProvider.Verify(passwordHash, password);
  735. }
  736. return (authenticationProvider, username, success);
  737. }
  738. private async Task<(string Username, bool Success)> AuthenticateWithProvider(
  739. IAuthenticationProvider provider,
  740. string username,
  741. string password,
  742. User? resolvedUser)
  743. {
  744. try
  745. {
  746. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  747. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  748. : await provider.Authenticate(username, password).ConfigureAwait(false);
  749. if (authenticationResult.Username != username)
  750. {
  751. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  752. username = authenticationResult.Username;
  753. }
  754. return (username, true);
  755. }
  756. catch (AuthenticationException ex)
  757. {
  758. _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
  759. return (username, false);
  760. }
  761. }
  762. private async Task IncrementInvalidLoginAttemptCount(User user)
  763. {
  764. user.InvalidLoginAttemptCount++;
  765. int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
  766. if (maxInvalidLogins.HasValue && user.InvalidLoginAttemptCount >= maxInvalidLogins)
  767. {
  768. user.SetPermission(PermissionKind.IsDisabled, true);
  769. await _eventManager.PublishAsync(new UserLockedOutEventArgs(user)).ConfigureAwait(false);
  770. _logger.LogWarning(
  771. "Disabling user {Username} due to {Attempts} unsuccessful login attempts.",
  772. user.Username,
  773. user.InvalidLoginAttemptCount);
  774. }
  775. await UpdateUserAsync(user).ConfigureAwait(false);
  776. }
  777. private async Task UpdateUserInternalAsync(JellyfinDbContext dbContext, User user)
  778. {
  779. dbContext.Users.Update(user);
  780. _users[user.Id] = user;
  781. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  782. }
  783. }
  784. }