UserManager.cs 36 KB

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