UserManager.cs 40 KB

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