UserManager.cs 40 KB

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