UserManager.cs 42 KB

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