UserManager.cs 42 KB

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