UserManager.cs 39 KB

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