UserManager.cs 39 KB

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