UserManager.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. #pragma warning disable CS0067
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using Jellyfin.Data.Enums;
  10. using MediaBrowser.Common.Cryptography;
  11. using MediaBrowser.Common.Net;
  12. using MediaBrowser.Controller.Authentication;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.Net;
  15. using MediaBrowser.Model.Configuration;
  16. using MediaBrowser.Model.Cryptography;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.Events;
  19. using MediaBrowser.Model.Users;
  20. using Microsoft.Extensions.Logging;
  21. namespace Jellyfin.Server.Implementations.User
  22. {
  23. public class UserManager : IUserManager
  24. {
  25. private readonly JellyfinDbProvider _dbProvider;
  26. private readonly ICryptoProvider _cryptoProvider;
  27. private readonly INetworkManager _networkManager;
  28. private readonly ILogger<IUserManager> _logger;
  29. private IAuthenticationProvider[] _authenticationProviders;
  30. private DefaultAuthenticationProvider _defaultAuthenticationProvider;
  31. private InvalidAuthProvider _invalidAuthProvider;
  32. private IPasswordResetProvider[] _passwordResetProviders;
  33. private DefaultPasswordResetProvider _defaultPasswordResetProvider;
  34. public UserManager(
  35. JellyfinDbProvider dbProvider,
  36. ICryptoProvider cryptoProvider,
  37. INetworkManager networkManager,
  38. ILogger<IUserManager> logger)
  39. {
  40. _dbProvider = dbProvider;
  41. _cryptoProvider = cryptoProvider;
  42. _networkManager = networkManager;
  43. _logger = logger;
  44. }
  45. public event EventHandler<GenericEventArgs<Data.Entities.User>> OnUserPasswordChanged;
  46. /// <inheritdoc/>
  47. public event EventHandler<GenericEventArgs<Data.Entities.User>> OnUserUpdated;
  48. /// <inheritdoc/>
  49. public event EventHandler<GenericEventArgs<Data.Entities.User>> OnUserCreated;
  50. /// <inheritdoc/>
  51. public event EventHandler<GenericEventArgs<Data.Entities.User>> OnUserDeleted;
  52. public event EventHandler<GenericEventArgs<Data.Entities.User>> OnUserLockedOut;
  53. public IEnumerable<Data.Entities.User> Users
  54. {
  55. get
  56. {
  57. using var dbContext = _dbProvider.CreateContext();
  58. return dbContext.Users;
  59. }
  60. }
  61. public IEnumerable<Guid> UsersIds
  62. {
  63. get
  64. {
  65. using var dbContext = _dbProvider.CreateContext();
  66. return dbContext.Users.Select(u => u.Id);
  67. }
  68. }
  69. public Data.Entities.User GetUserById(Guid id)
  70. {
  71. if (id == Guid.Empty)
  72. {
  73. throw new ArgumentException("Guid can't be empty", nameof(id));
  74. }
  75. using var dbContext = _dbProvider.CreateContext();
  76. return dbContext.Users.Find(id);
  77. }
  78. public Data.Entities.User GetUserByName(string name)
  79. {
  80. if (string.IsNullOrWhiteSpace(name))
  81. {
  82. throw new ArgumentException("Invalid username", nameof(name));
  83. }
  84. using var dbContext = _dbProvider.CreateContext();
  85. return dbContext.Users.FirstOrDefault(u =>
  86. string.Equals(u.Username, name, StringComparison.OrdinalIgnoreCase));
  87. }
  88. public async Task RenameUser(Data.Entities.User user, string newName)
  89. {
  90. if (user == null)
  91. {
  92. throw new ArgumentNullException(nameof(user));
  93. }
  94. if (string.IsNullOrWhiteSpace(newName))
  95. {
  96. throw new ArgumentException("Invalid username", nameof(newName));
  97. }
  98. if (user.Username.Equals(newName, StringComparison.Ordinal))
  99. {
  100. throw new ArgumentException("The new and old names must be different.");
  101. }
  102. if (Users.Any(
  103. u => u.Id != user.Id && u.Username.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  104. {
  105. throw new ArgumentException(string.Format(
  106. CultureInfo.InvariantCulture,
  107. "A user with the name '{0}' already exists.",
  108. newName));
  109. }
  110. user.Username = newName;
  111. await UpdateUserAsync(user).ConfigureAwait(false);
  112. OnUserUpdated?.Invoke(this, new GenericEventArgs<Data.Entities.User>(user));
  113. }
  114. public void UpdateUser(Data.Entities.User user)
  115. {
  116. using var dbContext = _dbProvider.CreateContext();
  117. dbContext.Users.Update(user);
  118. dbContext.SaveChanges();
  119. }
  120. public async Task UpdateUserAsync(Data.Entities.User user)
  121. {
  122. await using var dbContext = _dbProvider.CreateContext();
  123. dbContext.Users.Update(user);
  124. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  125. }
  126. public Data.Entities.User CreateUser(string name)
  127. {
  128. using var dbContext = _dbProvider.CreateContext();
  129. var newUser = CreateUserObject(name);
  130. dbContext.Users.Add(newUser);
  131. dbContext.SaveChanges();
  132. return newUser;
  133. }
  134. public void DeleteUser(Data.Entities.User user)
  135. {
  136. if (user == null)
  137. {
  138. throw new ArgumentNullException(nameof(user));
  139. }
  140. using var dbContext = _dbProvider.CreateContext();
  141. if (!dbContext.Users.Contains(user))
  142. {
  143. throw new ArgumentException(string.Format(
  144. CultureInfo.InvariantCulture,
  145. "The user cannot be deleted because there is no user with the Name {0} and Id {1}.",
  146. user.Username,
  147. user.Id));
  148. }
  149. if (dbContext.Users.Count() == 1)
  150. {
  151. throw new InvalidOperationException(string.Format(
  152. CultureInfo.InvariantCulture,
  153. "The user '{0}' cannot be deleted because there must be at least one user in the system.",
  154. user.Username));
  155. }
  156. if (user.HasPermission(PermissionKind.IsAdministrator)
  157. && Users.Count(i => i.HasPermission(PermissionKind.IsAdministrator)) == 1)
  158. {
  159. throw new ArgumentException(
  160. string.Format(
  161. CultureInfo.InvariantCulture,
  162. "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
  163. user.Username),
  164. nameof(user));
  165. }
  166. dbContext.Users.Remove(user);
  167. dbContext.SaveChanges();
  168. }
  169. public Task ResetPassword(Data.Entities.User user)
  170. {
  171. return ChangePassword(user, string.Empty);
  172. }
  173. public void ResetEasyPassword(Data.Entities.User user)
  174. {
  175. ChangeEasyPassword(user, string.Empty, null);
  176. }
  177. public async Task ChangePassword(Data.Entities.User user, string newPassword)
  178. {
  179. if (user == null)
  180. {
  181. throw new ArgumentNullException(nameof(user));
  182. }
  183. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  184. await UpdateUserAsync(user).ConfigureAwait(false);
  185. OnUserPasswordChanged?.Invoke(this, new GenericEventArgs<Data.Entities.User>(user));
  186. }
  187. public void ChangeEasyPassword(Data.Entities.User user, string newPassword, string newPasswordSha1)
  188. {
  189. if (user == null)
  190. {
  191. throw new ArgumentNullException(nameof(user));
  192. }
  193. GetAuthenticationProvider(user).ChangeEasyPassword(user, newPassword, newPasswordSha1);
  194. UpdateUser(user);
  195. OnUserPasswordChanged?.Invoke(this, new GenericEventArgs<Data.Entities.User>(user));
  196. }
  197. public UserDto GetUserDto(Data.Entities.User user, string remoteEndPoint = null)
  198. {
  199. return new UserDto
  200. {
  201. Id = user.Id,
  202. HasPassword = user.Password == null,
  203. EnableAutoLogin = user.EnableAutoLogin,
  204. LastLoginDate = user.LastLoginDate,
  205. LastActivityDate = user.LastActivityDate,
  206. Configuration = new UserConfiguration
  207. {
  208. SubtitleMode = user.SubtitleMode,
  209. HidePlayedInLatest = user.HidePlayedInLatest,
  210. EnableLocalPassword = user.EnableLocalPassword,
  211. PlayDefaultAudioTrack = user.PlayDefaultAudioTrack,
  212. DisplayCollectionsView = user.DisplayCollectionsView,
  213. DisplayMissingEpisodes = user.DisplayMissingEpisodes,
  214. AudioLanguagePreference = user.AudioLanguagePreference,
  215. RememberAudioSelections = user.RememberAudioSelections,
  216. EnableNextEpisodeAutoPlay = user.EnableNextEpisodeAutoPlay,
  217. RememberSubtitleSelections = user.RememberSubtitleSelections,
  218. SubtitleLanguagePreference = user.SubtitleLanguagePreference,
  219. OrderedViews = user.GetPreference(PreferenceKind.OrderedViews),
  220. GroupedFolders = user.GetPreference(PreferenceKind.GroupedFolders),
  221. MyMediaExcludes = user.GetPreference(PreferenceKind.MyMediaExcludes),
  222. LatestItemsExcludes = user.GetPreference(PreferenceKind.LatestItemExcludes)
  223. },
  224. Policy = new UserPolicy
  225. {
  226. MaxParentalRating = user.MaxParentalAgeRating,
  227. EnableUserPreferenceAccess = user.EnableUserPreferenceAccess,
  228. RemoteClientBitrateLimit = user.RemoteClientBitrateLimit.GetValueOrDefault(),
  229. AuthenticatioIsnProviderId = user.AuthenticationProviderId,
  230. PasswordResetProviderId = user.PasswordResetProviderId,
  231. InvalidLoginAttemptCount = user.InvalidLoginAttemptCount,
  232. LoginAttemptsBeforeLockout = user.LoginAttemptsBeforeLockout.GetValueOrDefault(),
  233. IsAdministrator = user.HasPermission(PermissionKind.IsAdministrator),
  234. IsHidden = user.HasPermission(PermissionKind.IsHidden),
  235. IsDisabled = user.HasPermission(PermissionKind.IsDisabled),
  236. EnableSharedDeviceControl = user.HasPermission(PermissionKind.EnableSharedDeviceControl),
  237. EnableRemoteAccess = user.HasPermission(PermissionKind.EnableRemoteAccess),
  238. EnableLiveTvManagement = user.HasPermission(PermissionKind.EnableLiveTvManagement),
  239. EnableLiveTvAccess = user.HasPermission(PermissionKind.EnableLiveTvAccess),
  240. EnableMediaPlayback = user.HasPermission(PermissionKind.EnableMediaPlayback),
  241. EnableAudioPlaybackTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding),
  242. EnableVideoPlaybackTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding),
  243. EnableContentDeletion = user.HasPermission(PermissionKind.EnableContentDeletion),
  244. EnableContentDownloading = user.HasPermission(PermissionKind.EnableContentDownloading),
  245. EnableSyncTranscoding = user.HasPermission(PermissionKind.EnableSyncTranscoding),
  246. EnableMediaConversion = user.HasPermission(PermissionKind.EnableMediaConversion),
  247. EnableAllChannels = user.HasPermission(PermissionKind.EnableAllChannels),
  248. EnableAllDevices = user.HasPermission(PermissionKind.EnableAllDevices),
  249. EnableAllFolders = user.HasPermission(PermissionKind.EnableAllFolders),
  250. EnableRemoteControlOfOtherUsers = user.HasPermission(PermissionKind.EnableRemoteControlOfOtherUsers),
  251. EnablePlaybackRemuxing = user.HasPermission(PermissionKind.EnablePlaybackRemuxing),
  252. ForceRemoteSourceTranscoding = user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding),
  253. EnablePublicSharing = user.HasPermission(PermissionKind.EnablePublicSharing),
  254. AccessSchedules = user.AccessSchedules.ToArray(),
  255. BlockedTags = user.GetPreference(PreferenceKind.BlockedTags),
  256. EnabledChannels = user.GetPreference(PreferenceKind.EnabledChannels),
  257. EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices),
  258. EnabledFolders = user.GetPreference(PreferenceKind.EnabledFolders),
  259. EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders)
  260. }
  261. };
  262. }
  263. public PublicUserDto GetPublicUserDto(Data.Entities.User user, string remoteEndPoint = null)
  264. {
  265. if (user == null)
  266. {
  267. throw new ArgumentNullException(nameof(user));
  268. }
  269. bool hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user);
  270. bool hasConfiguredEasyPassword = !string.IsNullOrEmpty(GetAuthenticationProvider(user).GetEasyPasswordHash(user));
  271. bool hasPassword = user.EnableLocalPassword &&
  272. !string.IsNullOrEmpty(remoteEndPoint) &&
  273. _networkManager.IsInLocalNetwork(remoteEndPoint) ? hasConfiguredEasyPassword : hasConfiguredPassword;
  274. return new PublicUserDto
  275. {
  276. Name = user.Username,
  277. HasPassword = hasPassword,
  278. HasConfiguredPassword = hasConfiguredPassword
  279. };
  280. }
  281. public async Task<Data.Entities.User> AuthenticateUser(
  282. string username,
  283. string password,
  284. string passwordSha1,
  285. string remoteEndPoint,
  286. bool isUserSession)
  287. {
  288. if (string.IsNullOrWhiteSpace(username))
  289. {
  290. _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
  291. throw new ArgumentNullException(nameof(username));
  292. }
  293. var user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  294. bool success;
  295. IAuthenticationProvider authenticationProvider;
  296. if (user != null)
  297. {
  298. var authResult = await AuthenticateLocalUser(username, password, user, remoteEndPoint)
  299. .ConfigureAwait(false);
  300. authenticationProvider = authResult.authenticationProvider;
  301. success = authResult.success;
  302. }
  303. else
  304. {
  305. var authResult = await AuthenticateLocalUser(username, password, null, remoteEndPoint)
  306. .ConfigureAwait(false);
  307. authenticationProvider = authResult.authenticationProvider;
  308. string updatedUsername = authResult.username;
  309. success = authResult.success;
  310. if (success
  311. && authenticationProvider != null
  312. && !(authenticationProvider is DefaultAuthenticationProvider))
  313. {
  314. // Trust the username returned by the authentication provider
  315. username = updatedUsername;
  316. // Search the database for the user again
  317. // the authentication provider might have created it
  318. user = Users
  319. .FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  320. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy)
  321. {
  322. UpdatePolicy(user.Id, hasNewUserPolicy.GetNewUserPolicy());
  323. await UpdateUserAsync(user).ConfigureAwait(false);
  324. }
  325. }
  326. }
  327. if (success && user != null && authenticationProvider != null)
  328. {
  329. var providerId = authenticationProvider.GetType().FullName;
  330. if (!string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  331. {
  332. user.AuthenticationProviderId = providerId;
  333. await UpdateUserAsync(user).ConfigureAwait(false);
  334. }
  335. }
  336. if (user == null)
  337. {
  338. _logger.LogInformation(
  339. "Authentication request for {UserName} has been denied (IP: {IP}).",
  340. username,
  341. remoteEndPoint);
  342. throw new AuthenticationException("Invalid username or password entered.");
  343. }
  344. if (user.HasPermission(PermissionKind.IsDisabled))
  345. {
  346. _logger.LogInformation(
  347. "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
  348. username,
  349. remoteEndPoint);
  350. throw new SecurityException(
  351. $"The {user.Username} account is currently disabled. Please consult with your administrator.");
  352. }
  353. if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
  354. !_networkManager.IsInLocalNetwork(remoteEndPoint))
  355. {
  356. _logger.LogInformation(
  357. "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
  358. username,
  359. remoteEndPoint);
  360. throw new SecurityException("Forbidden.");
  361. }
  362. if (!user.IsParentalScheduleAllowed())
  363. {
  364. _logger.LogInformation(
  365. "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
  366. username,
  367. remoteEndPoint);
  368. throw new SecurityException("User is not allowed access at this time.");
  369. }
  370. // Update LastActivityDate and LastLoginDate, then save
  371. if (success)
  372. {
  373. if (isUserSession)
  374. {
  375. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  376. UpdateUser(user);
  377. }
  378. ResetInvalidLoginAttemptCount(user);
  379. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
  380. }
  381. else
  382. {
  383. IncrementInvalidLoginAttemptCount(user);
  384. _logger.LogInformation(
  385. "Authentication request for {UserName} has been denied (IP: {IP}).",
  386. user.Username,
  387. remoteEndPoint);
  388. }
  389. return success ? user : null;
  390. }
  391. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  392. {
  393. var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
  394. var action = ForgotPasswordAction.InNetworkRequired;
  395. if (user != null && isInNetwork)
  396. {
  397. var passwordResetProvider = GetPasswordResetProvider(user);
  398. return await passwordResetProvider.StartForgotPasswordProcess(user, isInNetwork).ConfigureAwait(false);
  399. }
  400. return new ForgotPasswordResult
  401. {
  402. Action = action,
  403. PinFile = string.Empty
  404. };
  405. }
  406. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  407. {
  408. foreach (var provider in _passwordResetProviders)
  409. {
  410. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  411. if (result.Success)
  412. {
  413. return result;
  414. }
  415. }
  416. return new PinRedeemResult
  417. {
  418. Success = false,
  419. UsersReset = Array.Empty<string>()
  420. };
  421. }
  422. public void AddParts(IEnumerable<IAuthenticationProvider> authenticationProviders, IEnumerable<IPasswordResetProvider> passwordResetProviders)
  423. {
  424. _authenticationProviders = authenticationProviders.ToArray();
  425. _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
  426. _invalidAuthProvider = _authenticationProviders.OfType<InvalidAuthProvider>().First();
  427. _passwordResetProviders = passwordResetProviders.ToArray();
  428. _defaultPasswordResetProvider = passwordResetProviders.OfType<DefaultPasswordResetProvider>().First();
  429. }
  430. public NameIdPair[] GetAuthenticationProviders()
  431. {
  432. return _authenticationProviders
  433. .Where(provider => provider.IsEnabled)
  434. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  435. .ThenBy(i => i.Name)
  436. .Select(i => new NameIdPair
  437. {
  438. Name = i.Name,
  439. Id = i.GetType().FullName
  440. })
  441. .ToArray();
  442. }
  443. public NameIdPair[] GetPasswordResetProviders()
  444. {
  445. return _passwordResetProviders
  446. .Where(provider => provider.IsEnabled)
  447. .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
  448. .ThenBy(i => i.Name)
  449. .Select(i => new NameIdPair
  450. {
  451. Name = i.Name,
  452. Id = i.GetType().FullName
  453. })
  454. .ToArray();
  455. }
  456. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  457. {
  458. var user = GetUserById(userId);
  459. user.SubtitleMode = config.SubtitleMode;
  460. user.HidePlayedInLatest = config.HidePlayedInLatest;
  461. user.EnableLocalPassword = config.EnableLocalPassword;
  462. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  463. user.DisplayCollectionsView = config.DisplayCollectionsView;
  464. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  465. user.AudioLanguagePreference = config.AudioLanguagePreference;
  466. user.RememberAudioSelections = config.RememberAudioSelections;
  467. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  468. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  469. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  470. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  471. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  472. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  473. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  474. UpdateUser(user);
  475. }
  476. public void UpdatePolicy(Guid userId, UserPolicy policy)
  477. {
  478. var user = GetUserById(userId);
  479. user.MaxParentalAgeRating = policy.MaxParentalRating;
  480. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  481. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  482. user.AuthenticationProviderId = policy.AuthenticatioIsnProviderId;
  483. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  484. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  485. user.LoginAttemptsBeforeLockout = policy.LoginAttemptsBeforeLockout == -1
  486. ? null
  487. : new int?(policy.LoginAttemptsBeforeLockout);
  488. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  489. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  490. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  491. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  492. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  493. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  494. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  495. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  496. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  497. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  498. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  499. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  500. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  501. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  502. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  503. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  504. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  505. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  506. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  507. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  508. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  509. user.AccessSchedules.Clear();
  510. foreach (var policyAccessSchedule in policy.AccessSchedules)
  511. {
  512. user.AccessSchedules.Add(policyAccessSchedule);
  513. }
  514. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  515. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  516. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  517. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  518. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  519. }
  520. private Data.Entities.User CreateUserObject(string name)
  521. {
  522. return new Data.Entities.User(
  523. username: name,
  524. mustUpdatePassword: false,
  525. authenticationProviderId: _defaultAuthenticationProvider.GetType().FullName,
  526. invalidLoginAttemptCount: -1,
  527. subtitleMode: SubtitlePlaybackMode.Default,
  528. playDefaultAudioTrack: true);
  529. }
  530. private IAuthenticationProvider GetAuthenticationProvider(Data.Entities.User user)
  531. {
  532. return GetAuthenticationProviders(user)[0];
  533. }
  534. private IPasswordResetProvider GetPasswordResetProvider(Data.Entities.User user)
  535. {
  536. return GetPasswordResetProviders(user)[0];
  537. }
  538. private IList<IAuthenticationProvider> GetAuthenticationProviders(Data.Entities.User user)
  539. {
  540. var authenticationProviderId = user?.AuthenticationProviderId;
  541. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();
  542. if (!string.IsNullOrEmpty(authenticationProviderId))
  543. {
  544. providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
  545. }
  546. if (providers.Count == 0)
  547. {
  548. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  549. _logger.LogWarning(
  550. "User {UserName} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
  551. user?.Username,
  552. user?.AuthenticationProviderId);
  553. providers = new List<IAuthenticationProvider>
  554. {
  555. _invalidAuthProvider
  556. };
  557. }
  558. return providers;
  559. }
  560. private IList<IPasswordResetProvider> GetPasswordResetProviders(Data.Entities.User user)
  561. {
  562. var passwordResetProviderId = user?.PasswordResetProviderId;
  563. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  564. if (!string.IsNullOrEmpty(passwordResetProviderId))
  565. {
  566. providers = providers.Where(i =>
  567. string.Equals(passwordResetProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase))
  568. .ToArray();
  569. }
  570. if (providers.Length == 0)
  571. {
  572. providers = new IPasswordResetProvider[]
  573. {
  574. _defaultPasswordResetProvider
  575. };
  576. }
  577. return providers;
  578. }
  579. private async Task<(IAuthenticationProvider authenticationProvider, string username, bool success)>
  580. AuthenticateLocalUser(
  581. string username,
  582. string password,
  583. Jellyfin.Data.Entities.User user,
  584. string remoteEndPoint)
  585. {
  586. bool success = false;
  587. IAuthenticationProvider authenticationProvider = null;
  588. foreach (var provider in GetAuthenticationProviders(user))
  589. {
  590. var providerAuthResult =
  591. await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  592. var updatedUsername = providerAuthResult.username;
  593. success = providerAuthResult.success;
  594. if (success)
  595. {
  596. authenticationProvider = provider;
  597. username = updatedUsername;
  598. break;
  599. }
  600. }
  601. if (!success
  602. && _networkManager.IsInLocalNetwork(remoteEndPoint)
  603. && user?.EnableLocalPassword == true
  604. && !string.IsNullOrEmpty(user.EasyPassword))
  605. {
  606. // Check easy password
  607. var passwordHash = PasswordHash.Parse(user.EasyPassword);
  608. var hash = _cryptoProvider.ComputeHash(
  609. passwordHash.Id,
  610. Encoding.UTF8.GetBytes(password),
  611. passwordHash.Salt.ToArray());
  612. success = passwordHash.Hash.SequenceEqual(hash);
  613. }
  614. return (authenticationProvider, username, success);
  615. }
  616. private async Task<(string username, bool success)> AuthenticateWithProvider(
  617. IAuthenticationProvider provider,
  618. string username,
  619. string password,
  620. Data.Entities.User resolvedUser)
  621. {
  622. try
  623. {
  624. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  625. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  626. : await provider.Authenticate(username, password).ConfigureAwait(false);
  627. if (authenticationResult.Username != username)
  628. {
  629. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  630. username = authenticationResult.Username;
  631. }
  632. return (username, true);
  633. }
  634. catch (AuthenticationException ex)
  635. {
  636. _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
  637. return (username, false);
  638. }
  639. }
  640. private void IncrementInvalidLoginAttemptCount(Data.Entities.User user)
  641. {
  642. int invalidLogins = user.InvalidLoginAttemptCount;
  643. int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
  644. if (maxInvalidLogins.HasValue
  645. && invalidLogins >= maxInvalidLogins)
  646. {
  647. user.SetPermission(PermissionKind.IsDisabled, true);
  648. OnUserLockedOut?.Invoke(this, new GenericEventArgs<Data.Entities.User>(user));
  649. _logger.LogWarning(
  650. "Disabling user {UserName} due to {Attempts} unsuccessful login attempts.",
  651. user.Username,
  652. invalidLogins);
  653. }
  654. UpdateUser(user);
  655. }
  656. private void ResetInvalidLoginAttemptCount(Data.Entities.User user)
  657. {
  658. user.InvalidLoginAttemptCount = 0;
  659. }
  660. }
  661. }