UserManager.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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. await using var dbContext = _dbProvider.CreateContext();
  130. if (await dbContext.Users
  131. .AsQueryable()
  132. .Where(u => u.Username == newName && u.Id != user.Id)
  133. .AnyAsync()
  134. .ConfigureAwait(false))
  135. {
  136. throw new ArgumentException(string.Format(
  137. CultureInfo.InvariantCulture,
  138. "A user with the name '{0}' already exists.",
  139. newName));
  140. }
  141. user.Username = newName;
  142. await UpdateUserAsync(user).ConfigureAwait(false);
  143. OnUserUpdated?.Invoke(this, new GenericEventArgs<User>(user));
  144. }
  145. /// <inheritdoc/>
  146. public void UpdateUser(User user)
  147. {
  148. using var dbContext = _dbProvider.CreateContext();
  149. dbContext.Users.Update(user);
  150. _users[user.Id] = user;
  151. dbContext.SaveChanges();
  152. }
  153. /// <inheritdoc/>
  154. public async Task UpdateUserAsync(User user)
  155. {
  156. await using var dbContext = _dbProvider.CreateContext();
  157. dbContext.Users.Update(user);
  158. _users[user.Id] = user;
  159. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  160. }
  161. internal async Task<User> CreateUserInternalAsync(string name, JellyfinDb dbContext)
  162. {
  163. // TODO: Remove after user item data is migrated.
  164. var max = await dbContext.Users.AsQueryable().AnyAsync().ConfigureAwait(false)
  165. ? await dbContext.Users.AsQueryable().Select(u => u.InternalId).MaxAsync().ConfigureAwait(false)
  166. : 0;
  167. var user = new User(
  168. name,
  169. _defaultAuthenticationProvider.GetType().FullName!,
  170. _defaultPasswordResetProvider.GetType().FullName!)
  171. {
  172. InternalId = max + 1
  173. };
  174. user.AddDefaultPermissions();
  175. user.AddDefaultPreferences();
  176. _users.Add(user.Id, user);
  177. return user;
  178. }
  179. /// <inheritdoc/>
  180. public async Task<User> CreateUserAsync(string name)
  181. {
  182. ThrowIfInvalidUsername(name);
  183. if (Users.Any(u => u.Username.Equals(name, StringComparison.OrdinalIgnoreCase)))
  184. {
  185. throw new ArgumentException(string.Format(
  186. CultureInfo.InvariantCulture,
  187. "A user with the name '{0}' already exists.",
  188. name));
  189. }
  190. await using var dbContext = _dbProvider.CreateContext();
  191. var newUser = await CreateUserInternalAsync(name, dbContext).ConfigureAwait(false);
  192. dbContext.Users.Add(newUser);
  193. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  194. await _eventManager.PublishAsync(new UserCreatedEventArgs(newUser)).ConfigureAwait(false);
  195. return newUser;
  196. }
  197. /// <inheritdoc/>
  198. public async Task DeleteUserAsync(Guid userId)
  199. {
  200. if (!_users.TryGetValue(userId, out var user))
  201. {
  202. throw new ResourceNotFoundException(nameof(userId));
  203. }
  204. if (_users.Count == 1)
  205. {
  206. throw new InvalidOperationException(string.Format(
  207. CultureInfo.InvariantCulture,
  208. "The user '{0}' cannot be deleted because there must be at least one user in the system.",
  209. user.Username));
  210. }
  211. if (user.HasPermission(PermissionKind.IsAdministrator)
  212. && Users.Count(i => i.HasPermission(PermissionKind.IsAdministrator)) == 1)
  213. {
  214. throw new ArgumentException(
  215. string.Format(
  216. CultureInfo.InvariantCulture,
  217. "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
  218. user.Username),
  219. nameof(userId));
  220. }
  221. await using var dbContext = _dbProvider.CreateContext();
  222. dbContext.Users.Remove(user);
  223. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  224. _users.Remove(userId);
  225. await _eventManager.PublishAsync(new UserDeletedEventArgs(user)).ConfigureAwait(false);
  226. }
  227. /// <inheritdoc/>
  228. public Task ResetPassword(User user)
  229. {
  230. return ChangePassword(user, string.Empty);
  231. }
  232. /// <inheritdoc/>
  233. public void ResetEasyPassword(User user)
  234. {
  235. ChangeEasyPassword(user, string.Empty, null);
  236. }
  237. /// <inheritdoc/>
  238. public async Task ChangePassword(User user, string newPassword)
  239. {
  240. if (user == null)
  241. {
  242. throw new ArgumentNullException(nameof(user));
  243. }
  244. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  245. await UpdateUserAsync(user).ConfigureAwait(false);
  246. await _eventManager.PublishAsync(new UserPasswordChangedEventArgs(user)).ConfigureAwait(false);
  247. }
  248. /// <inheritdoc/>
  249. public void ChangeEasyPassword(User user, string newPassword, string? newPasswordSha1)
  250. {
  251. if (newPassword != null)
  252. {
  253. newPasswordSha1 = _cryptoProvider.CreatePasswordHash(newPassword).ToString();
  254. }
  255. if (string.IsNullOrWhiteSpace(newPasswordSha1))
  256. {
  257. throw new ArgumentNullException(nameof(newPasswordSha1));
  258. }
  259. user.EasyPassword = newPasswordSha1;
  260. UpdateUser(user);
  261. _eventManager.Publish(new UserPasswordChangedEventArgs(user));
  262. }
  263. /// <inheritdoc/>
  264. public UserDto GetUserDto(User user, string? remoteEndPoint = null)
  265. {
  266. var hasPassword = GetAuthenticationProvider(user).HasPassword(user);
  267. return new UserDto
  268. {
  269. Name = user.Username,
  270. Id = user.Id,
  271. ServerId = _appHost.SystemId,
  272. HasPassword = hasPassword,
  273. HasConfiguredPassword = hasPassword,
  274. HasConfiguredEasyPassword = !string.IsNullOrEmpty(user.EasyPassword),
  275. EnableAutoLogin = user.EnableAutoLogin,
  276. LastLoginDate = user.LastLoginDate,
  277. LastActivityDate = user.LastActivityDate,
  278. PrimaryImageTag = user.ProfileImage != null ? _imageProcessor.GetImageCacheTag(user) : null,
  279. Configuration = new UserConfiguration
  280. {
  281. SubtitleMode = user.SubtitleMode,
  282. HidePlayedInLatest = user.HidePlayedInLatest,
  283. EnableLocalPassword = user.EnableLocalPassword,
  284. PlayDefaultAudioTrack = user.PlayDefaultAudioTrack,
  285. DisplayCollectionsView = user.DisplayCollectionsView,
  286. DisplayMissingEpisodes = user.DisplayMissingEpisodes,
  287. AudioLanguagePreference = user.AudioLanguagePreference,
  288. RememberAudioSelections = user.RememberAudioSelections,
  289. EnableNextEpisodeAutoPlay = user.EnableNextEpisodeAutoPlay,
  290. RememberSubtitleSelections = user.RememberSubtitleSelections,
  291. SubtitleLanguagePreference = user.SubtitleLanguagePreference ?? string.Empty,
  292. OrderedViews = user.GetPreference(PreferenceKind.OrderedViews),
  293. GroupedFolders = user.GetPreference(PreferenceKind.GroupedFolders),
  294. MyMediaExcludes = user.GetPreference(PreferenceKind.MyMediaExcludes),
  295. LatestItemsExcludes = user.GetPreference(PreferenceKind.LatestItemExcludes)
  296. },
  297. Policy = new UserPolicy
  298. {
  299. MaxParentalRating = user.MaxParentalAgeRating,
  300. EnableUserPreferenceAccess = user.EnableUserPreferenceAccess,
  301. RemoteClientBitrateLimit = user.RemoteClientBitrateLimit ?? 0,
  302. AuthenticationProviderId = user.AuthenticationProviderId,
  303. PasswordResetProviderId = user.PasswordResetProviderId,
  304. InvalidLoginAttemptCount = user.InvalidLoginAttemptCount,
  305. LoginAttemptsBeforeLockout = user.LoginAttemptsBeforeLockout ?? -1,
  306. MaxActiveSessions = user.MaxActiveSessions,
  307. IsAdministrator = user.HasPermission(PermissionKind.IsAdministrator),
  308. IsHidden = user.HasPermission(PermissionKind.IsHidden),
  309. IsDisabled = user.HasPermission(PermissionKind.IsDisabled),
  310. EnableSharedDeviceControl = user.HasPermission(PermissionKind.EnableSharedDeviceControl),
  311. EnableRemoteAccess = user.HasPermission(PermissionKind.EnableRemoteAccess),
  312. EnableLiveTvManagement = user.HasPermission(PermissionKind.EnableLiveTvManagement),
  313. EnableLiveTvAccess = user.HasPermission(PermissionKind.EnableLiveTvAccess),
  314. EnableMediaPlayback = user.HasPermission(PermissionKind.EnableMediaPlayback),
  315. EnableAudioPlaybackTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding),
  316. EnableVideoPlaybackTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding),
  317. EnableContentDeletion = user.HasPermission(PermissionKind.EnableContentDeletion),
  318. EnableContentDownloading = user.HasPermission(PermissionKind.EnableContentDownloading),
  319. EnableSyncTranscoding = user.HasPermission(PermissionKind.EnableSyncTranscoding),
  320. EnableMediaConversion = user.HasPermission(PermissionKind.EnableMediaConversion),
  321. EnableAllChannels = user.HasPermission(PermissionKind.EnableAllChannels),
  322. EnableAllDevices = user.HasPermission(PermissionKind.EnableAllDevices),
  323. EnableAllFolders = user.HasPermission(PermissionKind.EnableAllFolders),
  324. EnableRemoteControlOfOtherUsers = user.HasPermission(PermissionKind.EnableRemoteControlOfOtherUsers),
  325. EnablePlaybackRemuxing = user.HasPermission(PermissionKind.EnablePlaybackRemuxing),
  326. ForceRemoteSourceTranscoding = user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding),
  327. EnablePublicSharing = user.HasPermission(PermissionKind.EnablePublicSharing),
  328. AccessSchedules = user.AccessSchedules.ToArray(),
  329. BlockedTags = user.GetPreference(PreferenceKind.BlockedTags),
  330. EnabledChannels = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledChannels),
  331. EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices),
  332. EnabledFolders = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders),
  333. EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders),
  334. SyncPlayAccess = user.SyncPlayAccess,
  335. BlockedChannels = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedChannels),
  336. BlockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders),
  337. BlockUnratedItems = user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems)
  338. }
  339. };
  340. }
  341. /// <inheritdoc/>
  342. public async Task<User?> AuthenticateUser(
  343. string username,
  344. string password,
  345. string passwordSha1,
  346. string remoteEndPoint,
  347. bool isUserSession)
  348. {
  349. if (string.IsNullOrWhiteSpace(username))
  350. {
  351. _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
  352. throw new ArgumentNullException(nameof(username));
  353. }
  354. var user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  355. var authResult = await AuthenticateLocalUser(username, password, user, remoteEndPoint)
  356. .ConfigureAwait(false);
  357. var authenticationProvider = authResult.authenticationProvider;
  358. var success = authResult.success;
  359. if (user == null)
  360. {
  361. string updatedUsername = authResult.username;
  362. if (success
  363. && authenticationProvider != null
  364. && authenticationProvider is not DefaultAuthenticationProvider)
  365. {
  366. // Trust the username returned by the authentication provider
  367. username = updatedUsername;
  368. // Search the database for the user again
  369. // the authentication provider might have created it
  370. user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  371. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy && user != null)
  372. {
  373. await UpdatePolicyAsync(user.Id, hasNewUserPolicy.GetNewUserPolicy()).ConfigureAwait(false);
  374. }
  375. }
  376. }
  377. if (success && user != null && authenticationProvider != null)
  378. {
  379. var providerId = authenticationProvider.GetType().FullName;
  380. if (providerId != null && !string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  381. {
  382. user.AuthenticationProviderId = providerId;
  383. await UpdateUserAsync(user).ConfigureAwait(false);
  384. }
  385. }
  386. if (user == null)
  387. {
  388. _logger.LogInformation(
  389. "Authentication request for {UserName} has been denied (IP: {IP}).",
  390. username,
  391. remoteEndPoint);
  392. throw new AuthenticationException("Invalid username or password entered.");
  393. }
  394. if (user.HasPermission(PermissionKind.IsDisabled))
  395. {
  396. _logger.LogInformation(
  397. "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
  398. username,
  399. remoteEndPoint);
  400. throw new SecurityException(
  401. $"The {user.Username} account is currently disabled. Please consult with your administrator.");
  402. }
  403. if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
  404. !_networkManager.IsInLocalNetwork(remoteEndPoint))
  405. {
  406. _logger.LogInformation(
  407. "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
  408. username,
  409. remoteEndPoint);
  410. throw new SecurityException("Forbidden.");
  411. }
  412. if (!user.IsParentalScheduleAllowed())
  413. {
  414. _logger.LogInformation(
  415. "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
  416. username,
  417. remoteEndPoint);
  418. throw new SecurityException("User is not allowed access at this time.");
  419. }
  420. // Update LastActivityDate and LastLoginDate, then save
  421. if (success)
  422. {
  423. if (isUserSession)
  424. {
  425. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  426. }
  427. user.InvalidLoginAttemptCount = 0;
  428. await UpdateUserAsync(user).ConfigureAwait(false);
  429. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
  430. }
  431. else
  432. {
  433. await IncrementInvalidLoginAttemptCount(user).ConfigureAwait(false);
  434. _logger.LogInformation(
  435. "Authentication request for {UserName} has been denied (IP: {IP}).",
  436. user.Username,
  437. remoteEndPoint);
  438. }
  439. return success ? user : null;
  440. }
  441. /// <inheritdoc/>
  442. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  443. {
  444. var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
  445. if (user != null && isInNetwork)
  446. {
  447. var passwordResetProvider = GetPasswordResetProvider(user);
  448. var result = await passwordResetProvider
  449. .StartForgotPasswordProcess(user, isInNetwork)
  450. .ConfigureAwait(false);
  451. await UpdateUserAsync(user).ConfigureAwait(false);
  452. return result;
  453. }
  454. return new ForgotPasswordResult
  455. {
  456. Action = ForgotPasswordAction.InNetworkRequired,
  457. PinFile = string.Empty
  458. };
  459. }
  460. /// <inheritdoc/>
  461. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  462. {
  463. foreach (var provider in _passwordResetProviders)
  464. {
  465. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  466. if (result.Success)
  467. {
  468. return result;
  469. }
  470. }
  471. return new PinRedeemResult
  472. {
  473. Success = false,
  474. UsersReset = Array.Empty<string>()
  475. };
  476. }
  477. /// <inheritdoc />
  478. public async Task InitializeAsync()
  479. {
  480. // TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
  481. if (_users.Any())
  482. {
  483. return;
  484. }
  485. var defaultName = Environment.UserName;
  486. if (string.IsNullOrWhiteSpace(defaultName) || !IsValidUsername(defaultName))
  487. {
  488. defaultName = "MyJellyfinUser";
  489. }
  490. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  491. await using var dbContext = _dbProvider.CreateContext();
  492. var newUser = await CreateUserInternalAsync(defaultName, dbContext).ConfigureAwait(false);
  493. newUser.SetPermission(PermissionKind.IsAdministrator, true);
  494. newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
  495. newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
  496. dbContext.Users.Add(newUser);
  497. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  498. }
  499. /// <inheritdoc/>
  500. public NameIdPair[] GetAuthenticationProviders()
  501. {
  502. return _authenticationProviders
  503. .Where(provider => provider.IsEnabled)
  504. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  505. .ThenBy(i => i.Name)
  506. .Select(i => new NameIdPair
  507. {
  508. Name = i.Name,
  509. Id = i.GetType().FullName
  510. })
  511. .ToArray();
  512. }
  513. /// <inheritdoc/>
  514. public NameIdPair[] GetPasswordResetProviders()
  515. {
  516. return _passwordResetProviders
  517. .Where(provider => provider.IsEnabled)
  518. .OrderBy(i => i is DefaultPasswordResetProvider ? 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 async Task UpdateConfigurationAsync(Guid userId, UserConfiguration config)
  529. {
  530. await using var dbContext = _dbProvider.CreateContext();
  531. var user = dbContext.Users
  532. .Include(u => u.Permissions)
  533. .Include(u => u.Preferences)
  534. .Include(u => u.AccessSchedules)
  535. .Include(u => u.ProfileImage)
  536. .FirstOrDefault(u => u.Id == userId)
  537. ?? throw new ArgumentException("No user exists with given Id!");
  538. user.SubtitleMode = config.SubtitleMode;
  539. user.HidePlayedInLatest = config.HidePlayedInLatest;
  540. user.EnableLocalPassword = config.EnableLocalPassword;
  541. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  542. user.DisplayCollectionsView = config.DisplayCollectionsView;
  543. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  544. user.AudioLanguagePreference = config.AudioLanguagePreference;
  545. user.RememberAudioSelections = config.RememberAudioSelections;
  546. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  547. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  548. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  549. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  550. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  551. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  552. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  553. dbContext.Update(user);
  554. _users[user.Id] = user;
  555. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  556. }
  557. /// <inheritdoc/>
  558. public async Task UpdatePolicyAsync(Guid userId, UserPolicy policy)
  559. {
  560. await using var dbContext = _dbProvider.CreateContext();
  561. var user = dbContext.Users
  562. .Include(u => u.Permissions)
  563. .Include(u => u.Preferences)
  564. .Include(u => u.AccessSchedules)
  565. .Include(u => u.ProfileImage)
  566. .FirstOrDefault(u => u.Id == userId)
  567. ?? throw new ArgumentException("No user exists with given Id!");
  568. // The default number of login attempts is 3, but for some god forsaken reason it's sent to the server as "0"
  569. int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
  570. {
  571. -1 => null,
  572. 0 => 3,
  573. _ => policy.LoginAttemptsBeforeLockout
  574. };
  575. user.MaxParentalAgeRating = policy.MaxParentalRating;
  576. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  577. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  578. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  579. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  580. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  581. user.LoginAttemptsBeforeLockout = maxLoginAttempts;
  582. user.MaxActiveSessions = policy.MaxActiveSessions;
  583. user.SyncPlayAccess = policy.SyncPlayAccess;
  584. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  585. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  586. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  587. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  588. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  589. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  590. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  591. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  592. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  593. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  594. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  595. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  596. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  597. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  598. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  599. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  600. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  601. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  602. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  603. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  604. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  605. user.AccessSchedules.Clear();
  606. foreach (var policyAccessSchedule in policy.AccessSchedules)
  607. {
  608. user.AccessSchedules.Add(policyAccessSchedule);
  609. }
  610. // TODO: fix this at some point
  611. user.SetPreference(PreferenceKind.BlockUnratedItems, policy.BlockUnratedItems ?? Array.Empty<UnratedItem>());
  612. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  613. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  614. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  615. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  616. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  617. dbContext.Update(user);
  618. _users[user.Id] = user;
  619. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  620. }
  621. /// <inheritdoc/>
  622. public async Task ClearProfileImageAsync(User user)
  623. {
  624. await using var dbContext = _dbProvider.CreateContext();
  625. dbContext.Remove(user.ProfileImage);
  626. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  627. user.ProfileImage = null;
  628. _users[user.Id] = user;
  629. }
  630. internal static void ThrowIfInvalidUsername(string name)
  631. {
  632. if (!string.IsNullOrWhiteSpace(name) && IsValidUsername(name))
  633. {
  634. return;
  635. }
  636. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)", nameof(name));
  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. }