UserManager.cs 39 KB

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