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