UserManager.cs 40 KB

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