UserManager.cs 42 KB

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