UserManager.cs 36 KB

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