UserManager.cs 37 KB

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