UserManager.cs 34 KB

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