UserManager.cs 35 KB

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