UserManager.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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. var authResult = await AuthenticateLocalUser(username, password, user, remoteEndPoint)
  348. .ConfigureAwait(false);
  349. var authenticationProvider = authResult.authenticationProvider;
  350. var success = authResult.success;
  351. if (user == null)
  352. {
  353. string updatedUsername = authResult.username;
  354. if (success
  355. && authenticationProvider != null
  356. && authenticationProvider is not DefaultAuthenticationProvider)
  357. {
  358. // Trust the username returned by the authentication provider
  359. username = updatedUsername;
  360. // Search the database for the user again
  361. // the authentication provider might have created it
  362. user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  363. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy && user != null)
  364. {
  365. await UpdatePolicyAsync(user.Id, hasNewUserPolicy.GetNewUserPolicy()).ConfigureAwait(false);
  366. }
  367. }
  368. }
  369. if (success && user != null && authenticationProvider != null)
  370. {
  371. var providerId = authenticationProvider.GetType().FullName;
  372. if (providerId != null && !string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  373. {
  374. user.AuthenticationProviderId = providerId;
  375. await UpdateUserAsync(user).ConfigureAwait(false);
  376. }
  377. }
  378. if (user == null)
  379. {
  380. _logger.LogInformation(
  381. "Authentication request for {UserName} has been denied (IP: {IP}).",
  382. username,
  383. remoteEndPoint);
  384. throw new AuthenticationException("Invalid username or password entered.");
  385. }
  386. if (user.HasPermission(PermissionKind.IsDisabled))
  387. {
  388. _logger.LogInformation(
  389. "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
  390. username,
  391. remoteEndPoint);
  392. throw new SecurityException(
  393. $"The {user.Username} account is currently disabled. Please consult with your administrator.");
  394. }
  395. if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
  396. !_networkManager.IsInLocalNetwork(remoteEndPoint))
  397. {
  398. _logger.LogInformation(
  399. "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
  400. username,
  401. remoteEndPoint);
  402. throw new SecurityException("Forbidden.");
  403. }
  404. if (!user.IsParentalScheduleAllowed())
  405. {
  406. _logger.LogInformation(
  407. "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
  408. username,
  409. remoteEndPoint);
  410. throw new SecurityException("User is not allowed access at this time.");
  411. }
  412. // Update LastActivityDate and LastLoginDate, then save
  413. if (success)
  414. {
  415. if (isUserSession)
  416. {
  417. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  418. }
  419. user.InvalidLoginAttemptCount = 0;
  420. await UpdateUserAsync(user).ConfigureAwait(false);
  421. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
  422. }
  423. else
  424. {
  425. await IncrementInvalidLoginAttemptCount(user).ConfigureAwait(false);
  426. _logger.LogInformation(
  427. "Authentication request for {UserName} has been denied (IP: {IP}).",
  428. user.Username,
  429. remoteEndPoint);
  430. }
  431. return success ? user : null;
  432. }
  433. /// <inheritdoc/>
  434. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  435. {
  436. var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
  437. if (user != null && isInNetwork)
  438. {
  439. var passwordResetProvider = GetPasswordResetProvider(user);
  440. var result = await passwordResetProvider
  441. .StartForgotPasswordProcess(user, isInNetwork)
  442. .ConfigureAwait(false);
  443. await UpdateUserAsync(user).ConfigureAwait(false);
  444. return result;
  445. }
  446. return new ForgotPasswordResult
  447. {
  448. Action = ForgotPasswordAction.InNetworkRequired,
  449. PinFile = string.Empty
  450. };
  451. }
  452. /// <inheritdoc/>
  453. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  454. {
  455. foreach (var provider in _passwordResetProviders)
  456. {
  457. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  458. if (result.Success)
  459. {
  460. return result;
  461. }
  462. }
  463. return new PinRedeemResult();
  464. }
  465. /// <inheritdoc />
  466. public async Task InitializeAsync()
  467. {
  468. // TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
  469. if (_users.Any())
  470. {
  471. return;
  472. }
  473. var defaultName = Environment.UserName;
  474. if (string.IsNullOrWhiteSpace(defaultName) || !IsValidUsername(defaultName))
  475. {
  476. defaultName = "MyJellyfinUser";
  477. }
  478. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  479. await using var dbContext = _dbProvider.CreateContext();
  480. var newUser = await CreateUserInternalAsync(defaultName, dbContext).ConfigureAwait(false);
  481. newUser.SetPermission(PermissionKind.IsAdministrator, true);
  482. newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
  483. newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
  484. dbContext.Users.Add(newUser);
  485. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  486. }
  487. /// <inheritdoc/>
  488. public NameIdPair[] GetAuthenticationProviders()
  489. {
  490. return _authenticationProviders
  491. .Where(provider => provider.IsEnabled)
  492. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  493. .ThenBy(i => i.Name)
  494. .Select(i => new NameIdPair
  495. {
  496. Name = i.Name,
  497. Id = i.GetType().FullName
  498. })
  499. .ToArray();
  500. }
  501. /// <inheritdoc/>
  502. public NameIdPair[] GetPasswordResetProviders()
  503. {
  504. return _passwordResetProviders
  505. .Where(provider => provider.IsEnabled)
  506. .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
  507. .ThenBy(i => i.Name)
  508. .Select(i => new NameIdPair
  509. {
  510. Name = i.Name,
  511. Id = i.GetType().FullName
  512. })
  513. .ToArray();
  514. }
  515. /// <inheritdoc/>
  516. public async Task UpdateConfigurationAsync(Guid userId, UserConfiguration config)
  517. {
  518. await using var dbContext = _dbProvider.CreateContext();
  519. var user = dbContext.Users
  520. .Include(u => u.Permissions)
  521. .Include(u => u.Preferences)
  522. .Include(u => u.AccessSchedules)
  523. .Include(u => u.ProfileImage)
  524. .FirstOrDefault(u => u.Id == userId)
  525. ?? throw new ArgumentException("No user exists with given Id!");
  526. user.SubtitleMode = config.SubtitleMode;
  527. user.HidePlayedInLatest = config.HidePlayedInLatest;
  528. user.EnableLocalPassword = config.EnableLocalPassword;
  529. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  530. user.DisplayCollectionsView = config.DisplayCollectionsView;
  531. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  532. user.AudioLanguagePreference = config.AudioLanguagePreference;
  533. user.RememberAudioSelections = config.RememberAudioSelections;
  534. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  535. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  536. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  537. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  538. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  539. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  540. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  541. dbContext.Update(user);
  542. _users[user.Id] = user;
  543. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  544. }
  545. /// <inheritdoc/>
  546. public async Task UpdatePolicyAsync(Guid userId, UserPolicy policy)
  547. {
  548. await using var dbContext = _dbProvider.CreateContext();
  549. var user = dbContext.Users
  550. .Include(u => u.Permissions)
  551. .Include(u => u.Preferences)
  552. .Include(u => u.AccessSchedules)
  553. .Include(u => u.ProfileImage)
  554. .FirstOrDefault(u => u.Id == userId)
  555. ?? throw new ArgumentException("No user exists with given Id!");
  556. // The default number of login attempts is 3, but for some god forsaken reason it's sent to the server as "0"
  557. int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
  558. {
  559. -1 => null,
  560. 0 => 3,
  561. _ => policy.LoginAttemptsBeforeLockout
  562. };
  563. user.MaxParentalAgeRating = policy.MaxParentalRating;
  564. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  565. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  566. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  567. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  568. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  569. user.LoginAttemptsBeforeLockout = maxLoginAttempts;
  570. user.MaxActiveSessions = policy.MaxActiveSessions;
  571. user.SyncPlayAccess = policy.SyncPlayAccess;
  572. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  573. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  574. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  575. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  576. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  577. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  578. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  579. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  580. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  581. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  582. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  583. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  584. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  585. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  586. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  587. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  588. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  589. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  590. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  591. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  592. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  593. user.AccessSchedules.Clear();
  594. foreach (var policyAccessSchedule in policy.AccessSchedules)
  595. {
  596. user.AccessSchedules.Add(policyAccessSchedule);
  597. }
  598. // TODO: fix this at some point
  599. user.SetPreference(PreferenceKind.BlockUnratedItems, policy.BlockUnratedItems ?? Array.Empty<UnratedItem>());
  600. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  601. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  602. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  603. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  604. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  605. dbContext.Update(user);
  606. _users[user.Id] = user;
  607. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  608. }
  609. /// <inheritdoc/>
  610. public async Task ClearProfileImageAsync(User user)
  611. {
  612. if (user.ProfileImage == null)
  613. {
  614. return;
  615. }
  616. await using var dbContext = _dbProvider.CreateContext();
  617. dbContext.Remove(user.ProfileImage);
  618. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  619. user.ProfileImage = null;
  620. _users[user.Id] = user;
  621. }
  622. internal static void ThrowIfInvalidUsername(string name)
  623. {
  624. if (!string.IsNullOrWhiteSpace(name) && IsValidUsername(name))
  625. {
  626. return;
  627. }
  628. throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)", nameof(name));
  629. }
  630. private static bool IsValidUsername(string name)
  631. {
  632. // This is some regex that matches only on unicode "word" characters, as well as -, _ and @
  633. // In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
  634. // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), periods (.) and spaces ( )
  635. return Regex.IsMatch(name, @"^[\w\ \-'._@]+$");
  636. }
  637. private IAuthenticationProvider GetAuthenticationProvider(User user)
  638. {
  639. return GetAuthenticationProviders(user)[0];
  640. }
  641. private IPasswordResetProvider GetPasswordResetProvider(User user)
  642. {
  643. return GetPasswordResetProviders(user)[0];
  644. }
  645. private IList<IAuthenticationProvider> GetAuthenticationProviders(User? user)
  646. {
  647. var authenticationProviderId = user?.AuthenticationProviderId;
  648. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();
  649. if (!string.IsNullOrEmpty(authenticationProviderId))
  650. {
  651. providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
  652. }
  653. if (providers.Count == 0)
  654. {
  655. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  656. _logger.LogWarning(
  657. "User {Username} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
  658. user?.Username,
  659. user?.AuthenticationProviderId);
  660. providers = new List<IAuthenticationProvider>
  661. {
  662. _invalidAuthProvider
  663. };
  664. }
  665. return providers;
  666. }
  667. private IList<IPasswordResetProvider> GetPasswordResetProviders(User user)
  668. {
  669. var passwordResetProviderId = user.PasswordResetProviderId;
  670. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  671. if (!string.IsNullOrEmpty(passwordResetProviderId))
  672. {
  673. providers = providers.Where(i =>
  674. string.Equals(passwordResetProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase))
  675. .ToArray();
  676. }
  677. if (providers.Length == 0)
  678. {
  679. providers = new IPasswordResetProvider[]
  680. {
  681. _defaultPasswordResetProvider
  682. };
  683. }
  684. return providers;
  685. }
  686. private async Task<(IAuthenticationProvider? authenticationProvider, string username, bool success)> AuthenticateLocalUser(
  687. string username,
  688. string password,
  689. User? user,
  690. string remoteEndPoint)
  691. {
  692. bool success = false;
  693. IAuthenticationProvider? authenticationProvider = null;
  694. foreach (var provider in GetAuthenticationProviders(user))
  695. {
  696. var providerAuthResult =
  697. await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  698. var updatedUsername = providerAuthResult.username;
  699. success = providerAuthResult.success;
  700. if (success)
  701. {
  702. authenticationProvider = provider;
  703. username = updatedUsername;
  704. break;
  705. }
  706. }
  707. if (!success
  708. && _networkManager.IsInLocalNetwork(remoteEndPoint)
  709. && user?.EnableLocalPassword == true
  710. && !string.IsNullOrEmpty(user.EasyPassword))
  711. {
  712. // Check easy password
  713. var passwordHash = PasswordHash.Parse(user.EasyPassword);
  714. var hash = _cryptoProvider.ComputeHash(
  715. passwordHash.Id,
  716. Encoding.UTF8.GetBytes(password),
  717. passwordHash.Salt.ToArray());
  718. success = passwordHash.Hash.SequenceEqual(hash);
  719. }
  720. return (authenticationProvider, username, success);
  721. }
  722. private async Task<(string username, bool success)> AuthenticateWithProvider(
  723. IAuthenticationProvider provider,
  724. string username,
  725. string password,
  726. User? resolvedUser)
  727. {
  728. try
  729. {
  730. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  731. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  732. : await provider.Authenticate(username, password).ConfigureAwait(false);
  733. if (authenticationResult.Username != username)
  734. {
  735. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  736. username = authenticationResult.Username;
  737. }
  738. return (username, true);
  739. }
  740. catch (AuthenticationException ex)
  741. {
  742. _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
  743. return (username, false);
  744. }
  745. }
  746. private async Task IncrementInvalidLoginAttemptCount(User user)
  747. {
  748. user.InvalidLoginAttemptCount++;
  749. int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
  750. if (maxInvalidLogins.HasValue && user.InvalidLoginAttemptCount >= maxInvalidLogins)
  751. {
  752. user.SetPermission(PermissionKind.IsDisabled, true);
  753. await _eventManager.PublishAsync(new UserLockedOutEventArgs(user)).ConfigureAwait(false);
  754. _logger.LogWarning(
  755. "Disabling user {Username} due to {Attempts} unsuccessful login attempts.",
  756. user.Username,
  757. user.InvalidLoginAttemptCount);
  758. }
  759. await UpdateUserAsync(user).ConfigureAwait(false);
  760. }
  761. }
  762. }