UserManager.cs 38 KB

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