UserManager.cs 38 KB

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