2
0

UserManager.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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) || !IsValidUsername(defaultName))
  523. {
  524. defaultName = "MyJellyfinUser";
  525. }
  526. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  527. var newUser = CreateUser(defaultName);
  528. newUser.SetPermission(PermissionKind.IsAdministrator, true);
  529. newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
  530. newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
  531. dbContext.Users.Update(newUser);
  532. dbContext.SaveChanges();
  533. }
  534. /// <inheritdoc/>
  535. public NameIdPair[] GetAuthenticationProviders()
  536. {
  537. return _authenticationProviders
  538. .Where(provider => provider.IsEnabled)
  539. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  540. .ThenBy(i => i.Name)
  541. .Select(i => new NameIdPair
  542. {
  543. Name = i.Name,
  544. Id = i.GetType().FullName
  545. })
  546. .ToArray();
  547. }
  548. /// <inheritdoc/>
  549. public NameIdPair[] GetPasswordResetProviders()
  550. {
  551. return _passwordResetProviders
  552. .Where(provider => provider.IsEnabled)
  553. .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
  554. .ThenBy(i => i.Name)
  555. .Select(i => new NameIdPair
  556. {
  557. Name = i.Name,
  558. Id = i.GetType().FullName
  559. })
  560. .ToArray();
  561. }
  562. /// <inheritdoc/>
  563. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  564. {
  565. using var dbContext = _dbProvider.CreateContext();
  566. var user = dbContext.Users
  567. .Include(u => u.Permissions)
  568. .Include(u => u.Preferences)
  569. .Include(u => u.AccessSchedules)
  570. .Include(u => u.ProfileImage)
  571. .FirstOrDefault(u => u.Id == userId)
  572. ?? throw new ArgumentException("No user exists with given Id!");
  573. user.SubtitleMode = config.SubtitleMode;
  574. user.HidePlayedInLatest = config.HidePlayedInLatest;
  575. user.EnableLocalPassword = config.EnableLocalPassword;
  576. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  577. user.DisplayCollectionsView = config.DisplayCollectionsView;
  578. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  579. user.AudioLanguagePreference = config.AudioLanguagePreference;
  580. user.RememberAudioSelections = config.RememberAudioSelections;
  581. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  582. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  583. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  584. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  585. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  586. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  587. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  588. dbContext.Update(user);
  589. dbContext.SaveChanges();
  590. }
  591. /// <inheritdoc/>
  592. public void UpdatePolicy(Guid userId, UserPolicy policy)
  593. {
  594. using var dbContext = _dbProvider.CreateContext();
  595. var user = dbContext.Users
  596. .Include(u => u.Permissions)
  597. .Include(u => u.Preferences)
  598. .Include(u => u.AccessSchedules)
  599. .Include(u => u.ProfileImage)
  600. .FirstOrDefault(u => u.Id == userId)
  601. ?? throw new ArgumentException("No user exists with given Id!");
  602. // The default number of login attempts is 3, but for some god forsaken reason it's sent to the server as "0"
  603. int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
  604. {
  605. -1 => null,
  606. 0 => 3,
  607. _ => policy.LoginAttemptsBeforeLockout
  608. };
  609. user.MaxParentalAgeRating = policy.MaxParentalRating;
  610. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  611. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  612. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  613. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  614. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  615. user.LoginAttemptsBeforeLockout = maxLoginAttempts;
  616. user.SyncPlayAccess = policy.SyncPlayAccess;
  617. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  618. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  619. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  620. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  621. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  622. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  623. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  624. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  625. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  626. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  627. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  628. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  629. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  630. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  631. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  632. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  633. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  634. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  635. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  636. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  637. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  638. user.AccessSchedules.Clear();
  639. foreach (var policyAccessSchedule in policy.AccessSchedules)
  640. {
  641. user.AccessSchedules.Add(policyAccessSchedule);
  642. }
  643. // TODO: fix this at some point
  644. user.SetPreference(
  645. PreferenceKind.BlockUnratedItems,
  646. policy.BlockUnratedItems?.Select(i => i.ToString()).ToArray() ?? Array.Empty<string>());
  647. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  648. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  649. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  650. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  651. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  652. dbContext.Update(user);
  653. dbContext.SaveChanges();
  654. }
  655. /// <inheritdoc/>
  656. public void ClearProfileImage(User user)
  657. {
  658. using var dbContext = _dbProvider.CreateContext();
  659. dbContext.Remove(user.ProfileImage);
  660. dbContext.SaveChanges();
  661. }
  662. private static bool IsValidUsername(string name)
  663. {
  664. // This is some regex that matches only on unicode "word" characters, as well as -, _ and @
  665. // In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
  666. // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), periods (.) and spaces ( )
  667. return Regex.IsMatch(name, @"^[\w\ \-'._@]*$");
  668. }
  669. private IAuthenticationProvider GetAuthenticationProvider(User user)
  670. {
  671. return GetAuthenticationProviders(user)[0];
  672. }
  673. private IPasswordResetProvider GetPasswordResetProvider(User user)
  674. {
  675. return GetPasswordResetProviders(user)[0];
  676. }
  677. private IList<IAuthenticationProvider> GetAuthenticationProviders(User? user)
  678. {
  679. var authenticationProviderId = user?.AuthenticationProviderId;
  680. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();
  681. if (!string.IsNullOrEmpty(authenticationProviderId))
  682. {
  683. providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
  684. }
  685. if (providers.Count == 0)
  686. {
  687. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  688. _logger.LogWarning(
  689. "User {Username} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
  690. user?.Username,
  691. user?.AuthenticationProviderId);
  692. providers = new List<IAuthenticationProvider>
  693. {
  694. _invalidAuthProvider
  695. };
  696. }
  697. return providers;
  698. }
  699. private IList<IPasswordResetProvider> GetPasswordResetProviders(User user)
  700. {
  701. var passwordResetProviderId = user?.PasswordResetProviderId;
  702. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  703. if (!string.IsNullOrEmpty(passwordResetProviderId))
  704. {
  705. providers = providers.Where(i =>
  706. string.Equals(passwordResetProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase))
  707. .ToArray();
  708. }
  709. if (providers.Length == 0)
  710. {
  711. providers = new IPasswordResetProvider[]
  712. {
  713. _defaultPasswordResetProvider
  714. };
  715. }
  716. return providers;
  717. }
  718. private async Task<(IAuthenticationProvider? authenticationProvider, string username, bool success)> AuthenticateLocalUser(
  719. string username,
  720. string password,
  721. User? user,
  722. string remoteEndPoint)
  723. {
  724. bool success = false;
  725. IAuthenticationProvider? authenticationProvider = null;
  726. foreach (var provider in GetAuthenticationProviders(user))
  727. {
  728. var providerAuthResult =
  729. await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  730. var updatedUsername = providerAuthResult.username;
  731. success = providerAuthResult.success;
  732. if (success)
  733. {
  734. authenticationProvider = provider;
  735. username = updatedUsername;
  736. break;
  737. }
  738. }
  739. if (!success
  740. && _networkManager.IsInLocalNetwork(remoteEndPoint)
  741. && user?.EnableLocalPassword == true
  742. && !string.IsNullOrEmpty(user.EasyPassword))
  743. {
  744. // Check easy password
  745. var passwordHash = PasswordHash.Parse(user.EasyPassword);
  746. var hash = _cryptoProvider.ComputeHash(
  747. passwordHash.Id,
  748. Encoding.UTF8.GetBytes(password),
  749. passwordHash.Salt.ToArray());
  750. success = passwordHash.Hash.SequenceEqual(hash);
  751. }
  752. return (authenticationProvider, username, success);
  753. }
  754. private async Task<(string username, bool success)> AuthenticateWithProvider(
  755. IAuthenticationProvider provider,
  756. string username,
  757. string password,
  758. User? resolvedUser)
  759. {
  760. try
  761. {
  762. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  763. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  764. : await provider.Authenticate(username, password).ConfigureAwait(false);
  765. if (authenticationResult.Username != username)
  766. {
  767. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  768. username = authenticationResult.Username;
  769. }
  770. return (username, true);
  771. }
  772. catch (AuthenticationException ex)
  773. {
  774. _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
  775. return (username, false);
  776. }
  777. }
  778. private void IncrementInvalidLoginAttemptCount(User user)
  779. {
  780. user.InvalidLoginAttemptCount++;
  781. int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
  782. if (maxInvalidLogins.HasValue && user.InvalidLoginAttemptCount >= maxInvalidLogins)
  783. {
  784. user.SetPermission(PermissionKind.IsDisabled, true);
  785. OnUserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
  786. _logger.LogWarning(
  787. "Disabling user {Username} due to {Attempts} unsuccessful login attempts.",
  788. user.Username,
  789. user.InvalidLoginAttemptCount);
  790. }
  791. UpdateUser(user);
  792. }
  793. }
  794. }