UserManager.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.Net;
  10. using MediaBrowser.Controller.Persistence;
  11. using MediaBrowser.Controller.Providers;
  12. using MediaBrowser.Model.Configuration;
  13. using MediaBrowser.Model.Connect;
  14. using MediaBrowser.Model.Dto;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.Events;
  17. using Microsoft.Extensions.Logging;
  18. using MediaBrowser.Model.Serialization;
  19. using MediaBrowser.Model.Users;
  20. using System;
  21. using System.Collections.Generic;
  22. using System.Globalization;
  23. using System.IO;
  24. using System.Linq;
  25. using System.Text;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. using MediaBrowser.Model.Cryptography;
  29. using MediaBrowser.Model.IO;
  30. using MediaBrowser.Controller.Authentication;
  31. using MediaBrowser.Controller.Security;
  32. using MediaBrowser.Controller.Devices;
  33. using MediaBrowser.Controller.Session;
  34. using MediaBrowser.Controller.Plugins;
  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 { get { return _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="System.ArgumentNullException"></exception>
  144. public User GetUserById(Guid id)
  145. {
  146. if (id.Equals(Guid.Empty))
  147. {
  148. throw new ArgumentNullException("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("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 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("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 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("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="System.ArgumentNullException">user</exception>
  530. /// <exception cref="System.ArgumentException"></exception>
  531. public async Task RenameUser(User user, string newName)
  532. {
  533. if (user == null)
  534. {
  535. throw new ArgumentNullException("user");
  536. }
  537. if (string.IsNullOrEmpty(newName))
  538. {
  539. throw new ArgumentNullException("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="System.ArgumentNullException">user</exception>
  557. /// <exception cref="System.ArgumentException"></exception>
  558. public void UpdateUser(User user)
  559. {
  560. if (user == null)
  561. {
  562. throw new ArgumentNullException("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="System.ArgumentNullException">name</exception>
  581. /// <exception cref="System.ArgumentException"></exception>
  582. public async Task<User> CreateUser(string name)
  583. {
  584. if (string.IsNullOrWhiteSpace(name))
  585. {
  586. throw new ArgumentNullException("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="System.ArgumentNullException">user</exception>
  619. /// <exception cref="System.ArgumentException"></exception>
  620. public async Task DeleteUser(User user)
  621. {
  622. if (user == null)
  623. {
  624. throw new ArgumentNullException("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("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("user");
  692. }
  693. if (newPassword != null)
  694. {
  695. newPasswordHash = _defaultAuthenticationProvider.GetHashedString(user, newPassword);
  696. }
  697. if (string.IsNullOrWhiteSpace(newPasswordHash))
  698. {
  699. throw new ArgumentNullException("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 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
  723. {
  724. get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); }
  725. }
  726. private string _lastPin;
  727. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  728. private int _pinAttempts;
  729. private async Task<PasswordPinCreationResult> CreatePasswordResetPin()
  730. {
  731. var num = new Random().Next(1, 9999);
  732. var path = PasswordResetFile;
  733. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  734. _lastPin = pin;
  735. var time = TimeSpan.FromMinutes(5);
  736. var expiration = DateTime.UtcNow.Add(time);
  737. var text = new StringBuilder();
  738. var localAddress = (await _appHost.GetLocalApiUrl(CancellationToken.None).ConfigureAwait(false)) ?? string.Empty;
  739. text.AppendLine("Use your web browser to visit:");
  740. text.AppendLine(string.Empty);
  741. text.AppendLine(localAddress + "/web/forgotpasswordpin.html");
  742. text.AppendLine(string.Empty);
  743. text.AppendLine("Enter the following pin code:");
  744. text.AppendLine(string.Empty);
  745. text.AppendLine(pin);
  746. text.AppendLine(string.Empty);
  747. var localExpirationTime = expiration.ToLocalTime();
  748. // Tuesday, 22 August 2006 06:30 AM
  749. text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
  750. _fileSystem.WriteAllText(path, text.ToString(), Encoding.UTF8);
  751. var result = new PasswordPinCreationResult
  752. {
  753. PinFile = path,
  754. ExpirationDate = expiration
  755. };
  756. _lastPasswordPinCreationResult = result;
  757. _pinAttempts = 0;
  758. return result;
  759. }
  760. public async Task<ForgotPasswordResult> StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  761. {
  762. DeletePinFile();
  763. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  764. null :
  765. GetUserByName(enteredUsername);
  766. if (user != null && user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  767. {
  768. throw new ArgumentException("Unable to process forgot password request for guests.");
  769. }
  770. var action = ForgotPasswordAction.InNetworkRequired;
  771. string pinFile = null;
  772. DateTime? expirationDate = null;
  773. if (user != null && !user.Policy.IsAdministrator)
  774. {
  775. action = ForgotPasswordAction.ContactAdmin;
  776. }
  777. else
  778. {
  779. if (isInNetwork)
  780. {
  781. action = ForgotPasswordAction.PinCode;
  782. }
  783. var result = await CreatePasswordResetPin().ConfigureAwait(false);
  784. pinFile = result.PinFile;
  785. expirationDate = result.ExpirationDate;
  786. }
  787. return new ForgotPasswordResult
  788. {
  789. Action = action,
  790. PinFile = pinFile,
  791. PinExpirationDate = expirationDate
  792. };
  793. }
  794. public async Task<PinRedeemResult> RedeemPasswordResetPin(string pin)
  795. {
  796. DeletePinFile();
  797. var usersReset = new List<string>();
  798. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  799. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  800. _lastPasswordPinCreationResult != null &&
  801. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  802. if (valid)
  803. {
  804. _lastPin = null;
  805. _lastPasswordPinCreationResult = null;
  806. var users = Users.Where(i => !i.ConnectLinkType.HasValue || i.ConnectLinkType.Value != UserLinkType.Guest)
  807. .ToList();
  808. foreach (var user in users)
  809. {
  810. await ResetPassword(user).ConfigureAwait(false);
  811. if (user.Policy.IsDisabled)
  812. {
  813. user.Policy.IsDisabled = false;
  814. UpdateUserPolicy(user, user.Policy, true);
  815. }
  816. usersReset.Add(user.Name);
  817. }
  818. }
  819. else
  820. {
  821. _pinAttempts++;
  822. if (_pinAttempts >= 3)
  823. {
  824. _lastPin = null;
  825. _lastPasswordPinCreationResult = null;
  826. }
  827. }
  828. return new PinRedeemResult
  829. {
  830. Success = valid,
  831. UsersReset = usersReset.ToArray()
  832. };
  833. }
  834. private void DeletePinFile()
  835. {
  836. try
  837. {
  838. _fileSystem.DeleteFile(PasswordResetFile);
  839. }
  840. catch
  841. {
  842. }
  843. }
  844. class PasswordPinCreationResult
  845. {
  846. public string PinFile { get; set; }
  847. public DateTime ExpirationDate { get; set; }
  848. }
  849. public UserPolicy GetUserPolicy(User user)
  850. {
  851. var path = GetPolicyFilePath(user);
  852. try
  853. {
  854. lock (_policySyncLock)
  855. {
  856. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  857. }
  858. }
  859. catch (FileNotFoundException)
  860. {
  861. return GetDefaultPolicy(user);
  862. }
  863. catch (IOException)
  864. {
  865. return GetDefaultPolicy(user);
  866. }
  867. catch (Exception ex)
  868. {
  869. _logger.LogError(ex, "Error reading policy file: {path}", path);
  870. return GetDefaultPolicy(user);
  871. }
  872. }
  873. private UserPolicy GetDefaultPolicy(User user)
  874. {
  875. return new UserPolicy
  876. {
  877. EnableContentDownloading = true,
  878. EnableSyncTranscoding = true
  879. };
  880. }
  881. private readonly object _policySyncLock = new object();
  882. public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
  883. {
  884. var user = GetUserById(userId);
  885. UpdateUserPolicy(user, userPolicy, true);
  886. }
  887. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  888. {
  889. // The xml serializer will output differently if the type is not exact
  890. if (userPolicy.GetType() != typeof(UserPolicy))
  891. {
  892. var json = _jsonSerializer.SerializeToString(userPolicy);
  893. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  894. }
  895. var path = GetPolicyFilePath(user);
  896. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  897. lock (_policySyncLock)
  898. {
  899. _xmlSerializer.SerializeToFile(userPolicy, path);
  900. user.Policy = userPolicy;
  901. }
  902. if (fireEvent)
  903. {
  904. UserPolicyUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  905. }
  906. }
  907. private void DeleteUserPolicy(User user)
  908. {
  909. var path = GetPolicyFilePath(user);
  910. try
  911. {
  912. lock (_policySyncLock)
  913. {
  914. _fileSystem.DeleteFile(path);
  915. }
  916. }
  917. catch (IOException)
  918. {
  919. }
  920. catch (Exception ex)
  921. {
  922. _logger.LogError(ex, "Error deleting policy file");
  923. }
  924. }
  925. private string GetPolicyFilePath(User user)
  926. {
  927. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  928. }
  929. private string GetConfigurationFilePath(User user)
  930. {
  931. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  932. }
  933. public UserConfiguration GetUserConfiguration(User user)
  934. {
  935. var path = GetConfigurationFilePath(user);
  936. try
  937. {
  938. lock (_configSyncLock)
  939. {
  940. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  941. }
  942. }
  943. catch (FileNotFoundException)
  944. {
  945. return new UserConfiguration();
  946. }
  947. catch (IOException)
  948. {
  949. return new UserConfiguration();
  950. }
  951. catch (Exception ex)
  952. {
  953. _logger.LogError(ex, "Error reading policy file: {path}", path);
  954. return new UserConfiguration();
  955. }
  956. }
  957. private readonly object _configSyncLock = new object();
  958. public void UpdateConfiguration(Guid userId, UserConfiguration config)
  959. {
  960. var user = GetUserById(userId);
  961. UpdateConfiguration(user, config);
  962. }
  963. public void UpdateConfiguration(User user, UserConfiguration config)
  964. {
  965. UpdateConfiguration(user, config, true);
  966. }
  967. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  968. {
  969. var path = GetConfigurationFilePath(user);
  970. // The xml serializer will output differently if the type is not exact
  971. if (config.GetType() != typeof(UserConfiguration))
  972. {
  973. var json = _jsonSerializer.SerializeToString(config);
  974. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  975. }
  976. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  977. lock (_configSyncLock)
  978. {
  979. _xmlSerializer.SerializeToFile(config, path);
  980. user.Configuration = config;
  981. }
  982. if (fireEvent)
  983. {
  984. UserConfigurationUpdated?.Invoke(this, new GenericEventArgs<User> { Argument = user });
  985. }
  986. }
  987. }
  988. public class DeviceAccessEntryPoint : IServerEntryPoint
  989. {
  990. private IUserManager _userManager;
  991. private IAuthenticationRepository _authRepo;
  992. private IDeviceManager _deviceManager;
  993. private ISessionManager _sessionManager;
  994. public DeviceAccessEntryPoint(IUserManager userManager, IAuthenticationRepository authRepo, IDeviceManager deviceManager, ISessionManager sessionManager)
  995. {
  996. _userManager = userManager;
  997. _authRepo = authRepo;
  998. _deviceManager = deviceManager;
  999. _sessionManager = sessionManager;
  1000. }
  1001. public void Run()
  1002. {
  1003. _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
  1004. }
  1005. private void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
  1006. {
  1007. var user = e.Argument;
  1008. if (!user.Policy.EnableAllDevices)
  1009. {
  1010. UpdateDeviceAccess(user);
  1011. }
  1012. }
  1013. private void UpdateDeviceAccess(User user)
  1014. {
  1015. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1016. {
  1017. UserId = user.Id
  1018. }).Items;
  1019. foreach (var authInfo in existing)
  1020. {
  1021. if (!string.IsNullOrEmpty(authInfo.DeviceId) && !_deviceManager.CanAccessDevice(user, authInfo.DeviceId))
  1022. {
  1023. _sessionManager.Logout(authInfo);
  1024. }
  1025. }
  1026. }
  1027. public void Dispose()
  1028. {
  1029. }
  1030. }
  1031. }