UserManager.cs 37 KB

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