UserManager.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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<JellyfinDb> _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<JellyfinDb> 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. .Include(user => user.Permissions)
  82. .Include(user => user.Preferences)
  83. .Include(user => user.AccessSchedules)
  84. .Include(user => user.ProfileImage)
  85. .AsEnumerable())
  86. {
  87. _users.Add(user.Id, user);
  88. }
  89. }
  90. /// <inheritdoc/>
  91. public event EventHandler<GenericEventArgs<User>>? OnUserUpdated;
  92. /// <inheritdoc/>
  93. public IEnumerable<User> Users => _users.Values;
  94. /// <inheritdoc/>
  95. public IEnumerable<Guid> UsersIds => _users.Keys;
  96. /// <inheritdoc/>
  97. public User? GetUserById(Guid id)
  98. {
  99. if (id.Equals(default))
  100. {
  101. throw new ArgumentException("Guid can't be empty", nameof(id));
  102. }
  103. _users.TryGetValue(id, out var user);
  104. return user;
  105. }
  106. /// <inheritdoc/>
  107. public User? GetUserByName(string name)
  108. {
  109. if (string.IsNullOrWhiteSpace(name))
  110. {
  111. throw new ArgumentException("Invalid username", nameof(name));
  112. }
  113. return _users.Values.FirstOrDefault(u => string.Equals(u.Username, name, StringComparison.OrdinalIgnoreCase));
  114. }
  115. /// <inheritdoc/>
  116. public async Task RenameUser(User user, string newName)
  117. {
  118. ArgumentNullException.ThrowIfNull(user);
  119. ThrowIfInvalidUsername(newName);
  120. if (user.Username.Equals(newName, StringComparison.Ordinal))
  121. {
  122. throw new ArgumentException("The new and old names must be different.");
  123. }
  124. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  125. await using (dbContext.ConfigureAwait(false))
  126. {
  127. if (await dbContext.Users
  128. .AsQueryable()
  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, JellyfinDb 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. AccessSchedules = user.AccessSchedules.ToArray(),
  325. BlockedTags = user.GetPreference(PreferenceKind.BlockedTags),
  326. EnabledChannels = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledChannels),
  327. EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices),
  328. EnabledFolders = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders),
  329. EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders),
  330. SyncPlayAccess = user.SyncPlayAccess,
  331. BlockedChannels = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedChannels),
  332. BlockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders),
  333. BlockUnratedItems = user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems)
  334. }
  335. };
  336. }
  337. /// <inheritdoc/>
  338. public async Task<User?> AuthenticateUser(
  339. string username,
  340. string password,
  341. string passwordSha1,
  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, remoteEndPoint)
  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) || !IsValidUsername(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. }
  493. }
  494. /// <inheritdoc/>
  495. public NameIdPair[] GetAuthenticationProviders()
  496. {
  497. return _authenticationProviders
  498. .Where(provider => provider.IsEnabled)
  499. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  500. .ThenBy(i => i.Name)
  501. .Select(i => new NameIdPair
  502. {
  503. Name = i.Name,
  504. Id = i.GetType().FullName
  505. })
  506. .ToArray();
  507. }
  508. /// <inheritdoc/>
  509. public NameIdPair[] GetPasswordResetProviders()
  510. {
  511. return _passwordResetProviders
  512. .Where(provider => provider.IsEnabled)
  513. .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
  514. .ThenBy(i => i.Name)
  515. .Select(i => new NameIdPair
  516. {
  517. Name = i.Name,
  518. Id = i.GetType().FullName
  519. })
  520. .ToArray();
  521. }
  522. /// <inheritdoc/>
  523. public async Task UpdateConfigurationAsync(Guid userId, UserConfiguration config)
  524. {
  525. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  526. await using (dbContext.ConfigureAwait(false))
  527. {
  528. var user = dbContext.Users
  529. .Include(u => u.Permissions)
  530. .Include(u => u.Preferences)
  531. .Include(u => u.AccessSchedules)
  532. .Include(u => u.ProfileImage)
  533. .FirstOrDefault(u => u.Id.Equals(userId))
  534. ?? throw new ArgumentException("No user exists with given Id!");
  535. user.SubtitleMode = config.SubtitleMode;
  536. user.HidePlayedInLatest = config.HidePlayedInLatest;
  537. user.EnableLocalPassword = config.EnableLocalPassword;
  538. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  539. user.DisplayCollectionsView = config.DisplayCollectionsView;
  540. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  541. user.AudioLanguagePreference = config.AudioLanguagePreference;
  542. user.RememberAudioSelections = config.RememberAudioSelections;
  543. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  544. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  545. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  546. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  547. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  548. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  549. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  550. dbContext.Update(user);
  551. _users[user.Id] = user;
  552. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  553. }
  554. }
  555. /// <inheritdoc/>
  556. public async Task UpdatePolicyAsync(Guid userId, UserPolicy policy)
  557. {
  558. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  559. await using (dbContext.ConfigureAwait(false))
  560. {
  561. var user = dbContext.Users
  562. .Include(u => u.Permissions)
  563. .Include(u => u.Preferences)
  564. .Include(u => u.AccessSchedules)
  565. .Include(u => u.ProfileImage)
  566. .FirstOrDefault(u => u.Id.Equals(userId))
  567. ?? throw new ArgumentException("No user exists with given Id!");
  568. // The default number of login attempts is 3, but for some god forsaken reason it's sent to the server as "0"
  569. int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
  570. {
  571. -1 => null,
  572. 0 => 3,
  573. _ => policy.LoginAttemptsBeforeLockout
  574. };
  575. user.MaxParentalAgeRating = policy.MaxParentalRating;
  576. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  577. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  578. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  579. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  580. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  581. user.LoginAttemptsBeforeLockout = maxLoginAttempts;
  582. user.MaxActiveSessions = policy.MaxActiveSessions;
  583. user.SyncPlayAccess = policy.SyncPlayAccess;
  584. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  585. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  586. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  587. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  588. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  589. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  590. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  591. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  592. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  593. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  594. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  595. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  596. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  597. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  598. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  599. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  600. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  601. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  602. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  603. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  604. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  605. user.AccessSchedules.Clear();
  606. foreach (var policyAccessSchedule in policy.AccessSchedules)
  607. {
  608. user.AccessSchedules.Add(policyAccessSchedule);
  609. }
  610. // TODO: fix this at some point
  611. user.SetPreference(PreferenceKind.BlockUnratedItems, policy.BlockUnratedItems ?? Array.Empty<UnratedItem>());
  612. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  613. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  614. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  615. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  616. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  617. dbContext.Update(user);
  618. _users[user.Id] = user;
  619. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  620. }
  621. }
  622. /// <inheritdoc/>
  623. public async Task ClearProfileImageAsync(User user)
  624. {
  625. if (user.ProfileImage is null)
  626. {
  627. return;
  628. }
  629. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  630. await using (dbContext.ConfigureAwait(false))
  631. {
  632. dbContext.Remove(user.ProfileImage);
  633. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  634. }
  635. user.ProfileImage = null;
  636. _users[user.Id] = user;
  637. }
  638. internal static void ThrowIfInvalidUsername(string name)
  639. {
  640. if (!string.IsNullOrWhiteSpace(name) && IsValidUsername(name))
  641. {
  642. return;
  643. }
  644. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)", nameof(name));
  645. }
  646. private static bool IsValidUsername(string name)
  647. {
  648. // This is some regex that matches only on unicode "word" characters, as well as -, _ and @
  649. // In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
  650. // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), periods (.) and spaces ( )
  651. return Regex.IsMatch(name, @"^[\w\ \-'._@]+$");
  652. }
  653. private IAuthenticationProvider GetAuthenticationProvider(User user)
  654. {
  655. return GetAuthenticationProviders(user)[0];
  656. }
  657. private IPasswordResetProvider GetPasswordResetProvider(User user)
  658. {
  659. return GetPasswordResetProviders(user)[0];
  660. }
  661. private IList<IAuthenticationProvider> GetAuthenticationProviders(User? user)
  662. {
  663. var authenticationProviderId = user?.AuthenticationProviderId;
  664. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();
  665. if (!string.IsNullOrEmpty(authenticationProviderId))
  666. {
  667. providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
  668. }
  669. if (providers.Count == 0)
  670. {
  671. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  672. _logger.LogWarning(
  673. "User {Username} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
  674. user?.Username,
  675. user?.AuthenticationProviderId);
  676. providers = new List<IAuthenticationProvider>
  677. {
  678. _invalidAuthProvider
  679. };
  680. }
  681. return providers;
  682. }
  683. private IList<IPasswordResetProvider> GetPasswordResetProviders(User user)
  684. {
  685. var passwordResetProviderId = user.PasswordResetProviderId;
  686. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  687. if (!string.IsNullOrEmpty(passwordResetProviderId))
  688. {
  689. providers = providers.Where(i =>
  690. string.Equals(passwordResetProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase))
  691. .ToArray();
  692. }
  693. if (providers.Length == 0)
  694. {
  695. providers = new IPasswordResetProvider[]
  696. {
  697. _defaultPasswordResetProvider
  698. };
  699. }
  700. return providers;
  701. }
  702. private async Task<(IAuthenticationProvider? AuthenticationProvider, string Username, bool Success)> AuthenticateLocalUser(
  703. string username,
  704. string password,
  705. User? user,
  706. string remoteEndPoint)
  707. {
  708. bool success = false;
  709. IAuthenticationProvider? authenticationProvider = null;
  710. foreach (var provider in GetAuthenticationProviders(user))
  711. {
  712. var providerAuthResult =
  713. await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  714. var updatedUsername = providerAuthResult.Username;
  715. success = providerAuthResult.Success;
  716. if (success)
  717. {
  718. authenticationProvider = provider;
  719. username = updatedUsername;
  720. break;
  721. }
  722. }
  723. if (!success
  724. && _networkManager.IsInLocalNetwork(remoteEndPoint)
  725. && user?.EnableLocalPassword == true
  726. && !string.IsNullOrEmpty(user.EasyPassword))
  727. {
  728. // Check easy password
  729. var passwordHash = PasswordHash.Parse(user.EasyPassword);
  730. success = _cryptoProvider.Verify(passwordHash, password);
  731. }
  732. return (authenticationProvider, username, success);
  733. }
  734. private async Task<(string Username, bool Success)> AuthenticateWithProvider(
  735. IAuthenticationProvider provider,
  736. string username,
  737. string password,
  738. User? resolvedUser)
  739. {
  740. try
  741. {
  742. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  743. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  744. : await provider.Authenticate(username, password).ConfigureAwait(false);
  745. if (authenticationResult.Username != username)
  746. {
  747. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  748. username = authenticationResult.Username;
  749. }
  750. return (username, true);
  751. }
  752. catch (AuthenticationException ex)
  753. {
  754. _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
  755. return (username, false);
  756. }
  757. }
  758. private async Task IncrementInvalidLoginAttemptCount(User user)
  759. {
  760. user.InvalidLoginAttemptCount++;
  761. int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
  762. if (maxInvalidLogins.HasValue && user.InvalidLoginAttemptCount >= maxInvalidLogins)
  763. {
  764. user.SetPermission(PermissionKind.IsDisabled, true);
  765. await _eventManager.PublishAsync(new UserLockedOutEventArgs(user)).ConfigureAwait(false);
  766. _logger.LogWarning(
  767. "Disabling user {Username} due to {Attempts} unsuccessful login attempts.",
  768. user.Username,
  769. user.InvalidLoginAttemptCount);
  770. }
  771. await UpdateUserAsync(user).ConfigureAwait(false);
  772. }
  773. private async Task UpdateUserInternalAsync(JellyfinDb dbContext, User user)
  774. {
  775. dbContext.Users.Update(user);
  776. _users[user.Id] = user;
  777. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  778. }
  779. }
  780. }