UserManager.cs 39 KB

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