UserManager.cs 39 KB

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