UserManager.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. #nullable enable
  2. #pragma warning disable CA1307
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Data.Entities;
  11. using Jellyfin.Data.Enums;
  12. using Jellyfin.Data.Events;
  13. using Jellyfin.Data.Events.Users;
  14. using MediaBrowser.Common;
  15. using MediaBrowser.Common.Cryptography;
  16. using MediaBrowser.Common.Extensions;
  17. using MediaBrowser.Common.Net;
  18. using MediaBrowser.Controller.Authentication;
  19. using MediaBrowser.Controller.Drawing;
  20. using MediaBrowser.Controller.Events;
  21. using MediaBrowser.Controller.Library;
  22. using MediaBrowser.Controller.Net;
  23. using MediaBrowser.Model.Configuration;
  24. using MediaBrowser.Model.Cryptography;
  25. using MediaBrowser.Model.Dto;
  26. using MediaBrowser.Model.Users;
  27. using Microsoft.EntityFrameworkCore;
  28. using Microsoft.Extensions.Logging;
  29. namespace Jellyfin.Server.Implementations.Users
  30. {
  31. /// <summary>
  32. /// Manages the creation and retrieval of <see cref="User"/> instances.
  33. /// </summary>
  34. public class UserManager : IUserManager
  35. {
  36. private readonly JellyfinDbProvider _dbProvider;
  37. private readonly IEventManager _eventManager;
  38. private readonly ICryptoProvider _cryptoProvider;
  39. private readonly INetworkManager _networkManager;
  40. private readonly IApplicationHost _appHost;
  41. private readonly IImageProcessor _imageProcessor;
  42. private readonly ILogger<UserManager> _logger;
  43. private readonly IReadOnlyCollection<IPasswordResetProvider> _passwordResetProviders;
  44. private readonly IReadOnlyCollection<IAuthenticationProvider> _authenticationProviders;
  45. private readonly InvalidAuthProvider _invalidAuthProvider;
  46. private readonly DefaultAuthenticationProvider _defaultAuthenticationProvider;
  47. private readonly DefaultPasswordResetProvider _defaultPasswordResetProvider;
  48. /// <summary>
  49. /// Initializes a new instance of the <see cref="UserManager"/> class.
  50. /// </summary>
  51. /// <param name="dbProvider">The database provider.</param>
  52. /// <param name="eventManager">The event manager.</param>
  53. /// <param name="cryptoProvider">The cryptography provider.</param>
  54. /// <param name="networkManager">The network manager.</param>
  55. /// <param name="appHost">The application host.</param>
  56. /// <param name="imageProcessor">The image processor.</param>
  57. /// <param name="logger">The logger.</param>
  58. public UserManager(
  59. JellyfinDbProvider dbProvider,
  60. IEventManager eventManager,
  61. ICryptoProvider cryptoProvider,
  62. INetworkManager networkManager,
  63. IApplicationHost appHost,
  64. IImageProcessor imageProcessor,
  65. ILogger<UserManager> logger)
  66. {
  67. _dbProvider = dbProvider;
  68. _eventManager = eventManager;
  69. _cryptoProvider = cryptoProvider;
  70. _networkManager = networkManager;
  71. _appHost = appHost;
  72. _imageProcessor = imageProcessor;
  73. _logger = logger;
  74. _passwordResetProviders = appHost.GetExports<IPasswordResetProvider>();
  75. _authenticationProviders = appHost.GetExports<IAuthenticationProvider>();
  76. _invalidAuthProvider = _authenticationProviders.OfType<InvalidAuthProvider>().First();
  77. _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
  78. _defaultPasswordResetProvider = _passwordResetProviders.OfType<DefaultPasswordResetProvider>().First();
  79. }
  80. /// <inheritdoc/>
  81. public event EventHandler<GenericEventArgs<User>>? OnUserUpdated;
  82. /// <inheritdoc/>
  83. public IEnumerable<User> Users
  84. {
  85. get
  86. {
  87. using var dbContext = _dbProvider.CreateContext();
  88. return dbContext.Users
  89. .Include(user => user.Permissions)
  90. .Include(user => user.Preferences)
  91. .Include(user => user.AccessSchedules)
  92. .Include(user => user.ProfileImage)
  93. .ToList();
  94. }
  95. }
  96. /// <inheritdoc/>
  97. public IEnumerable<Guid> UsersIds
  98. {
  99. get
  100. {
  101. using var dbContext = _dbProvider.CreateContext();
  102. return dbContext.Users
  103. .AsQueryable()
  104. .Select(user => user.Id)
  105. .ToList();
  106. }
  107. }
  108. /// <inheritdoc/>
  109. public User? GetUserById(Guid id)
  110. {
  111. if (id == Guid.Empty)
  112. {
  113. throw new ArgumentException("Guid can't be empty", nameof(id));
  114. }
  115. using var dbContext = _dbProvider.CreateContext();
  116. return dbContext.Users
  117. .Include(user => user.Permissions)
  118. .Include(user => user.Preferences)
  119. .Include(user => user.AccessSchedules)
  120. .Include(user => user.ProfileImage)
  121. .FirstOrDefault(user => user.Id == id);
  122. }
  123. /// <inheritdoc/>
  124. public User? GetUserByName(string name)
  125. {
  126. if (string.IsNullOrWhiteSpace(name))
  127. {
  128. throw new ArgumentException("Invalid username", nameof(name));
  129. }
  130. using var dbContext = _dbProvider.CreateContext();
  131. return dbContext.Users
  132. .Include(user => user.Permissions)
  133. .Include(user => user.Preferences)
  134. .Include(user => user.AccessSchedules)
  135. .Include(user => user.ProfileImage)
  136. .AsEnumerable()
  137. .FirstOrDefault(u => string.Equals(u.Username, name, StringComparison.OrdinalIgnoreCase));
  138. }
  139. /// <inheritdoc/>
  140. public async Task RenameUser(User user, string newName)
  141. {
  142. if (user == null)
  143. {
  144. throw new ArgumentNullException(nameof(user));
  145. }
  146. if (string.IsNullOrWhiteSpace(newName))
  147. {
  148. throw new ArgumentException("Invalid username", nameof(newName));
  149. }
  150. if (user.Username.Equals(newName, StringComparison.Ordinal))
  151. {
  152. throw new ArgumentException("The new and old names must be different.");
  153. }
  154. if (Users.Any(u => u.Id != user.Id && u.Username.Equals(newName, StringComparison.Ordinal)))
  155. {
  156. throw new ArgumentException(string.Format(
  157. CultureInfo.InvariantCulture,
  158. "A user with the name '{0}' already exists.",
  159. newName));
  160. }
  161. user.Username = newName;
  162. await UpdateUserAsync(user).ConfigureAwait(false);
  163. OnUserUpdated?.Invoke(this, new GenericEventArgs<User>(user));
  164. }
  165. /// <inheritdoc/>
  166. public void UpdateUser(User user)
  167. {
  168. using var dbContext = _dbProvider.CreateContext();
  169. dbContext.Users.Update(user);
  170. dbContext.SaveChanges();
  171. }
  172. /// <inheritdoc/>
  173. public async Task UpdateUserAsync(User user)
  174. {
  175. await using var dbContext = _dbProvider.CreateContext();
  176. dbContext.Users.Update(user);
  177. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  178. }
  179. internal async Task<User> CreateUserInternalAsync(string name, JellyfinDb dbContext)
  180. {
  181. // TODO: Remove after user item data is migrated.
  182. var max = await dbContext.Users.AsQueryable().AnyAsync().ConfigureAwait(false)
  183. ? await dbContext.Users.AsQueryable().Select(u => u.InternalId).MaxAsync().ConfigureAwait(false)
  184. : 0;
  185. return new User(
  186. name,
  187. _defaultAuthenticationProvider.GetType().FullName,
  188. _defaultPasswordResetProvider.GetType().FullName)
  189. {
  190. InternalId = max + 1
  191. };
  192. }
  193. /// <inheritdoc/>
  194. public async Task<User> CreateUserAsync(string name)
  195. {
  196. if (!IsValidUsername(name))
  197. {
  198. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  199. }
  200. await using var dbContext = _dbProvider.CreateContext();
  201. var newUser = await CreateUserInternalAsync(name, dbContext).ConfigureAwait(false);
  202. dbContext.Users.Add(newUser);
  203. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  204. await _eventManager.PublishAsync(new UserCreatedEventArgs(newUser)).ConfigureAwait(false);
  205. return newUser;
  206. }
  207. /// <inheritdoc/>
  208. public void DeleteUser(Guid userId)
  209. {
  210. using var dbContext = _dbProvider.CreateContext();
  211. var user = dbContext.Users
  212. .Include(u => u.Permissions)
  213. .Include(u => u.Preferences)
  214. .Include(u => u.AccessSchedules)
  215. .Include(u => u.ProfileImage)
  216. .FirstOrDefault(u => u.Id == userId);
  217. if (user == null)
  218. {
  219. throw new ResourceNotFoundException(nameof(userId));
  220. }
  221. if (dbContext.Users.Find(user.Id) == null)
  222. {
  223. throw new ArgumentException(string.Format(
  224. CultureInfo.InvariantCulture,
  225. "The user cannot be deleted because there is no user with the Name {0} and Id {1}.",
  226. user.Username,
  227. user.Id));
  228. }
  229. if (dbContext.Users.Count() == 1)
  230. {
  231. throw new InvalidOperationException(string.Format(
  232. CultureInfo.InvariantCulture,
  233. "The user '{0}' cannot be deleted because there must be at least one user in the system.",
  234. user.Username));
  235. }
  236. if (user.HasPermission(PermissionKind.IsAdministrator)
  237. && Users.Count(i => i.HasPermission(PermissionKind.IsAdministrator)) == 1)
  238. {
  239. throw new ArgumentException(
  240. string.Format(
  241. CultureInfo.InvariantCulture,
  242. "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
  243. user.Username),
  244. nameof(userId));
  245. }
  246. // Clear all entities related to the user from the database.
  247. if (user.ProfileImage != null)
  248. {
  249. dbContext.Remove(user.ProfileImage);
  250. }
  251. dbContext.RemoveRange(user.Permissions);
  252. dbContext.RemoveRange(user.Preferences);
  253. dbContext.RemoveRange(user.AccessSchedules);
  254. dbContext.Users.Remove(user);
  255. dbContext.SaveChanges();
  256. _eventManager.Publish(new UserDeletedEventArgs(user));
  257. }
  258. /// <inheritdoc/>
  259. public Task ResetPassword(User user)
  260. {
  261. return ChangePassword(user, string.Empty);
  262. }
  263. /// <inheritdoc/>
  264. public void ResetEasyPassword(User user)
  265. {
  266. ChangeEasyPassword(user, string.Empty, null);
  267. }
  268. /// <inheritdoc/>
  269. public async Task ChangePassword(User user, string newPassword)
  270. {
  271. if (user == null)
  272. {
  273. throw new ArgumentNullException(nameof(user));
  274. }
  275. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  276. await UpdateUserAsync(user).ConfigureAwait(false);
  277. await _eventManager.PublishAsync(new UserPasswordChangedEventArgs(user)).ConfigureAwait(false);
  278. }
  279. /// <inheritdoc/>
  280. public void ChangeEasyPassword(User user, string newPassword, string? newPasswordSha1)
  281. {
  282. if (newPassword != null)
  283. {
  284. newPasswordSha1 = _cryptoProvider.CreatePasswordHash(newPassword).ToString();
  285. }
  286. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  287. {
  288. throw new ArgumentNullException(nameof(newPasswordSha1));
  289. }
  290. user.EasyPassword = newPasswordSha1;
  291. UpdateUser(user);
  292. _eventManager.Publish(new UserPasswordChangedEventArgs(user));
  293. }
  294. /// <inheritdoc/>
  295. public UserDto GetUserDto(User user, string? remoteEndPoint = null)
  296. {
  297. var hasPassword = GetAuthenticationProvider(user).HasPassword(user);
  298. return new UserDto
  299. {
  300. Name = user.Username,
  301. Id = user.Id,
  302. ServerId = _appHost.SystemId,
  303. HasPassword = hasPassword,
  304. HasConfiguredPassword = hasPassword,
  305. HasConfiguredEasyPassword = !string.IsNullOrEmpty(user.EasyPassword),
  306. EnableAutoLogin = user.EnableAutoLogin,
  307. LastLoginDate = user.LastLoginDate,
  308. LastActivityDate = user.LastActivityDate,
  309. PrimaryImageTag = user.ProfileImage != null ? _imageProcessor.GetImageCacheTag(user) : null,
  310. Configuration = new UserConfiguration
  311. {
  312. SubtitleMode = user.SubtitleMode,
  313. HidePlayedInLatest = user.HidePlayedInLatest,
  314. EnableLocalPassword = user.EnableLocalPassword,
  315. PlayDefaultAudioTrack = user.PlayDefaultAudioTrack,
  316. DisplayCollectionsView = user.DisplayCollectionsView,
  317. DisplayMissingEpisodes = user.DisplayMissingEpisodes,
  318. AudioLanguagePreference = user.AudioLanguagePreference,
  319. RememberAudioSelections = user.RememberAudioSelections,
  320. EnableNextEpisodeAutoPlay = user.EnableNextEpisodeAutoPlay,
  321. RememberSubtitleSelections = user.RememberSubtitleSelections,
  322. SubtitleLanguagePreference = user.SubtitleLanguagePreference ?? string.Empty,
  323. OrderedViews = user.GetPreference(PreferenceKind.OrderedViews),
  324. GroupedFolders = user.GetPreference(PreferenceKind.GroupedFolders),
  325. MyMediaExcludes = user.GetPreference(PreferenceKind.MyMediaExcludes),
  326. LatestItemsExcludes = user.GetPreference(PreferenceKind.LatestItemExcludes)
  327. },
  328. Policy = new UserPolicy
  329. {
  330. MaxParentalRating = user.MaxParentalAgeRating,
  331. EnableUserPreferenceAccess = user.EnableUserPreferenceAccess,
  332. RemoteClientBitrateLimit = user.RemoteClientBitrateLimit ?? 0,
  333. AuthenticationProviderId = user.AuthenticationProviderId,
  334. PasswordResetProviderId = user.PasswordResetProviderId,
  335. InvalidLoginAttemptCount = user.InvalidLoginAttemptCount,
  336. LoginAttemptsBeforeLockout = user.LoginAttemptsBeforeLockout ?? -1,
  337. MaxActiveSessions = user.MaxActiveSessions,
  338. IsAdministrator = user.HasPermission(PermissionKind.IsAdministrator),
  339. IsHidden = user.HasPermission(PermissionKind.IsHidden),
  340. IsDisabled = user.HasPermission(PermissionKind.IsDisabled),
  341. EnableSharedDeviceControl = user.HasPermission(PermissionKind.EnableSharedDeviceControl),
  342. EnableRemoteAccess = user.HasPermission(PermissionKind.EnableRemoteAccess),
  343. EnableLiveTvManagement = user.HasPermission(PermissionKind.EnableLiveTvManagement),
  344. EnableLiveTvAccess = user.HasPermission(PermissionKind.EnableLiveTvAccess),
  345. EnableMediaPlayback = user.HasPermission(PermissionKind.EnableMediaPlayback),
  346. EnableAudioPlaybackTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding),
  347. EnableVideoPlaybackTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding),
  348. EnableContentDeletion = user.HasPermission(PermissionKind.EnableContentDeletion),
  349. EnableContentDownloading = user.HasPermission(PermissionKind.EnableContentDownloading),
  350. EnableSyncTranscoding = user.HasPermission(PermissionKind.EnableSyncTranscoding),
  351. EnableMediaConversion = user.HasPermission(PermissionKind.EnableMediaConversion),
  352. EnableAllChannels = user.HasPermission(PermissionKind.EnableAllChannels),
  353. EnableAllDevices = user.HasPermission(PermissionKind.EnableAllDevices),
  354. EnableAllFolders = user.HasPermission(PermissionKind.EnableAllFolders),
  355. EnableRemoteControlOfOtherUsers = user.HasPermission(PermissionKind.EnableRemoteControlOfOtherUsers),
  356. EnablePlaybackRemuxing = user.HasPermission(PermissionKind.EnablePlaybackRemuxing),
  357. ForceRemoteSourceTranscoding = user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding),
  358. EnablePublicSharing = user.HasPermission(PermissionKind.EnablePublicSharing),
  359. AccessSchedules = user.AccessSchedules.ToArray(),
  360. BlockedTags = user.GetPreference(PreferenceKind.BlockedTags),
  361. EnabledChannels = user.GetPreference(PreferenceKind.EnabledChannels)?.Select(Guid.Parse).ToArray(),
  362. EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices),
  363. EnabledFolders = user.GetPreference(PreferenceKind.EnabledFolders)?.Select(Guid.Parse).ToArray(),
  364. EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders),
  365. SyncPlayAccess = user.SyncPlayAccess,
  366. BlockedChannels = user.GetPreference(PreferenceKind.BlockedChannels)?.Select(Guid.Parse).ToArray(),
  367. BlockedMediaFolders = user.GetPreference(PreferenceKind.BlockedMediaFolders)?.Select(Guid.Parse).ToArray(),
  368. BlockUnratedItems = user.GetPreference(PreferenceKind.BlockUnratedItems).Select(Enum.Parse<UnratedItem>).ToArray()
  369. }
  370. };
  371. }
  372. /// <inheritdoc/>
  373. public async Task<User?> AuthenticateUser(
  374. string username,
  375. string password,
  376. string passwordSha1,
  377. string remoteEndPoint,
  378. bool isUserSession)
  379. {
  380. if (string.IsNullOrWhiteSpace(username))
  381. {
  382. _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
  383. throw new ArgumentNullException(nameof(username));
  384. }
  385. var user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  386. bool success;
  387. IAuthenticationProvider? authenticationProvider;
  388. if (user != null)
  389. {
  390. var authResult = await AuthenticateLocalUser(username, password, user, remoteEndPoint)
  391. .ConfigureAwait(false);
  392. authenticationProvider = authResult.authenticationProvider;
  393. success = authResult.success;
  394. }
  395. else
  396. {
  397. var authResult = await AuthenticateLocalUser(username, password, null, remoteEndPoint)
  398. .ConfigureAwait(false);
  399. authenticationProvider = authResult.authenticationProvider;
  400. string updatedUsername = authResult.username;
  401. success = authResult.success;
  402. if (success
  403. && authenticationProvider != null
  404. && !(authenticationProvider is DefaultAuthenticationProvider))
  405. {
  406. // Trust the username returned by the authentication provider
  407. username = updatedUsername;
  408. // Search the database for the user again
  409. // the authentication provider might have created it
  410. user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  411. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy)
  412. {
  413. UpdatePolicy(user.Id, hasNewUserPolicy.GetNewUserPolicy());
  414. await UpdateUserAsync(user).ConfigureAwait(false);
  415. }
  416. }
  417. }
  418. if (success && user != null && authenticationProvider != null)
  419. {
  420. var providerId = authenticationProvider.GetType().FullName;
  421. if (!string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  422. {
  423. user.AuthenticationProviderId = providerId;
  424. await UpdateUserAsync(user).ConfigureAwait(false);
  425. }
  426. }
  427. if (user == null)
  428. {
  429. _logger.LogInformation(
  430. "Authentication request for {UserName} has been denied (IP: {IP}).",
  431. username,
  432. remoteEndPoint);
  433. throw new AuthenticationException("Invalid username or password entered.");
  434. }
  435. if (user.HasPermission(PermissionKind.IsDisabled))
  436. {
  437. _logger.LogInformation(
  438. "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
  439. username,
  440. remoteEndPoint);
  441. throw new SecurityException(
  442. $"The {user.Username} account is currently disabled. Please consult with your administrator.");
  443. }
  444. if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
  445. !_networkManager.IsInLocalNetwork(remoteEndPoint))
  446. {
  447. _logger.LogInformation(
  448. "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
  449. username,
  450. remoteEndPoint);
  451. throw new SecurityException("Forbidden.");
  452. }
  453. if (!user.IsParentalScheduleAllowed())
  454. {
  455. _logger.LogInformation(
  456. "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
  457. username,
  458. remoteEndPoint);
  459. throw new SecurityException("User is not allowed access at this time.");
  460. }
  461. // Update LastActivityDate and LastLoginDate, then save
  462. if (success)
  463. {
  464. if (isUserSession)
  465. {
  466. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  467. }
  468. user.InvalidLoginAttemptCount = 0;
  469. await UpdateUserAsync(user).ConfigureAwait(false);
  470. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
  471. }
  472. else
  473. {
  474. await IncrementInvalidLoginAttemptCount(user).ConfigureAwait(false);
  475. _logger.LogInformation(
  476. "Authentication request for {UserName} has been denied (IP: {IP}).",
  477. user.Username,
  478. remoteEndPoint);
  479. }
  480. return success ? user : null;
  481. }
  482. /// <inheritdoc/>
  483. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  484. {
  485. var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
  486. if (user != null && isInNetwork)
  487. {
  488. var passwordResetProvider = GetPasswordResetProvider(user);
  489. var result = await passwordResetProvider
  490. .StartForgotPasswordProcess(user, isInNetwork)
  491. .ConfigureAwait(false);
  492. await UpdateUserAsync(user).ConfigureAwait(false);
  493. return result;
  494. }
  495. return new ForgotPasswordResult
  496. {
  497. Action = ForgotPasswordAction.InNetworkRequired,
  498. PinFile = string.Empty
  499. };
  500. }
  501. /// <inheritdoc/>
  502. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  503. {
  504. foreach (var provider in _passwordResetProviders)
  505. {
  506. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  507. if (result.Success)
  508. {
  509. return result;
  510. }
  511. }
  512. return new PinRedeemResult
  513. {
  514. Success = false,
  515. UsersReset = Array.Empty<string>()
  516. };
  517. }
  518. /// <inheritdoc />
  519. public async Task InitializeAsync()
  520. {
  521. // TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
  522. await using var dbContext = _dbProvider.CreateContext();
  523. if (await dbContext.Users.AsQueryable().AnyAsync().ConfigureAwait(false))
  524. {
  525. return;
  526. }
  527. var defaultName = Environment.UserName;
  528. if (string.IsNullOrWhiteSpace(defaultName) || !IsValidUsername(defaultName))
  529. {
  530. defaultName = "MyJellyfinUser";
  531. }
  532. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  533. var newUser = await CreateUserInternalAsync(defaultName, dbContext).ConfigureAwait(false);
  534. newUser.SetPermission(PermissionKind.IsAdministrator, true);
  535. newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
  536. newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
  537. dbContext.Users.Add(newUser);
  538. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  539. }
  540. /// <inheritdoc/>
  541. public NameIdPair[] GetAuthenticationProviders()
  542. {
  543. return _authenticationProviders
  544. .Where(provider => provider.IsEnabled)
  545. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  546. .ThenBy(i => i.Name)
  547. .Select(i => new NameIdPair
  548. {
  549. Name = i.Name,
  550. Id = i.GetType().FullName
  551. })
  552. .ToArray();
  553. }
  554. /// <inheritdoc/>
  555. public NameIdPair[] GetPasswordResetProviders()
  556. {
  557. return _passwordResetProviders
  558. .Where(provider => provider.IsEnabled)
  559. .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
  560. .ThenBy(i => i.Name)
  561. .Select(i => new NameIdPair
  562. {
  563. Name = i.Name,
  564. Id = i.GetType().FullName
  565. })
  566. .ToArray();
  567. }
  568. /// <inheritdoc/>
  569. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  570. {
  571. using var dbContext = _dbProvider.CreateContext();
  572. var user = dbContext.Users
  573. .Include(u => u.Permissions)
  574. .Include(u => u.Preferences)
  575. .Include(u => u.AccessSchedules)
  576. .Include(u => u.ProfileImage)
  577. .FirstOrDefault(u => u.Id == userId)
  578. ?? throw new ArgumentException("No user exists with given Id!");
  579. user.SubtitleMode = config.SubtitleMode;
  580. user.HidePlayedInLatest = config.HidePlayedInLatest;
  581. user.EnableLocalPassword = config.EnableLocalPassword;
  582. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  583. user.DisplayCollectionsView = config.DisplayCollectionsView;
  584. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  585. user.AudioLanguagePreference = config.AudioLanguagePreference;
  586. user.RememberAudioSelections = config.RememberAudioSelections;
  587. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  588. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  589. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  590. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  591. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  592. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  593. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  594. dbContext.Update(user);
  595. dbContext.SaveChanges();
  596. }
  597. /// <inheritdoc/>
  598. public void UpdatePolicy(Guid userId, UserPolicy policy)
  599. {
  600. using var dbContext = _dbProvider.CreateContext();
  601. var user = dbContext.Users
  602. .Include(u => u.Permissions)
  603. .Include(u => u.Preferences)
  604. .Include(u => u.AccessSchedules)
  605. .Include(u => u.ProfileImage)
  606. .FirstOrDefault(u => u.Id == userId)
  607. ?? throw new ArgumentException("No user exists with given Id!");
  608. // The default number of login attempts is 3, but for some god forsaken reason it's sent to the server as "0"
  609. int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
  610. {
  611. -1 => null,
  612. 0 => 3,
  613. _ => policy.LoginAttemptsBeforeLockout
  614. };
  615. user.MaxParentalAgeRating = policy.MaxParentalRating;
  616. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  617. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  618. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  619. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  620. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  621. user.LoginAttemptsBeforeLockout = maxLoginAttempts;
  622. user.MaxActiveSessions = policy.MaxActiveSessions;
  623. user.SyncPlayAccess = policy.SyncPlayAccess;
  624. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  625. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  626. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  627. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  628. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  629. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  630. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  631. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  632. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  633. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  634. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  635. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  636. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  637. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  638. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  639. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  640. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  641. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  642. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  643. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  644. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  645. user.AccessSchedules.Clear();
  646. foreach (var policyAccessSchedule in policy.AccessSchedules)
  647. {
  648. user.AccessSchedules.Add(policyAccessSchedule);
  649. }
  650. // TODO: fix this at some point
  651. user.SetPreference(
  652. PreferenceKind.BlockUnratedItems,
  653. policy.BlockUnratedItems?.Select(i => i.ToString()).ToArray() ?? Array.Empty<string>());
  654. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  655. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels?.Select(i => i.ToString("N", CultureInfo.InvariantCulture)).ToArray());
  656. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  657. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders?.Select(i => i.ToString("N", CultureInfo.InvariantCulture)).ToArray());
  658. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  659. dbContext.Update(user);
  660. dbContext.SaveChanges();
  661. }
  662. /// <inheritdoc/>
  663. public void ClearProfileImage(User user)
  664. {
  665. using var dbContext = _dbProvider.CreateContext();
  666. dbContext.Remove(user.ProfileImage);
  667. dbContext.SaveChanges();
  668. }
  669. private static bool IsValidUsername(string name)
  670. {
  671. // This is some regex that matches only on unicode "word" characters, as well as -, _ and @
  672. // In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
  673. // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), periods (.) and spaces ( )
  674. return Regex.IsMatch(name, @"^[\w\ \-'._@]*$");
  675. }
  676. private IAuthenticationProvider GetAuthenticationProvider(User user)
  677. {
  678. return GetAuthenticationProviders(user)[0];
  679. }
  680. private IPasswordResetProvider GetPasswordResetProvider(User user)
  681. {
  682. return GetPasswordResetProviders(user)[0];
  683. }
  684. private IList<IAuthenticationProvider> GetAuthenticationProviders(User? user)
  685. {
  686. var authenticationProviderId = user?.AuthenticationProviderId;
  687. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();
  688. if (!string.IsNullOrEmpty(authenticationProviderId))
  689. {
  690. providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
  691. }
  692. if (providers.Count == 0)
  693. {
  694. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  695. _logger.LogWarning(
  696. "User {Username} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
  697. user?.Username,
  698. user?.AuthenticationProviderId);
  699. providers = new List<IAuthenticationProvider>
  700. {
  701. _invalidAuthProvider
  702. };
  703. }
  704. return providers;
  705. }
  706. private IList<IPasswordResetProvider> GetPasswordResetProviders(User user)
  707. {
  708. var passwordResetProviderId = user.PasswordResetProviderId;
  709. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  710. if (!string.IsNullOrEmpty(passwordResetProviderId))
  711. {
  712. providers = providers.Where(i =>
  713. string.Equals(passwordResetProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase))
  714. .ToArray();
  715. }
  716. if (providers.Length == 0)
  717. {
  718. providers = new IPasswordResetProvider[]
  719. {
  720. _defaultPasswordResetProvider
  721. };
  722. }
  723. return providers;
  724. }
  725. private async Task<(IAuthenticationProvider? authenticationProvider, string username, bool success)> AuthenticateLocalUser(
  726. string username,
  727. string password,
  728. User? user,
  729. string remoteEndPoint)
  730. {
  731. bool success = false;
  732. IAuthenticationProvider? authenticationProvider = null;
  733. foreach (var provider in GetAuthenticationProviders(user))
  734. {
  735. var providerAuthResult =
  736. await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  737. var updatedUsername = providerAuthResult.username;
  738. success = providerAuthResult.success;
  739. if (success)
  740. {
  741. authenticationProvider = provider;
  742. username = updatedUsername;
  743. break;
  744. }
  745. }
  746. if (!success
  747. && _networkManager.IsInLocalNetwork(remoteEndPoint)
  748. && user?.EnableLocalPassword == true
  749. && !string.IsNullOrEmpty(user.EasyPassword))
  750. {
  751. // Check easy password
  752. var passwordHash = PasswordHash.Parse(user.EasyPassword);
  753. var hash = _cryptoProvider.ComputeHash(
  754. passwordHash.Id,
  755. Encoding.UTF8.GetBytes(password),
  756. passwordHash.Salt.ToArray());
  757. success = passwordHash.Hash.SequenceEqual(hash);
  758. }
  759. return (authenticationProvider, username, success);
  760. }
  761. private async Task<(string username, bool success)> AuthenticateWithProvider(
  762. IAuthenticationProvider provider,
  763. string username,
  764. string password,
  765. User? resolvedUser)
  766. {
  767. try
  768. {
  769. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  770. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  771. : await provider.Authenticate(username, password).ConfigureAwait(false);
  772. if (authenticationResult.Username != username)
  773. {
  774. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  775. username = authenticationResult.Username;
  776. }
  777. return (username, true);
  778. }
  779. catch (AuthenticationException ex)
  780. {
  781. _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
  782. return (username, false);
  783. }
  784. }
  785. private async Task IncrementInvalidLoginAttemptCount(User user)
  786. {
  787. user.InvalidLoginAttemptCount++;
  788. int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
  789. if (maxInvalidLogins.HasValue && user.InvalidLoginAttemptCount >= maxInvalidLogins)
  790. {
  791. user.SetPermission(PermissionKind.IsDisabled, true);
  792. await _eventManager.PublishAsync(new UserLockedOutEventArgs(user)).ConfigureAwait(false);
  793. _logger.LogWarning(
  794. "Disabling user {Username} due to {Attempts} unsuccessful login attempts.",
  795. user.Username,
  796. user.InvalidLoginAttemptCount);
  797. }
  798. await UpdateUserAsync(user).ConfigureAwait(false);
  799. }
  800. }
  801. }