UserManager.cs 39 KB

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