UserManager.cs 34 KB

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