UserManager.cs 38 KB

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