UserManager.cs 35 KB

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