UserManager.cs 39 KB

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