UserManager.cs 39 KB

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