2
0

UserManager.cs 37 KB

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