2
0

UserManager.cs 38 KB

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