UserManager.cs 37 KB

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