UserManager.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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.Net;
  15. using MediaBrowser.Controller.Authentication;
  16. using MediaBrowser.Controller.Drawing;
  17. using MediaBrowser.Controller.Library;
  18. using MediaBrowser.Controller.Net;
  19. using MediaBrowser.Model.Configuration;
  20. using MediaBrowser.Model.Cryptography;
  21. using MediaBrowser.Model.Dto;
  22. using MediaBrowser.Model.Events;
  23. using MediaBrowser.Model.Users;
  24. using Microsoft.EntityFrameworkCore.Internal;
  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(User user)
  166. {
  167. if (user == null)
  168. {
  169. throw new ArgumentNullException(nameof(user));
  170. }
  171. var dbContext = _dbProvider.CreateContext();
  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(user));
  196. }
  197. dbContext.Users.Remove(user);
  198. dbContext.SaveChanges();
  199. OnUserDeleted?.Invoke(this, new GenericEventArgs<User>(user));
  200. }
  201. /// <inheritdoc/>
  202. public Task ResetPassword(User user)
  203. {
  204. return ChangePassword(user, string.Empty);
  205. }
  206. /// <inheritdoc/>
  207. public void ResetEasyPassword(User user)
  208. {
  209. ChangeEasyPassword(user, string.Empty, null);
  210. }
  211. /// <inheritdoc/>
  212. public async Task ChangePassword(User user, string newPassword)
  213. {
  214. if (user == null)
  215. {
  216. throw new ArgumentNullException(nameof(user));
  217. }
  218. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  219. await UpdateUserAsync(user).ConfigureAwait(false);
  220. OnUserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  221. }
  222. /// <inheritdoc/>
  223. public void ChangeEasyPassword(User user, string newPassword, string? newPasswordSha1)
  224. {
  225. GetAuthenticationProvider(user).ChangeEasyPassword(user, newPassword, newPasswordSha1);
  226. UpdateUser(user);
  227. OnUserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  228. }
  229. /// <inheritdoc/>
  230. public UserDto GetUserDto(User user, string? remoteEndPoint = null)
  231. {
  232. var hasPassword = GetAuthenticationProvider(user).HasPassword(user);
  233. return new UserDto
  234. {
  235. Name = user.Username,
  236. Id = user.Id,
  237. ServerId = _appHost.SystemId,
  238. HasPassword = hasPassword,
  239. HasConfiguredPassword = hasPassword,
  240. HasConfiguredEasyPassword = !string.IsNullOrEmpty(user.EasyPassword),
  241. EnableAutoLogin = user.EnableAutoLogin,
  242. LastLoginDate = user.LastLoginDate,
  243. LastActivityDate = user.LastActivityDate,
  244. PrimaryImageTag = user.ProfileImage != null ? _imageProcessor.GetImageCacheTag(user) : null,
  245. Configuration = new UserConfiguration
  246. {
  247. SubtitleMode = user.SubtitleMode,
  248. HidePlayedInLatest = user.HidePlayedInLatest,
  249. EnableLocalPassword = user.EnableLocalPassword,
  250. PlayDefaultAudioTrack = user.PlayDefaultAudioTrack,
  251. DisplayCollectionsView = user.DisplayCollectionsView,
  252. DisplayMissingEpisodes = user.DisplayMissingEpisodes,
  253. AudioLanguagePreference = user.AudioLanguagePreference,
  254. RememberAudioSelections = user.RememberAudioSelections,
  255. EnableNextEpisodeAutoPlay = user.EnableNextEpisodeAutoPlay,
  256. RememberSubtitleSelections = user.RememberSubtitleSelections,
  257. SubtitleLanguagePreference = user.SubtitleLanguagePreference ?? string.Empty,
  258. OrderedViews = user.GetPreference(PreferenceKind.OrderedViews),
  259. GroupedFolders = user.GetPreference(PreferenceKind.GroupedFolders),
  260. MyMediaExcludes = user.GetPreference(PreferenceKind.MyMediaExcludes),
  261. LatestItemsExcludes = user.GetPreference(PreferenceKind.LatestItemExcludes)
  262. },
  263. Policy = new UserPolicy
  264. {
  265. MaxParentalRating = user.MaxParentalAgeRating,
  266. EnableUserPreferenceAccess = user.EnableUserPreferenceAccess,
  267. RemoteClientBitrateLimit = user.RemoteClientBitrateLimit ?? 0,
  268. AuthenticationProviderId = user.AuthenticationProviderId,
  269. PasswordResetProviderId = user.PasswordResetProviderId,
  270. InvalidLoginAttemptCount = user.InvalidLoginAttemptCount,
  271. LoginAttemptsBeforeLockout = user.LoginAttemptsBeforeLockout ?? -1,
  272. IsAdministrator = user.HasPermission(PermissionKind.IsAdministrator),
  273. IsHidden = user.HasPermission(PermissionKind.IsHidden),
  274. IsDisabled = user.HasPermission(PermissionKind.IsDisabled),
  275. EnableSharedDeviceControl = user.HasPermission(PermissionKind.EnableSharedDeviceControl),
  276. EnableRemoteAccess = user.HasPermission(PermissionKind.EnableRemoteAccess),
  277. EnableLiveTvManagement = user.HasPermission(PermissionKind.EnableLiveTvManagement),
  278. EnableLiveTvAccess = user.HasPermission(PermissionKind.EnableLiveTvAccess),
  279. EnableMediaPlayback = user.HasPermission(PermissionKind.EnableMediaPlayback),
  280. EnableAudioPlaybackTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding),
  281. EnableVideoPlaybackTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding),
  282. EnableContentDeletion = user.HasPermission(PermissionKind.EnableContentDeletion),
  283. EnableContentDownloading = user.HasPermission(PermissionKind.EnableContentDownloading),
  284. EnableSyncTranscoding = user.HasPermission(PermissionKind.EnableSyncTranscoding),
  285. EnableMediaConversion = user.HasPermission(PermissionKind.EnableMediaConversion),
  286. EnableAllChannels = user.HasPermission(PermissionKind.EnableAllChannels),
  287. EnableAllDevices = user.HasPermission(PermissionKind.EnableAllDevices),
  288. EnableAllFolders = user.HasPermission(PermissionKind.EnableAllFolders),
  289. EnableRemoteControlOfOtherUsers = user.HasPermission(PermissionKind.EnableRemoteControlOfOtherUsers),
  290. EnablePlaybackRemuxing = user.HasPermission(PermissionKind.EnablePlaybackRemuxing),
  291. ForceRemoteSourceTranscoding = user.HasPermission(PermissionKind.ForceRemoteSourceTranscoding),
  292. EnablePublicSharing = user.HasPermission(PermissionKind.EnablePublicSharing),
  293. AccessSchedules = user.AccessSchedules.ToArray(),
  294. BlockedTags = user.GetPreference(PreferenceKind.BlockedTags),
  295. EnabledChannels = user.GetPreference(PreferenceKind.EnabledChannels),
  296. EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices),
  297. EnabledFolders = user.GetPreference(PreferenceKind.EnabledFolders),
  298. EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders),
  299. SyncPlayAccess = user.SyncPlayAccess
  300. }
  301. };
  302. }
  303. /// <inheritdoc/>
  304. public async Task<User?> AuthenticateUser(
  305. string username,
  306. string password,
  307. string passwordSha1,
  308. string remoteEndPoint,
  309. bool isUserSession)
  310. {
  311. if (string.IsNullOrWhiteSpace(username))
  312. {
  313. _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
  314. throw new ArgumentNullException(nameof(username));
  315. }
  316. var user = Users.ToList().FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  317. bool success;
  318. IAuthenticationProvider? authenticationProvider;
  319. if (user != null)
  320. {
  321. var authResult = await AuthenticateLocalUser(username, password, user, remoteEndPoint)
  322. .ConfigureAwait(false);
  323. authenticationProvider = authResult.authenticationProvider;
  324. success = authResult.success;
  325. }
  326. else
  327. {
  328. var authResult = await AuthenticateLocalUser(username, password, null, remoteEndPoint)
  329. .ConfigureAwait(false);
  330. authenticationProvider = authResult.authenticationProvider;
  331. string updatedUsername = authResult.username;
  332. success = authResult.success;
  333. if (success
  334. && authenticationProvider != null
  335. && !(authenticationProvider is DefaultAuthenticationProvider))
  336. {
  337. // Trust the username returned by the authentication provider
  338. username = updatedUsername;
  339. // Search the database for the user again
  340. // the authentication provider might have created it
  341. user = Users
  342. .ToList().FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
  343. if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy)
  344. {
  345. UpdatePolicy(user.Id, hasNewUserPolicy.GetNewUserPolicy());
  346. await UpdateUserAsync(user).ConfigureAwait(false);
  347. }
  348. }
  349. }
  350. if (success && user != null && authenticationProvider != null)
  351. {
  352. var providerId = authenticationProvider.GetType().FullName;
  353. if (!string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  354. {
  355. user.AuthenticationProviderId = providerId;
  356. await UpdateUserAsync(user).ConfigureAwait(false);
  357. }
  358. }
  359. if (user == null)
  360. {
  361. _logger.LogInformation(
  362. "Authentication request for {UserName} has been denied (IP: {IP}).",
  363. username,
  364. remoteEndPoint);
  365. throw new AuthenticationException("Invalid username or password entered.");
  366. }
  367. if (user.HasPermission(PermissionKind.IsDisabled))
  368. {
  369. _logger.LogInformation(
  370. "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
  371. username,
  372. remoteEndPoint);
  373. throw new SecurityException(
  374. $"The {user.Username} account is currently disabled. Please consult with your administrator.");
  375. }
  376. if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
  377. !_networkManager.IsInLocalNetwork(remoteEndPoint))
  378. {
  379. _logger.LogInformation(
  380. "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
  381. username,
  382. remoteEndPoint);
  383. throw new SecurityException("Forbidden.");
  384. }
  385. if (!user.IsParentalScheduleAllowed())
  386. {
  387. _logger.LogInformation(
  388. "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
  389. username,
  390. remoteEndPoint);
  391. throw new SecurityException("User is not allowed access at this time.");
  392. }
  393. // Update LastActivityDate and LastLoginDate, then save
  394. if (success)
  395. {
  396. if (isUserSession)
  397. {
  398. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  399. }
  400. user.InvalidLoginAttemptCount = 0;
  401. await UpdateUserAsync(user).ConfigureAwait(false);
  402. _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
  403. }
  404. else
  405. {
  406. IncrementInvalidLoginAttemptCount(user);
  407. _logger.LogInformation(
  408. "Authentication request for {UserName} has been denied (IP: {IP}).",
  409. user.Username,
  410. remoteEndPoint);
  411. }
  412. return success ? user : null;
  413. }
  414. /// <inheritdoc/>
  415. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  416. {
  417. var user = string.IsNullOrWhiteSpace(enteredUsername) ? null : GetUserByName(enteredUsername);
  418. if (user != null && isInNetwork)
  419. {
  420. var passwordResetProvider = GetPasswordResetProvider(user);
  421. return await passwordResetProvider.StartForgotPasswordProcess(user, isInNetwork).ConfigureAwait(false);
  422. }
  423. return new ForgotPasswordResult
  424. {
  425. Action = ForgotPasswordAction.InNetworkRequired,
  426. PinFile = string.Empty
  427. };
  428. }
  429. /// <inheritdoc/>
  430. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  431. {
  432. foreach (var provider in _passwordResetProviders)
  433. {
  434. var result = await provider.RedeemPasswordResetPin(pin).ConfigureAwait(false);
  435. if (result.Success)
  436. {
  437. return result;
  438. }
  439. }
  440. return new PinRedeemResult
  441. {
  442. Success = false,
  443. UsersReset = Array.Empty<string>()
  444. };
  445. }
  446. /// <inheritdoc/>
  447. public void AddParts(IEnumerable<IAuthenticationProvider> authenticationProviders, IEnumerable<IPasswordResetProvider> passwordResetProviders)
  448. {
  449. _authenticationProviders = authenticationProviders.ToArray();
  450. _passwordResetProviders = passwordResetProviders.ToArray();
  451. _invalidAuthProvider = _authenticationProviders.OfType<InvalidAuthProvider>().First();
  452. _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
  453. _defaultPasswordResetProvider = _passwordResetProviders.OfType<DefaultPasswordResetProvider>().First();
  454. }
  455. /// <inheritdoc />
  456. public void Initialize()
  457. {
  458. // TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
  459. var dbContext = _dbProvider.CreateContext();
  460. if (dbContext.Users.Any())
  461. {
  462. return;
  463. }
  464. var defaultName = Environment.UserName;
  465. if (string.IsNullOrWhiteSpace(defaultName))
  466. {
  467. defaultName = "MyJellyfinUser";
  468. }
  469. _logger.LogWarning("No users, creating one with username {UserName}", defaultName);
  470. if (!IsValidUsername(defaultName))
  471. {
  472. throw new ArgumentException("Provided username is not valid!", defaultName);
  473. }
  474. var newUser = CreateUser(defaultName);
  475. newUser.SetPermission(PermissionKind.IsAdministrator, true);
  476. newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
  477. newUser.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, true);
  478. dbContext.Users.Update(newUser);
  479. dbContext.SaveChanges();
  480. }
  481. /// <inheritdoc/>
  482. public NameIdPair[] GetAuthenticationProviders()
  483. {
  484. return _authenticationProviders
  485. .Where(provider => provider.IsEnabled)
  486. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  487. .ThenBy(i => i.Name)
  488. .Select(i => new NameIdPair
  489. {
  490. Name = i.Name,
  491. Id = i.GetType().FullName
  492. })
  493. .ToArray();
  494. }
  495. /// <inheritdoc/>
  496. public NameIdPair[] GetPasswordResetProviders()
  497. {
  498. return _passwordResetProviders
  499. .Where(provider => provider.IsEnabled)
  500. .OrderBy(i => i is DefaultPasswordResetProvider ? 0 : 1)
  501. .ThenBy(i => i.Name)
  502. .Select(i => new NameIdPair
  503. {
  504. Name = i.Name,
  505. Id = i.GetType().FullName
  506. })
  507. .ToArray();
  508. }
  509. /// <inheritdoc/>
  510. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  511. {
  512. var dbContext = _dbProvider.CreateContext();
  513. var user = dbContext.Users.Find(userId) ?? throw new ArgumentException("No user exists with given Id!");
  514. user.SubtitleMode = config.SubtitleMode;
  515. user.HidePlayedInLatest = config.HidePlayedInLatest;
  516. user.EnableLocalPassword = config.EnableLocalPassword;
  517. user.PlayDefaultAudioTrack = config.PlayDefaultAudioTrack;
  518. user.DisplayCollectionsView = config.DisplayCollectionsView;
  519. user.DisplayMissingEpisodes = config.DisplayMissingEpisodes;
  520. user.AudioLanguagePreference = config.AudioLanguagePreference;
  521. user.RememberAudioSelections = config.RememberAudioSelections;
  522. user.EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay;
  523. user.RememberSubtitleSelections = config.RememberSubtitleSelections;
  524. user.SubtitleLanguagePreference = config.SubtitleLanguagePreference;
  525. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  526. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  527. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  528. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  529. dbContext.Update(user);
  530. dbContext.SaveChanges();
  531. }
  532. /// <inheritdoc/>
  533. public void UpdatePolicy(Guid userId, UserPolicy policy)
  534. {
  535. var dbContext = _dbProvider.CreateContext();
  536. var user = dbContext.Users.Find(userId) ?? throw new ArgumentException("No user exists with given Id!");
  537. int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
  538. {
  539. -1 => null,
  540. 0 => 3,
  541. _ => policy.LoginAttemptsBeforeLockout
  542. };
  543. user.MaxParentalAgeRating = policy.MaxParentalRating;
  544. user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
  545. user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
  546. user.AuthenticationProviderId = policy.AuthenticationProviderId;
  547. user.PasswordResetProviderId = policy.PasswordResetProviderId;
  548. user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
  549. user.LoginAttemptsBeforeLockout = maxLoginAttempts;
  550. user.SyncPlayAccess = policy.SyncPlayAccess;
  551. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  552. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  553. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  554. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  555. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  556. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  557. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  558. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  559. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  560. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  561. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  562. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  563. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  564. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  565. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  566. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  567. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  568. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  569. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  570. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  571. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  572. user.AccessSchedules.Clear();
  573. foreach (var policyAccessSchedule in policy.AccessSchedules)
  574. {
  575. user.AccessSchedules.Add(policyAccessSchedule);
  576. }
  577. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  578. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  579. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  580. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  581. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  582. dbContext.Update(user);
  583. dbContext.SaveChanges();
  584. }
  585. private static bool IsValidUsername(string name)
  586. {
  587. // This is some regex that matches only on unicode "word" characters, as well as -, _ and @
  588. // In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
  589. // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), and periods (.)
  590. return Regex.IsMatch(name, @"^[\w\-'._@]*$");
  591. }
  592. private IAuthenticationProvider GetAuthenticationProvider(User user)
  593. {
  594. return GetAuthenticationProviders(user)[0];
  595. }
  596. private IPasswordResetProvider GetPasswordResetProvider(User user)
  597. {
  598. return GetPasswordResetProviders(user)[0];
  599. }
  600. private IList<IAuthenticationProvider> GetAuthenticationProviders(User? user)
  601. {
  602. var authenticationProviderId = user?.AuthenticationProviderId;
  603. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();
  604. if (!string.IsNullOrEmpty(authenticationProviderId))
  605. {
  606. providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
  607. }
  608. if (providers.Count == 0)
  609. {
  610. // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
  611. _logger.LogWarning(
  612. "User {Username} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
  613. user?.Username,
  614. user?.AuthenticationProviderId);
  615. providers = new List<IAuthenticationProvider>
  616. {
  617. _invalidAuthProvider
  618. };
  619. }
  620. return providers;
  621. }
  622. private IList<IPasswordResetProvider> GetPasswordResetProviders(User user)
  623. {
  624. var passwordResetProviderId = user?.PasswordResetProviderId;
  625. var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
  626. if (!string.IsNullOrEmpty(passwordResetProviderId))
  627. {
  628. providers = providers.Where(i =>
  629. string.Equals(passwordResetProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase))
  630. .ToArray();
  631. }
  632. if (providers.Length == 0)
  633. {
  634. providers = new IPasswordResetProvider[]
  635. {
  636. _defaultPasswordResetProvider
  637. };
  638. }
  639. return providers;
  640. }
  641. private async Task<(IAuthenticationProvider? authenticationProvider, string username, bool success)> AuthenticateLocalUser(
  642. string username,
  643. string password,
  644. User? user,
  645. string remoteEndPoint)
  646. {
  647. bool success = false;
  648. IAuthenticationProvider? authenticationProvider = null;
  649. foreach (var provider in GetAuthenticationProviders(user))
  650. {
  651. var providerAuthResult =
  652. await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  653. var updatedUsername = providerAuthResult.username;
  654. success = providerAuthResult.success;
  655. if (success)
  656. {
  657. authenticationProvider = provider;
  658. username = updatedUsername;
  659. break;
  660. }
  661. }
  662. if (!success
  663. && _networkManager.IsInLocalNetwork(remoteEndPoint)
  664. && user?.EnableLocalPassword == true
  665. && !string.IsNullOrEmpty(user.EasyPassword))
  666. {
  667. // Check easy password
  668. var passwordHash = PasswordHash.Parse(user.EasyPassword);
  669. var hash = _cryptoProvider.ComputeHash(
  670. passwordHash.Id,
  671. Encoding.UTF8.GetBytes(password),
  672. passwordHash.Salt.ToArray());
  673. success = passwordHash.Hash.SequenceEqual(hash);
  674. }
  675. return (authenticationProvider, username, success);
  676. }
  677. private async Task<(string username, bool success)> AuthenticateWithProvider(
  678. IAuthenticationProvider provider,
  679. string username,
  680. string password,
  681. User? resolvedUser)
  682. {
  683. try
  684. {
  685. var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
  686. ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
  687. : await provider.Authenticate(username, password).ConfigureAwait(false);
  688. if (authenticationResult.Username != username)
  689. {
  690. _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
  691. username = authenticationResult.Username;
  692. }
  693. return (username, true);
  694. }
  695. catch (AuthenticationException ex)
  696. {
  697. _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
  698. return (username, false);
  699. }
  700. }
  701. private void IncrementInvalidLoginAttemptCount(User user)
  702. {
  703. user.InvalidLoginAttemptCount++;
  704. int? maxInvalidLogins = user.LoginAttemptsBeforeLockout;
  705. if (maxInvalidLogins.HasValue && user.InvalidLoginAttemptCount >= maxInvalidLogins)
  706. {
  707. user.SetPermission(PermissionKind.IsDisabled, true);
  708. OnUserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
  709. _logger.LogWarning(
  710. "Disabling user {Username} due to {Attempts} unsuccessful login attempts.",
  711. user.Username,
  712. user.InvalidLoginAttemptCount);
  713. }
  714. UpdateUser(user);
  715. }
  716. }
  717. }