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