UserManager.cs 39 KB

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