UserManager.cs 33 KB

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