UserManager.cs 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Common.Events;
  11. using MediaBrowser.Common.Net;
  12. using MediaBrowser.Controller;
  13. using MediaBrowser.Controller.Authentication;
  14. using MediaBrowser.Controller.Configuration;
  15. using MediaBrowser.Controller.Devices;
  16. using MediaBrowser.Controller.Drawing;
  17. using MediaBrowser.Controller.Dto;
  18. using MediaBrowser.Controller.Entities;
  19. using MediaBrowser.Controller.Library;
  20. using MediaBrowser.Controller.Net;
  21. using MediaBrowser.Controller.Persistence;
  22. using MediaBrowser.Controller.Plugins;
  23. using MediaBrowser.Controller.Providers;
  24. using MediaBrowser.Controller.Security;
  25. using MediaBrowser.Controller.Session;
  26. using MediaBrowser.Model.Configuration;
  27. using MediaBrowser.Model.Cryptography;
  28. using MediaBrowser.Model.Dto;
  29. using MediaBrowser.Model.Entities;
  30. using MediaBrowser.Model.Events;
  31. using MediaBrowser.Model.IO;
  32. using MediaBrowser.Model.Serialization;
  33. using MediaBrowser.Model.Users;
  34. using Microsoft.Extensions.Logging;
  35. namespace Emby.Server.Implementations.Library
  36. {
  37. /// <summary>
  38. /// Class UserManager
  39. /// </summary>
  40. public class UserManager : IUserManager
  41. {
  42. /// <summary>
  43. /// Gets the users.
  44. /// </summary>
  45. /// <value>The users.</value>
  46. public IEnumerable<User> Users => _users;
  47. private User[] _users;
  48. /// <summary>
  49. /// The _logger
  50. /// </summary>
  51. private readonly ILogger _logger;
  52. /// <summary>
  53. /// Gets or sets the configuration manager.
  54. /// </summary>
  55. /// <value>The configuration manager.</value>
  56. private IServerConfigurationManager ConfigurationManager { get; set; }
  57. /// <summary>
  58. /// Gets the active user repository
  59. /// </summary>
  60. /// <value>The user repository.</value>
  61. private IUserRepository UserRepository { get; set; }
  62. public event EventHandler<GenericEventArgs<User>> UserPasswordChanged;
  63. private readonly IXmlSerializer _xmlSerializer;
  64. private readonly IJsonSerializer _jsonSerializer;
  65. private readonly INetworkManager _networkManager;
  66. private readonly Func<IImageProcessor> _imageProcessorFactory;
  67. private readonly Func<IDtoService> _dtoServiceFactory;
  68. private readonly IServerApplicationHost _appHost;
  69. private readonly IFileSystem _fileSystem;
  70. private readonly ICryptoProvider _cryptographyProvider;
  71. private IAuthenticationProvider[] _authenticationProviders;
  72. private DefaultAuthenticationProvider _defaultAuthenticationProvider;
  73. public UserManager(
  74. ILoggerFactory loggerFactory,
  75. IServerConfigurationManager configurationManager,
  76. IUserRepository userRepository,
  77. IXmlSerializer xmlSerializer,
  78. INetworkManager networkManager,
  79. Func<IImageProcessor> imageProcessorFactory,
  80. Func<IDtoService> dtoServiceFactory,
  81. IServerApplicationHost appHost,
  82. IJsonSerializer jsonSerializer,
  83. IFileSystem fileSystem,
  84. ICryptoProvider cryptographyProvider)
  85. {
  86. _logger = loggerFactory.CreateLogger(nameof(UserManager));
  87. UserRepository = userRepository;
  88. _xmlSerializer = xmlSerializer;
  89. _networkManager = networkManager;
  90. _imageProcessorFactory = imageProcessorFactory;
  91. _dtoServiceFactory = dtoServiceFactory;
  92. _appHost = appHost;
  93. _jsonSerializer = jsonSerializer;
  94. _fileSystem = fileSystem;
  95. _cryptographyProvider = cryptographyProvider;
  96. ConfigurationManager = configurationManager;
  97. _users = Array.Empty<User>();
  98. DeletePinFile();
  99. }
  100. public NameIdPair[] GetAuthenticationProviders()
  101. {
  102. return _authenticationProviders
  103. .Where(i => i.IsEnabled)
  104. .OrderBy(i => i is DefaultAuthenticationProvider ? 0 : 1)
  105. .ThenBy(i => i.Name)
  106. .Select(i => new NameIdPair
  107. {
  108. Name = i.Name,
  109. Id = GetAuthenticationProviderId(i)
  110. })
  111. .ToArray();
  112. }
  113. public void AddParts(IEnumerable<IAuthenticationProvider> authenticationProviders)
  114. {
  115. _authenticationProviders = authenticationProviders.ToArray();
  116. _defaultAuthenticationProvider = _authenticationProviders.OfType<DefaultAuthenticationProvider>().First();
  117. }
  118. #region UserUpdated Event
  119. /// <summary>
  120. /// Occurs when [user updated].
  121. /// </summary>
  122. public event EventHandler<GenericEventArgs<User>> UserUpdated;
  123. public event EventHandler<GenericEventArgs<User>> UserPolicyUpdated;
  124. public event EventHandler<GenericEventArgs<User>> UserConfigurationUpdated;
  125. public event EventHandler<GenericEventArgs<User>> UserLockedOut;
  126. /// <summary>
  127. /// Called when [user updated].
  128. /// </summary>
  129. /// <param name="user">The user.</param>
  130. private void OnUserUpdated(User user)
  131. {
  132. UserUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  133. }
  134. #endregion
  135. #region UserDeleted Event
  136. /// <summary>
  137. /// Occurs when [user deleted].
  138. /// </summary>
  139. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  140. /// <summary>
  141. /// Called when [user deleted].
  142. /// </summary>
  143. /// <param name="user">The user.</param>
  144. private void OnUserDeleted(User user)
  145. {
  146. UserDeleted?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  147. }
  148. #endregion
  149. /// <summary>
  150. /// Gets a User by Id
  151. /// </summary>
  152. /// <param name="id">The id.</param>
  153. /// <returns>User.</returns>
  154. /// <exception cref="ArgumentNullException"></exception>
  155. public User GetUserById(Guid id)
  156. {
  157. if (id.Equals(Guid.Empty))
  158. {
  159. throw new ArgumentNullException(nameof(id));
  160. }
  161. return Users.FirstOrDefault(u => u.Id == id);
  162. }
  163. /// <summary>
  164. /// Gets the user by identifier.
  165. /// </summary>
  166. /// <param name="id">The identifier.</param>
  167. /// <returns>User.</returns>
  168. public User GetUserById(string id)
  169. {
  170. return GetUserById(new Guid(id));
  171. }
  172. public User GetUserByName(string name)
  173. {
  174. if (string.IsNullOrWhiteSpace(name))
  175. {
  176. throw new ArgumentNullException(nameof(name));
  177. }
  178. return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));
  179. }
  180. public void Initialize()
  181. {
  182. _users = LoadUsers();
  183. var users = Users.ToList();
  184. // If there are no local users with admin rights, make them all admins
  185. if (!users.Any(i => i.Policy.IsAdministrator))
  186. {
  187. foreach (var user in users)
  188. {
  189. user.Policy.IsAdministrator = true;
  190. UpdateUserPolicy(user, user.Policy, false);
  191. }
  192. }
  193. }
  194. public bool IsValidUsername(string username)
  195. {
  196. //The old way was dumb, we should make it less dumb, lets do so.
  197. //This is some regex that matches only on unicode "word" characters, as well as -, _ and @
  198. //In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
  199. string UserNameRegex = "^[\\w-'._@]*$";
  200. // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  201. return Regex.IsMatch(username, UserNameRegex);
  202. }
  203. private static bool IsValidUsernameCharacter(char i)
  204. {
  205. string UserNameRegex = "^[\\w-'._@]*$";
  206. return Regex.IsMatch(i.ToString(), UserNameRegex);
  207. }
  208. public string MakeValidUsername(string username)
  209. {
  210. if (IsValidUsername(username))
  211. {
  212. return username;
  213. }
  214. // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
  215. var builder = new StringBuilder();
  216. foreach (var c in username)
  217. {
  218. if (IsValidUsernameCharacter(c))
  219. {
  220. builder.Append(c);
  221. }
  222. }
  223. return builder.ToString();
  224. }
  225. public async Task<User> AuthenticateUser(string username, string password, string hashedPassword, string remoteEndPoint, bool isUserSession)
  226. {
  227. if (string.IsNullOrWhiteSpace(username))
  228. {
  229. throw new ArgumentNullException(nameof(username));
  230. }
  231. var user = Users
  232. .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  233. var success = false;
  234. IAuthenticationProvider authenticationProvider = null;
  235. if (user != null)
  236. {
  237. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, user, remoteEndPoint).ConfigureAwait(false);
  238. authenticationProvider = authResult.Item1;
  239. success = authResult.Item2;
  240. }
  241. else
  242. {
  243. // user is null
  244. var authResult = await AuthenticateLocalUser(username, password, hashedPassword, null, remoteEndPoint).ConfigureAwait(false);
  245. authenticationProvider = authResult.Item1;
  246. success = authResult.Item2;
  247. if (success && authenticationProvider != null && !(authenticationProvider is DefaultAuthenticationProvider))
  248. {
  249. user = await CreateUser(username).ConfigureAwait(false);
  250. var hasNewUserPolicy = authenticationProvider as IHasNewUserPolicy;
  251. if (hasNewUserPolicy != null)
  252. {
  253. var policy = hasNewUserPolicy.GetNewUserPolicy();
  254. UpdateUserPolicy(user, policy, true);
  255. }
  256. }
  257. }
  258. if (success && user != null && authenticationProvider != null)
  259. {
  260. var providerId = GetAuthenticationProviderId(authenticationProvider);
  261. if (!string.Equals(providerId, user.Policy.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
  262. {
  263. user.Policy.AuthenticationProviderId = providerId;
  264. UpdateUserPolicy(user, user.Policy, true);
  265. }
  266. }
  267. if (user == null)
  268. {
  269. throw new SecurityException("Invalid username or password entered.");
  270. }
  271. if (user.Policy.IsDisabled)
  272. {
  273. throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  274. }
  275. if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint))
  276. {
  277. throw new SecurityException("Forbidden.");
  278. }
  279. if (!user.IsParentalScheduleAllowed())
  280. {
  281. throw new SecurityException("User is not allowed access at this time.");
  282. }
  283. // Update LastActivityDate and LastLoginDate, then save
  284. if (success)
  285. {
  286. if (isUserSession)
  287. {
  288. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  289. UpdateUser(user);
  290. }
  291. UpdateInvalidLoginAttemptCount(user, 0);
  292. }
  293. else
  294. {
  295. UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1);
  296. }
  297. _logger.LogInformation("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
  298. return success ? user : null;
  299. }
  300. private static string GetAuthenticationProviderId(IAuthenticationProvider provider)
  301. {
  302. return provider.GetType().FullName;
  303. }
  304. private IAuthenticationProvider GetAuthenticationProvider(User user)
  305. {
  306. return GetAuthenticationProviders(user).First();
  307. }
  308. private IAuthenticationProvider[] GetAuthenticationProviders(User user)
  309. {
  310. var authenticationProviderId = user == null ? null : user.Policy.AuthenticationProviderId;
  311. var providers = _authenticationProviders.Where(i => i.IsEnabled).ToArray();
  312. if (!string.IsNullOrEmpty(authenticationProviderId))
  313. {
  314. providers = providers.Where(i => string.Equals(authenticationProviderId, GetAuthenticationProviderId(i), StringComparison.OrdinalIgnoreCase)).ToArray();
  315. }
  316. if (providers.Length == 0)
  317. {
  318. providers = new IAuthenticationProvider[] { _defaultAuthenticationProvider };
  319. }
  320. return providers;
  321. }
  322. private async Task<bool> AuthenticateWithProvider(IAuthenticationProvider provider, string username, string password, User resolvedUser)
  323. {
  324. try
  325. {
  326. var requiresResolvedUser = provider as IRequiresResolvedUser;
  327. if (requiresResolvedUser != null)
  328. {
  329. await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false);
  330. }
  331. else
  332. {
  333. await provider.Authenticate(username, password).ConfigureAwait(false);
  334. }
  335. return true;
  336. }
  337. catch (Exception ex)
  338. {
  339. _logger.LogError(ex, "Error authenticating with provider {provider}", provider.Name);
  340. return false;
  341. }
  342. }
  343. private async Task<Tuple<IAuthenticationProvider, bool>> AuthenticateLocalUser(string username, string password, string hashedPassword, User user, string remoteEndPoint)
  344. {
  345. bool success = false;
  346. IAuthenticationProvider authenticationProvider = null;
  347. if (password != null && user != null)
  348. {
  349. // Doesn't look like this is even possible to be used, because of password == null checks below
  350. hashedPassword = _defaultAuthenticationProvider.GetHashedString(user, password);
  351. }
  352. if (password == null)
  353. {
  354. // legacy
  355. success = string.Equals(_defaultAuthenticationProvider.GetPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  356. }
  357. else
  358. {
  359. foreach (var provider in GetAuthenticationProviders(user))
  360. {
  361. success = await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
  362. if (success)
  363. {
  364. authenticationProvider = provider;
  365. break;
  366. }
  367. }
  368. }
  369. if (user != null)
  370. {
  371. if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
  372. {
  373. if (password == null)
  374. {
  375. // legacy
  376. success = string.Equals(GetLocalPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  377. }
  378. else
  379. {
  380. success = string.Equals(GetLocalPasswordHash(user), _defaultAuthenticationProvider.GetHashedString(user, password), StringComparison.OrdinalIgnoreCase);
  381. }
  382. }
  383. }
  384. return new Tuple<IAuthenticationProvider, bool>(authenticationProvider, success);
  385. }
  386. private void UpdateInvalidLoginAttemptCount(User user, int newValue)
  387. {
  388. if (user.Policy.InvalidLoginAttemptCount == newValue || newValue <= 0)
  389. {
  390. return;
  391. }
  392. user.Policy.InvalidLoginAttemptCount = newValue;
  393. var maxCount = user.Policy.IsAdministrator ? 3 : 5;
  394. var fireLockout = false;
  395. if (newValue >= maxCount)
  396. {
  397. _logger.LogDebug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue);
  398. user.Policy.IsDisabled = true;
  399. fireLockout = true;
  400. }
  401. UpdateUserPolicy(user, user.Policy, false);
  402. if (fireLockout)
  403. {
  404. UserLockedOut?.Invoke(this, new GenericEventArgs<User>(user));
  405. }
  406. }
  407. private string GetLocalPasswordHash(User user)
  408. {
  409. return string.IsNullOrEmpty(user.EasyPassword)
  410. ? _defaultAuthenticationProvider.GetEmptyHashedString(user)
  411. : user.EasyPassword;
  412. }
  413. private bool IsPasswordEmpty(User user, string passwordHash)
  414. {
  415. return string.Equals(passwordHash, _defaultAuthenticationProvider.GetEmptyHashedString(user), StringComparison.OrdinalIgnoreCase);
  416. }
  417. /// <summary>
  418. /// Loads the users from the repository
  419. /// </summary>
  420. /// <returns>IEnumerable{User}.</returns>
  421. private User[] LoadUsers()
  422. {
  423. var users = UserRepository.RetrieveAllUsers();
  424. // There always has to be at least one user.
  425. if (users.Count == 0)
  426. {
  427. var defaultName = Environment.UserName;
  428. if (string.IsNullOrWhiteSpace(defaultName))
  429. {
  430. defaultName = "MyJellyfinUser";
  431. }
  432. var name = MakeValidUsername(defaultName);
  433. var user = InstantiateNewUser(name);
  434. user.DateLastSaved = DateTime.UtcNow;
  435. UserRepository.CreateUser(user);
  436. users.Add(user);
  437. user.Policy.IsAdministrator = true;
  438. user.Policy.EnableContentDeletion = true;
  439. user.Policy.EnableRemoteControlOfOtherUsers = true;
  440. UpdateUserPolicy(user, user.Policy, false);
  441. }
  442. return users.ToArray();
  443. }
  444. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  445. {
  446. if (user == null)
  447. {
  448. throw new ArgumentNullException(nameof(user));
  449. }
  450. var hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result;
  451. var hasConfiguredEasyPassword = !IsPasswordEmpty(user, GetLocalPasswordHash(user));
  452. var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  453. hasConfiguredEasyPassword :
  454. hasConfiguredPassword;
  455. var dto = new UserDto
  456. {
  457. Id = user.Id,
  458. Name = user.Name,
  459. HasPassword = hasPassword,
  460. HasConfiguredPassword = hasConfiguredPassword,
  461. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  462. LastActivityDate = user.LastActivityDate,
  463. LastLoginDate = user.LastLoginDate,
  464. Configuration = user.Configuration,
  465. ServerId = _appHost.SystemId,
  466. Policy = user.Policy
  467. };
  468. if (!hasPassword && Users.Count() == 1)
  469. {
  470. dto.EnableAutoLogin = true;
  471. }
  472. var image = user.GetImageInfo(ImageType.Primary, 0);
  473. if (image != null)
  474. {
  475. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  476. try
  477. {
  478. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  479. }
  480. catch (Exception ex)
  481. {
  482. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  483. _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {user}", user.Name);
  484. }
  485. }
  486. return dto;
  487. }
  488. public UserDto GetOfflineUserDto(User user)
  489. {
  490. var dto = GetUserDto(user);
  491. dto.ServerName = _appHost.FriendlyName;
  492. return dto;
  493. }
  494. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  495. {
  496. try
  497. {
  498. return _imageProcessorFactory().GetImageCacheTag(item, image);
  499. }
  500. catch (Exception ex)
  501. {
  502. _logger.LogError(ex, "Error getting {imageType} image info for {imagePath}", image.Type, image.Path);
  503. return null;
  504. }
  505. }
  506. /// <summary>
  507. /// Refreshes metadata for each user
  508. /// </summary>
  509. /// <param name="cancellationToken">The cancellation token.</param>
  510. /// <returns>Task.</returns>
  511. public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
  512. {
  513. foreach (var user in Users)
  514. {
  515. await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false);
  516. }
  517. }
  518. /// <summary>
  519. /// Renames the user.
  520. /// </summary>
  521. /// <param name="user">The user.</param>
  522. /// <param name="newName">The new name.</param>
  523. /// <returns>Task.</returns>
  524. /// <exception cref="ArgumentNullException">user</exception>
  525. /// <exception cref="ArgumentException"></exception>
  526. public async Task RenameUser(User user, string newName)
  527. {
  528. if (user == null)
  529. {
  530. throw new ArgumentNullException(nameof(user));
  531. }
  532. if (string.IsNullOrEmpty(newName))
  533. {
  534. throw new ArgumentNullException(nameof(newName));
  535. }
  536. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  537. {
  538. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  539. }
  540. if (user.Name.Equals(newName, StringComparison.Ordinal))
  541. {
  542. throw new ArgumentException("The new and old names must be different.");
  543. }
  544. await user.Rename(newName);
  545. OnUserUpdated(user);
  546. }
  547. /// <summary>
  548. /// Updates the user.
  549. /// </summary>
  550. /// <param name="user">The user.</param>
  551. /// <exception cref="ArgumentNullException">user</exception>
  552. /// <exception cref="ArgumentException"></exception>
  553. public void UpdateUser(User user)
  554. {
  555. if (user == null)
  556. {
  557. throw new ArgumentNullException(nameof(user));
  558. }
  559. if (user.Id.Equals(Guid.Empty) || !Users.Any(u => u.Id.Equals(user.Id)))
  560. {
  561. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  562. }
  563. user.DateModified = DateTime.UtcNow;
  564. user.DateLastSaved = DateTime.UtcNow;
  565. UserRepository.UpdateUser(user);
  566. OnUserUpdated(user);
  567. }
  568. public event EventHandler<GenericEventArgs<User>> UserCreated;
  569. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  570. /// <summary>
  571. /// Creates the user.
  572. /// </summary>
  573. /// <param name="name">The name.</param>
  574. /// <returns>User.</returns>
  575. /// <exception cref="ArgumentNullException">name</exception>
  576. /// <exception cref="ArgumentException"></exception>
  577. public async Task<User> CreateUser(string name)
  578. {
  579. if (string.IsNullOrWhiteSpace(name))
  580. {
  581. throw new ArgumentNullException(nameof(name));
  582. }
  583. if (!IsValidUsername(name))
  584. {
  585. throw new ArgumentException("Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  586. }
  587. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  588. {
  589. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  590. }
  591. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  592. try
  593. {
  594. var user = InstantiateNewUser(name);
  595. var list = Users.ToList();
  596. list.Add(user);
  597. _users = list.ToArray();
  598. user.DateLastSaved = DateTime.UtcNow;
  599. UserRepository.CreateUser(user);
  600. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  601. return user;
  602. }
  603. finally
  604. {
  605. _userListLock.Release();
  606. }
  607. }
  608. /// <summary>
  609. /// Deletes the user.
  610. /// </summary>
  611. /// <param name="user">The user.</param>
  612. /// <returns>Task.</returns>
  613. /// <exception cref="ArgumentNullException">user</exception>
  614. /// <exception cref="ArgumentException"></exception>
  615. public async Task DeleteUser(User user)
  616. {
  617. if (user == null)
  618. {
  619. throw new ArgumentNullException(nameof(user));
  620. }
  621. var allUsers = Users.ToList();
  622. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  623. {
  624. throw new ArgumentException(string.Format("The user cannot be deleted because there is no user with the Name {0} and Id {1}.", user.Name, user.Id));
  625. }
  626. if (allUsers.Count == 1)
  627. {
  628. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  629. }
  630. if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1)
  631. {
  632. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one admin user in the system.", user.Name));
  633. }
  634. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  635. try
  636. {
  637. var configPath = GetConfigurationFilePath(user);
  638. UserRepository.DeleteUser(user);
  639. try
  640. {
  641. _fileSystem.DeleteFile(configPath);
  642. }
  643. catch (IOException ex)
  644. {
  645. _logger.LogError(ex, "Error deleting file {path}", configPath);
  646. }
  647. DeleteUserPolicy(user);
  648. _users = allUsers.Where(i => i.Id != user.Id).ToArray();
  649. OnUserDeleted(user);
  650. }
  651. finally
  652. {
  653. _userListLock.Release();
  654. }
  655. }
  656. /// <summary>
  657. /// Resets the password by clearing it.
  658. /// </summary>
  659. /// <returns>Task.</returns>
  660. public Task ResetPassword(User user)
  661. {
  662. return ChangePassword(user, string.Empty);
  663. }
  664. public void ResetEasyPassword(User user)
  665. {
  666. ChangeEasyPassword(user, string.Empty, null);
  667. }
  668. public async Task ChangePassword(User user, string newPassword)
  669. {
  670. if (user == null)
  671. {
  672. throw new ArgumentNullException(nameof(user));
  673. }
  674. await GetAuthenticationProvider(user).ChangePassword(user, newPassword).ConfigureAwait(false);
  675. UpdateUser(user);
  676. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  677. }
  678. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  679. {
  680. if (user == null)
  681. {
  682. throw new ArgumentNullException(nameof(user));
  683. }
  684. if (newPassword != null)
  685. {
  686. newPasswordHash = _defaultAuthenticationProvider.GetHashedString(user, newPassword);
  687. }
  688. if (string.IsNullOrWhiteSpace(newPasswordHash))
  689. {
  690. throw new ArgumentNullException(nameof(newPasswordHash));
  691. }
  692. user.EasyPassword = newPasswordHash;
  693. UpdateUser(user);
  694. UserPasswordChanged?.Invoke(this, new GenericEventArgs<User>(user));
  695. }
  696. /// <summary>
  697. /// Instantiates the new user.
  698. /// </summary>
  699. /// <param name="name">The name.</param>
  700. /// <returns>User.</returns>
  701. private static User InstantiateNewUser(string name)
  702. {
  703. return new User
  704. {
  705. Name = name,
  706. Id = Guid.NewGuid(),
  707. DateCreated = DateTime.UtcNow,
  708. DateModified = DateTime.UtcNow,
  709. UsesIdForConfigurationPath = true,
  710. //Salt = BCrypt.GenerateSalt()
  711. };
  712. }
  713. private string PasswordResetFile => Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt");
  714. private string _lastPin;
  715. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  716. private int _pinAttempts;
  717. private async Task<PasswordPinCreationResult> CreatePasswordResetPin()
  718. {
  719. var num = new Random().Next(1, 9999);
  720. var path = PasswordResetFile;
  721. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  722. _lastPin = pin;
  723. var time = TimeSpan.FromMinutes(5);
  724. var expiration = DateTime.UtcNow.Add(time);
  725. var text = new StringBuilder();
  726. var localAddress = (await _appHost.GetLocalApiUrl(CancellationToken.None).ConfigureAwait(false)) ?? string.Empty;
  727. text.AppendLine("Use your web browser to visit:");
  728. text.AppendLine(string.Empty);
  729. text.AppendLine(localAddress + "/web/index.html#!/forgotpasswordpin.html");
  730. text.AppendLine(string.Empty);
  731. text.AppendLine("Enter the following pin code:");
  732. text.AppendLine(string.Empty);
  733. text.AppendLine(pin);
  734. text.AppendLine(string.Empty);
  735. var localExpirationTime = expiration.ToLocalTime();
  736. // Tuesday, 22 August 2006 06:30 AM
  737. text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
  738. File.WriteAllText(path, text.ToString(), Encoding.UTF8);
  739. var result = new PasswordPinCreationResult
  740. {
  741. PinFile = path,
  742. ExpirationDate = expiration
  743. };
  744. _lastPasswordPinCreationResult = result;
  745. _pinAttempts = 0;
  746. return result;
  747. }
  748. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  749. {
  750. DeletePinFile();
  751. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  752. null :
  753. GetUserByName(enteredUsername);
  754. var action = ForgotPasswordAction.InNetworkRequired;
  755. string pinFile = null;
  756. DateTime? expirationDate = null;
  757. if (user != null && !user.Policy.IsAdministrator)
  758. {
  759. action = ForgotPasswordAction.ContactAdmin;
  760. }
  761. else
  762. {
  763. if (isInNetwork)
  764. {
  765. action = ForgotPasswordAction.PinCode;
  766. }
  767. var result = await CreatePasswordResetPin().ConfigureAwait(false);
  768. pinFile = result.PinFile;
  769. expirationDate = result.ExpirationDate;
  770. }
  771. return new ForgotPasswordResult
  772. {
  773. Action = action,
  774. PinFile = pinFile,
  775. PinExpirationDate = expirationDate
  776. };
  777. }
  778. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  779. {
  780. DeletePinFile();
  781. var usersReset = new List<string>();
  782. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  783. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  784. _lastPasswordPinCreationResult != null &&
  785. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  786. if (valid)
  787. {
  788. _lastPin = null;
  789. _lastPasswordPinCreationResult = null;
  790. foreach (var user in Users)
  791. {
  792. await ResetPassword(user).ConfigureAwait(false);
  793. if (user.Policy.IsDisabled)
  794. {
  795. user.Policy.IsDisabled = false;
  796. UpdateUserPolicy(user, user.Policy, true);
  797. }
  798. usersReset.Add(user.Name);
  799. }
  800. }
  801. else
  802. {
  803. _pinAttempts++;
  804. if (_pinAttempts >= 3)
  805. {
  806. _lastPin = null;
  807. _lastPasswordPinCreationResult = null;
  808. }
  809. }
  810. return new PinRedeemResult
  811. {
  812. Success = valid,
  813. UsersReset = usersReset.ToArray()
  814. };
  815. }
  816. private void DeletePinFile()
  817. {
  818. try
  819. {
  820. _fileSystem.DeleteFile(PasswordResetFile);
  821. }
  822. catch
  823. {
  824. }
  825. }
  826. class PasswordPinCreationResult
  827. {
  828. public string PinFile { get; set; }
  829. public DateTime ExpirationDate { get; set; }
  830. }
  831. public UserPolicy GetUserPolicy(User user)
  832. {
  833. var path = GetPolicyFilePath(user);
  834. if (!File.Exists(path))
  835. {
  836. return GetDefaultPolicy(user);
  837. }
  838. try
  839. {
  840. lock (_policySyncLock)
  841. {
  842. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  843. }
  844. }
  845. catch (IOException)
  846. {
  847. return GetDefaultPolicy(user);
  848. }
  849. catch (Exception ex)
  850. {
  851. _logger.LogError(ex, "Error reading policy file: {path}", path);
  852. return GetDefaultPolicy(user);
  853. }
  854. }
  855. private static UserPolicy GetDefaultPolicy(User user)
  856. {
  857. return new UserPolicy
  858. {
  859. EnableContentDownloading = true,
  860. EnableSyncTranscoding = true
  861. };
  862. }
  863. private readonly object _policySyncLock = new object();
  864. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  865. {
  866. var user = GetUserById(userId);
  867. UpdateUserPolicy(user, userPolicy, true);
  868. }
  869. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  870. {
  871. // The xml serializer will output differently if the type is not exact
  872. if (userPolicy.GetType() != typeof(UserPolicy))
  873. {
  874. var json = _jsonSerializer.SerializeToString(userPolicy);
  875. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  876. }
  877. var path = GetPolicyFilePath(user);
  878. Directory.CreateDirectory(Path.GetDirectoryName(path));
  879. lock (_policySyncLock)
  880. {
  881. _xmlSerializer.SerializeToFile(userPolicy, path);
  882. user.Policy = userPolicy;
  883. }
  884. if (fireEvent)
  885. {
  886. UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  887. }
  888. }
  889. private void DeleteUserPolicy(User user)
  890. {
  891. var path = GetPolicyFilePath(user);
  892. try
  893. {
  894. lock (_policySyncLock)
  895. {
  896. _fileSystem.DeleteFile(path);
  897. }
  898. }
  899. catch (IOException)
  900. {
  901. }
  902. catch (Exception ex)
  903. {
  904. _logger.LogError(ex, "Error deleting policy file");
  905. }
  906. }
  907. private static string GetPolicyFilePath(User user)
  908. {
  909. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  910. }
  911. private static string GetConfigurationFilePath(User user)
  912. {
  913. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  914. }
  915. public UserConfiguration GetUserConfiguration(User user)
  916. {
  917. var path = GetConfigurationFilePath(user);
  918. if (!File.Exists(path))
  919. {
  920. return new UserConfiguration();
  921. }
  922. try
  923. {
  924. lock (_configSyncLock)
  925. {
  926. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  927. }
  928. }
  929. catch (IOException)
  930. {
  931. return new UserConfiguration();
  932. }
  933. catch (Exception ex)
  934. {
  935. _logger.LogError(ex, "Error reading policy file: {path}", path);
  936. return new UserConfiguration();
  937. }
  938. }
  939. private readonly object _configSyncLock = new object();
  940. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  941. {
  942. var user = GetUserById(userId);
  943. UpdateConfiguration(user, config);
  944. }
  945. public void UpdateConfiguration(User user, UserConfiguration config)
  946. {
  947. UpdateConfiguration(user, config, true);
  948. }
  949. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  950. {
  951. var path = GetConfigurationFilePath(user);
  952. // The xml serializer will output differently if the type is not exact
  953. if (config.GetType() != typeof(UserConfiguration))
  954. {
  955. var json = _jsonSerializer.SerializeToString(config);
  956. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  957. }
  958. Directory.CreateDirectory(Path.GetDirectoryName(path));
  959. lock (_configSyncLock)
  960. {
  961. _xmlSerializer.SerializeToFile(config, path);
  962. user.Configuration = config;
  963. }
  964. if (fireEvent)
  965. {
  966. UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  967. }
  968. }
  969. }
  970. public class DeviceAccessEntryPoint : IServerEntryPoint
  971. {
  972. private IUserManager _userManager;
  973. private IAuthenticationRepository _authRepo;
  974. private IDeviceManager _deviceManager;
  975. private ISessionManager _sessionManager;
  976. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  977. {
  978. _userManager = userManager;
  979. _authRepo = authRepo;
  980. _deviceManager = deviceManager;
  981. _sessionManager = sessionManager;
  982. }
  983. public Task RunAsync()
  984. {
  985. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  986. return Task.CompletedTask;
  987. }
  988. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  989. {
  990. var user = e.Argument;
  991. if (!user.Policy.EnableAllDevices)
  992. {
  993. UpdateDeviceAccess(user);
  994. }
  995. }
  996. private void UpdateDeviceAccess(User user)
  997. {
  998. var existing = _authRepo.Get(new AuthenticationInfoQuery
  999. {
  1000. UserId = user.Id
  1001. }).Items;
  1002. foreach (var authInfo in existing)
  1003. {
  1004. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  1005. {
  1006. _sessionManager.Logout(authInfo);
  1007. }
  1008. }
  1009. }
  1010. public void Dispose()
  1011. {
  1012. }
  1013. }
  1014. }