UserManager.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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 MediaBrowser.Common;
  13. using MediaBrowser.Common.Cryptography;
  14. using MediaBrowser.Common.Extensions;
  15. using MediaBrowser.Common.Net;
  16. using MediaBrowser.Controller.Authentication;
  17. using MediaBrowser.Controller.Drawing;
  18. using MediaBrowser.Controller.Library;
  19. using MediaBrowser.Controller.Net;
  20. using MediaBrowser.Model.Configuration;
  21. using MediaBrowser.Model.Cryptography;
  22. using MediaBrowser.Model.Dto;
  23. using MediaBrowser.Model.Events;
  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 ICryptoProvider _cryptoProvider;
  36. private readonly INetworkManager _networkManager;
  37. private readonly IApplicationHost _appHost;
  38. private readonly IImageProcessor _imageProcessor;
  39. private readonly ILogger<UserManager> _logger;
  40. private readonly IReadOnlyCollection<IPasswordResetProvider> _passwordResetProviders;
  41. private readonly IReadOnlyCollection<IAuthenticationProvider> _authenticationProviders;
  42. private readonly InvalidAuthProvider _invalidAuthProvider;
  43. private readonly DefaultAuthenticationProvider _defaultAuthenticationProvider;
  44. private readonly DefaultPasswordResetProvider _defaultPasswordResetProvider;
  45. /// <summary>
  46. /// Initializes a new instance of the <see cref="UserManager"/> class.
  47. /// </summary>
  48. /// <param name="dbProvider">The database provider.</param>
  49. /// <param name="cryptoProvider">The cryptography provider.</param>
  50. /// <param name="networkManager">The network manager.</param>
  51. /// <param name="appHost">The application host.</param>
  52. /// <param name="imageProcessor">The image processor.</param>
  53. /// <param name="logger">The logger.</param>
  54. public UserManager(
  55. JellyfinDbProvider dbProvider,
  56. ICryptoProvider cryptoProvider,
  57. INetworkManager networkManager,
  58. IApplicationHost appHost,
  59. IImageProcessor imageProcessor,
  60. ILogger<UserManager> logger)
  61. {
  62. _dbProvider = dbProvider;
  63. _cryptoProvider = cryptoProvider;
  64. _networkManager = networkManager;
  65. _appHost = appHost;
  66. _imageProcessor = imageProcessor;
  67. _logger = logger;
  68. _passwordResetProviders = appHost.GetExports<IPasswordResetProvider>();
  69. _authenticationProviders = appHost.GetExports<IAuthenticationProvider>();
  70. _invalidAuthProvider = _authenticationProviders.OfType<InvalidAuthProvider>().First();
  71. _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
  72. _defaultPasswordResetProvider = _passwordResetProviders.OfType<DefaultPasswordResetProvider>().First();
  73. }
  74. /// <inheritdoc/>
  75. public event EventHandler<GenericEventArgs<User>>? OnUserPasswordChanged;
  76. /// <inheritdoc/>
  77. public event EventHandler<GenericEventArgs<User>>? OnUserUpdated;
  78. /// <inheritdoc/>
  79. public event EventHandler<GenericEventArgs<User>>? OnUserCreated;
  80. /// <inheritdoc/>
  81. public event EventHandler<GenericEventArgs<User>>? OnUserDeleted;
  82. /// <inheritdoc/>
  83. public event EventHandler<GenericEventArgs<User>>? OnUserLockedOut;
  84. /// <inheritdoc/>
  85. public IEnumerable<User> Users
  86. {
  87. get
  88. {
  89. using var dbContext = _dbProvider.CreateContext();
  90. return dbContext.Users
  91. .Include(user => user.Permissions)
  92. .Include(user => user.Preferences)
  93. .Include(user => user.AccessSchedules)
  94. .Include(user => user.ProfileImage)
  95. .ToList();
  96. }
  97. }
  98. /// <inheritdoc/>
  99. public IEnumerable<Guid> UsersIds
  100. {
  101. get
  102. {
  103. using var dbContext = _dbProvider.CreateContext();
  104. return dbContext.Users
  105. .Select(user => user.Id)
  106. .ToList();
  107. }
  108. }
  109. /// <inheritdoc/>
  110. public User? GetUserById(Guid id)
  111. {
  112. if (id == Guid.Empty)
  113. {
  114. throw new ArgumentException("Guid can't be empty", nameof(id));
  115. }
  116. using var dbContext = _dbProvider.CreateContext();
  117. return dbContext.Users
  118. .Include(user => user.Permissions)
  119. .Include(user => user.Preferences)
  120. .Include(user => user.AccessSchedules)
  121. .Include(user => user.ProfileImage)
  122. .FirstOrDefault(user => user.Id == id);
  123. }
  124. /// <inheritdoc/>
  125. public User? GetUserByName(string name)
  126. {
  127. if (string.IsNullOrWhiteSpace(name))
  128. {
  129. throw new ArgumentException("Invalid username", nameof(name));
  130. }
  131. using var dbContext = _dbProvider.CreateContext();
  132. return dbContext.Users
  133. .Include(user => user.Permissions)
  134. .Include(user => user.Preferences)
  135. .Include(user => user.AccessSchedules)
  136. .Include(user => user.ProfileImage)
  137. .AsEnumerable()
  138. .FirstOrDefault(u => string.Equals(u.Username, name, StringComparison.OrdinalIgnoreCase));
  139. }
  140. /// <inheritdoc/>
  141. public async Task RenameUser(User user, string newName)
  142. {
  143. if (user == null)
  144. {
  145. throw new ArgumentNullException(nameof(user));
  146. }
  147. if (string.IsNullOrWhiteSpace(newName))
  148. {
  149. throw new ArgumentException("Invalid username", nameof(newName));
  150. }
  151. if (user.Username.Equals(newName, StringComparison.Ordinal))
  152. {
  153. throw new ArgumentException("The new and old names must be different.");
  154. }
  155. if (Users.Any(u => u.Id != user.Id && u.Username.Equals(newName, StringComparison.Ordinal)))
  156. {
  157. throw new ArgumentException(string.Format(
  158. CultureInfo.InvariantCulture,
  159. "A user with the name '{0}' already exists.",
  160. newName));
  161. }
  162. user.Username = newName;
  163. await UpdateUserAsync(user).ConfigureAwait(false);
  164. OnUserUpdated?.Invoke(this, new GenericEventArgs<User>(user));
  165. }
  166. /// <inheritdoc/>
  167. public void UpdateUser(User user)
  168. {
  169. using var dbContext = _dbProvider.CreateContext();
  170. dbContext.Users.Update(user);
  171. dbContext.SaveChanges();
  172. }
  173. /// <inheritdoc/>
  174. public async Task UpdateUserAsync(User user)
  175. {
  176. await using var dbContext = _dbProvider.CreateContext();
  177. dbContext.Users.Update(user);
  178. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  179. }
  180. /// <inheritdoc/>
  181. public User CreateUser(string name)
  182. {
  183. if (!IsValidUsername(name))
  184. {
  185. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  186. }
  187. using var dbContext = _dbProvider.CreateContext();
  188. // TODO: Remove after user item data is migrated.
  189. var max = dbContext.Users.Any() ? dbContext.Users.Select(u => u.InternalId).Max() : 0;
  190. var newUser = new User(
  191. name,
  192. _defaultAuthenticationProvider.GetType().FullName,
  193. _defaultPasswordResetProvider.GetType().FullName)
  194. {
  195. InternalId = max + 1
  196. };
  197. dbContext.Users.Add(newUser);
  198. dbContext.SaveChanges();
  199. OnUserCreated?.Invoke(this, new GenericEventArgs<User>(newUser));
  200. return newUser;
  201. }
  202. /// <inheritdoc/>
  203. public void DeleteUser(Guid userId)
  204. {
  205. using var dbContext = _dbProvider.CreateContext();
  206. var user = dbContext.Users
  207. .Include(u => u.Permissions)
  208. .Include(u => u.Preferences)
  209. .Include(u => u.AccessSchedules)
  210. .Include(u => u.ProfileImage)
  211. .FirstOrDefault(u => u.Id == userId);
  212. if (user == null)
  213. {
  214. throw new ResourceNotFoundException(nameof(userId));
  215. }
  216. if (dbContext.Users.Find(user.Id) == null)
  217. {
  218. throw new ArgumentException(string.Format(
  219. CultureInfo.InvariantCulture,
  220. "The user cannot be deleted because there is no user with the Name {0} and Id {1}.",
  221. user.Username,
  222. user.Id));
  223. }
  224. if (dbContext.Users.Count() == 1)
  225. {
  226. throw new InvalidOperationException(string.Format(
  227. CultureInfo.InvariantCulture,
  228. "The user '{0}' cannot be deleted because there must be at least one user in the system.",
  229. user.Username));
  230. }
  231. if (user.HasPermission(PermissionKind.IsAdministrator)
  232. && Users.Count(i => i.HasPermission(PermissionKind.IsAdministrator)) == 1)
  233. {
  234. throw new ArgumentException(
  235. string.Format(
  236. CultureInfo.InvariantCulture,
  237. "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
  238. user.Username),
  239. nameof(userId));
  240. }
  241. // Clear all entities related to the user from the database.
  242. if (user.ProfileImage != null)
  243. {
  244. dbContext.Remove(user.ProfileImage);
  245. }
  246. dbContext.RemoveRange(user.Permissions);
  247. dbContext.RemoveRange(user.Preferences);
  248. dbContext.RemoveRange(user.AccessSchedules);
  249. dbContext.Users.Remove(user);
  250. dbContext.SaveChanges();
  251. OnUserDeleted?.Invoke(this, new GenericEventArgs<User>(user));
  252. }
  253. /// <inheritdoc/>
  254. public Task ResetPassword(User user)
  255. {
  256. return ChangePassword(user, string.Empty);
  257. }
  258. /// <inheritdoc/>
  259. public void ResetEasyPassword(User user)
  260. {
  261. ChangeEasyPassword(user, string.Empty, null);
  262. }
  263. /// <inheritdoc/>
  264. public async Task ChangePassword(User user, string newPassword)
  265. {
  266. if (user == null)
  267. {
  268. throw new ArgumentNullException(nameof(user));
  269. }
  270. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  271. await UpdateUserAsync(user).ConfigureAwait(false);
  272. OnUserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  273. }
  274. /// <inheritdoc/>
  275. public void ChangeEasyPassword(User user, string newPassword, string? newPasswordSha1)
  276. {
  277. if (newPassword != null)
  278. {
  279. newPasswordSha1 = _cryptoProvider.CreatePasswordHash(newPassword).ToString();
  280. }
  281. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  282. {
  283. throw new ArgumentNullException(nameof(newPasswordSha1));
  284. }
  285. user.EasyPassword = newPasswordSha1;
  286. UpdateUser(user);
  287. OnUserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  288. }
  289. /// <inheritdoc/>
  290. public UserDto GetUserDto(User user, string? remoteEndPoint = null)
  291. {
  292. var hasPassword = GetAuthenticationProvider(user).HasPassword(user);
  293. return new UserDto
  294. {
  295. Name = user.Username,
  296. Id = user.Id,
  297. ServerId = _appHost.SystemId,
  298. HasPassword = hasPassword,
  299. HasConfiguredPassword = hasPassword,
  300. HasConfiguredEasyPassword = !string.IsNullOrEmpty(user.EasyPassword),
  301. EnableAutoLogin = user.EnableAutoLogin,
  302. LastLoginDate = user.LastLoginDate,
  303. LastActivityDate = user.LastActivityDate,
  304. PrimaryImageTag = user.ProfileImage != null ? _imageProcessor.GetImageCacheTag(user) : null,
  305. Configuration = new UserConfiguration
  306. {
  307. SubtitleMode = user.SubtitleMode,
  308. HidePlayedInLatest = user.HidePlayedInLatest,
  309. EnableLocalPassword = user.EnableLocalPassword,
  310. PlayDefaultAudioTrack = user.PlayDefaultAudioTrack,
  311. DisplayCollectionsView = user.DisplayCollectionsView,
  312. DisplayMissingEpisodes = user.DisplayMissingEpisodes,
  313. AudioLanguagePreference = user.AudioLanguagePreference,
  314. RememberAudioSelections = user.RememberAudioSelections,
  315. EnableNextEpisodeAutoPlay = user.EnableNextEpisodeAutoPlay,
  316. RememberSubtitleSelections = user.RememberSubtitleSelections,
  317. SubtitleLanguagePreference = user.SubtitleLanguagePreference ?? string.Empty,
  318. OrderedViews = user.GetPreference(PreferenceKind.OrderedViews),
  319. GroupedFolders = user.GetPreference(PreferenceKind.GroupedFolders),
  320. MyMediaExcludes = user.GetPreference(PreferenceKind.MyMediaExcludes),
  321. LatestItemsExcludes = user.GetPreference(PreferenceKind.LatestItemExcludes)
  322. },
  323. Policy = new UserPolicy
  324. {
  325. MaxParentalRating = user.MaxParentalAgeRating,
  326. EnableUserPreferenceAccess = user.EnableUserPreferenceAccess,
  327. RemoteClientBitrateLimit = user.RemoteClientBitrateLimit ?? 0,
  328. AuthenticationProviderId = user.AuthenticationProviderId,
  329. PasswordResetProviderId = user.PasswordResetProviderId,
  330. InvalidLoginAttemptCount = user.InvalidLoginAttemptCount,
  331. LoginAttemptsBeforeLockout = user.LoginAttemptsBeforeLockout ?? -1,
  332. IsAdministrator = user.HasPermission(PermissionKind.IsAdministrator),
  333. IsHidden = user.HasPermission(PermissionKind.IsHidden),
  334. IsDisabled = user.HasPermission(PermissionKind.IsDisabled),
  335. EnableSharedDeviceControl = user.HasPermission(PermissionKind.EnableSharedDeviceControl),
  336. EnableRemoteAccess = user.HasPermission(PermissionKind.EnableRemoteAccess),
  337. EnableLiveTvManagement = user.HasPermission(PermissionKind.EnableLiveTvManagement),
  338. EnableLiveTvAccess = user.HasPermission(PermissionKind.EnableLiveTvAccess),
  339. EnableMediaPlayback = user.HasPermission(PermissionKind.EnableMediaPlayback),
  340. EnableAudioPlaybackTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding),
  341. EnableVideoPlaybackTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding),
  342. EnableContentDeletion = user.HasPermission(PermissionKind.EnableContentDeletion),
  343. EnableContentDownloading = user.HasPermission(PermissionKind.EnableContentDownloading),
  344. EnableSyncTranscoding = user.HasPermission(PermissionKind.EnableSyncTranscoding),
  345. EnableMediaConversion = user.HasPermission(PermissionKind.EnableMediaConversion),
  346. EnableAllChannels = user.HasPermission(PermissionKind.EnableAllChannels),
  347. EnableAllDevices = user.HasPermission(PermissionKind.EnableAllDevices),
  348. EnableAllFolders = user.HasPermission(PermissionKind.EnableAllFolders),
  349. EnableRemoteControlOfOtherUsers = user.HasPermission(PermissionKind.EnableRemoteControlOfOtherUsers),
  350. EnablePlaybackRemuxing = user.HasPermission(PermissionKind.EnablePlaybackRemuxing),
  351. ForceRemoteSourceTranscoding = user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding),
  352. EnablePublicSharing = user.HasPermission(PermissionKind.EnablePublicSharing),
  353. AccessSchedules = user.AccessSchedules.ToArray(),
  354. BlockedTags = user.GetPreference(PreferenceKind.BlockedTags),
  355. EnabledChannels = user.GetPreference(PreferenceKind.EnabledChannels),
  356. EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices),
  357. EnabledFolders = user.GetPreference(PreferenceKind.EnabledFolders),
  358. EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders),
  359. SyncPlayAccess = user.SyncPlayAccess,
  360. BlockedChannels = user.GetPreference(PreferenceKind.BlockedChannels),
  361. BlockedMediaFolders = user.GetPreference(PreferenceKind.BlockedMediaFolders),
  362. BlockUnratedItems = user.GetPreference(PreferenceKind.BlockUnratedItems).Select(Enum.Parse<UnratedItem>).ToArray()
  363. }
  364. };
  365. }
  366. /// <inheritdoc/>
  367. public async Task<User?> AuthenticateUser(
  368. string username,
  369. string password,
  370. string passwordSha1,
  371. string remoteEndPoint,
  372. bool isUserSession)
  373. {
  374. if (string.IsNullOrWhiteSpace(username))
  375. {
  376. _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
  377. throw new ArgumentNullException(nameof(username));
  378. }
  379. var user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  380. bool success;
  381. IAuthenticationProvider? authenticationProvider;
  382. if (user != null)
  383. {
  384. var authResult = await AuthenticateLocalUser(username, password, user, remoteEndPoint)
  385. .ConfigureAwait(false);
  386. authenticationProvider = authResult.authenticationProvider;
  387. success = authResult.success;
  388. }
  389. else
  390. {
  391. var authResult = await AuthenticateLocalUser(username, password, null, remoteEndPoint)
  392. .ConfigureAwait(false);
  393. authenticationProvider = authResult.authenticationProvider;
  394. string updatedUsername = authResult.username;
  395. success = authResult.success;
  396. if (success
  397. && authenticationProvider != null
  398. && !(authenticationProvider is DefaultAuthenticationProvider))
  399. {
  400. // Trust the username returned by the authentication provider
  401. username = updatedUsername;
  402. // Search the database for the user again
  403. // the authentication provider might have created it
  404. user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  405. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy)
  406. {
  407. UpdatePolicy(user.Id, hasNewUserPolicy.GetNewUserPolicy());
  408. await UpdateUserAsync(user).ConfigureAwait(false);
  409. }
  410. }
  411. }
  412. if (success && user != null && authenticationProvider != null)
  413. {
  414. var providerId = authenticationProvider.GetType().FullName;
  415. if (!string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  416. {
  417. user.AuthenticationProviderId = providerId;
  418. await UpdateUserAsync(user).ConfigureAwait(false);
  419. }
  420. }
  421. if (user == null)
  422. {
  423. _logger.LogInformation(
  424. "Authentication request for {UserName} has been denied (IP: {IP}).",
  425. username,
  426. remoteEndPoint);
  427. throw new AuthenticationException("Invalid username or password entered.");
  428. }
  429. if (user.HasPermission(PermissionKind.IsDisabled))
  430. {
  431. _logger.LogInformation(
  432. "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
  433. username,
  434. remoteEndPoint);
  435. throw new SecurityException(
  436. $"The {user.Username} account is currently disabled. Please consult with your administrator.");
  437. }
  438. if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
  439. !_networkManager.IsInLocalNetwork(remoteEndPoint))
  440. {
  441. _logger.LogInformation(
  442. "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
  443. username,
  444. remoteEndPoint);
  445. throw new SecurityException("Forbidden.");
  446. }
  447. if (!user.IsParentalScheduleAllowed())
  448. {
  449. _logger.LogInformation(
  450. "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
  451. username,
  452. remoteEndPoint);
  453. throw new SecurityException("User is not allowed access at this time.");
  454. }
  455. // Update LastActivityDate and LastLoginDate, then save
  456. if (success)
  457. {
  458. if (isUserSession)
  459. {
  460. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  461. }
  462. user.InvalidLoginAttemptCount = 0;
  463. await UpdateUserAsync(user).ConfigureAwait(false);
  464. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
  465. }
  466. else
  467. {
  468. await IncrementInvalidLoginAttemptCount(user).ConfigureAwait(false);
  469. _logger.LogInformation(
  470. "Authentication request for {UserName} has been denied (IP: {IP}).",
  471. user.Username,
  472. remoteEndPoint);
  473. }
  474. return success ? user : null;
  475. }
  476. /// <inheritdoc/>
  477. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  478. {
  479. var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
  480. if (user != null && isInNetwork)
  481. {
  482. var passwordResetProvider = GetPasswordResetProvider(user);
  483. var result = await passwordResetProvider
  484. .StartForgotPasswordProcess(user, isInNetwork)
  485. .ConfigureAwait(false);
  486. await UpdateUserAsync(user).ConfigureAwait(false);
  487. return result;
  488. }
  489. return new ForgotPasswordResult
  490. {
  491. Action = ForgotPasswordAction.InNetworkRequired,
  492. PinFile = string.Empty
  493. };
  494. }
  495. /// <inheritdoc/>
  496. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  497. {
  498. foreach (var provider in _passwordResetProviders)
  499. {
  500. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  501. if (result.Success)
  502. {
  503. return result;
  504. }
  505. }
  506. return new PinRedeemResult
  507. {
  508. Success = false,
  509. UsersReset = Array.Empty<string>()
  510. };
  511. }
  512. /// <inheritdoc />
  513. public void Initialize()
  514. {
  515. // TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
  516. using var dbContext = _dbProvider.CreateContext();
  517. if (dbContext.Users.Any())
  518. {
  519. return;
  520. }
  521. var defaultName = Environment.UserName;
  522. if (string.IsNullOrWhiteSpace(defaultName))
  523. {
  524. defaultName = "MyJellyfinUser";
  525. }
  526. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  527. if (!IsValidUsername(defaultName))
  528. {
  529. throw new ArgumentException("Provided username is not valid!", defaultName);
  530. }
  531. var newUser = CreateUser(defaultName);
  532. newUser.SetPermission(PermissionKind.IsAdministrator, true);
  533. newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
  534. newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
  535. dbContext.Users.Update(newUser);
  536. dbContext.SaveChanges();
  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 ('), and periods (.)
  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. OnUserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
  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. }