UserManager.cs 39 KB

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