UserManager.cs 39 KB

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