UserManager.cs 39 KB

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