2
0

UserManager.cs 39 KB

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