UserManager.cs 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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)
  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. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  253. UpdateUser(user);
  254. UpdateInvalidLoginAttemptCount(user, 0);
  255. }
  256. else
  257. {
  258. UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1);
  259. }
  260. _logger.Info("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
  261. return success ? user : null;
  262. }
  263. private bool AuthenticateLocalUser(User user, string password, string hashedPassword, string remoteEndPoint)
  264. {
  265. bool success;
  266. if (password == null)
  267. {
  268. // legacy
  269. success = string.Equals(GetPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  270. }
  271. else
  272. {
  273. success = string.Equals(GetPasswordHash(user), GetHashedString(user, password), StringComparison.OrdinalIgnoreCase);
  274. }
  275. if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
  276. {
  277. if (password == null)
  278. {
  279. // legacy
  280. success = string.Equals(GetLocalPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  281. }
  282. else
  283. {
  284. success = string.Equals(GetLocalPasswordHash(user), GetHashedString(user, password), StringComparison.OrdinalIgnoreCase);
  285. }
  286. }
  287. return success;
  288. }
  289. private void UpdateInvalidLoginAttemptCount(User user, int newValue)
  290. {
  291. if (user.Policy.InvalidLoginAttemptCount != newValue || newValue > 0)
  292. {
  293. user.Policy.InvalidLoginAttemptCount = newValue;
  294. var maxCount = user.Policy.IsAdministrator ?
  295. 3 :
  296. 5;
  297. var fireLockout = false;
  298. if (newValue >= maxCount)
  299. {
  300. //_logger.Debug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture));
  301. //user.Policy.IsDisabled = true;
  302. //fireLockout = true;
  303. }
  304. UpdateUserPolicy(user, user.Policy, false);
  305. if (fireLockout)
  306. {
  307. if (UserLockedOut != null)
  308. {
  309. EventHelper.FireEventIfNotNull(UserLockedOut, this, new GenericEventArgs<User>(user), _logger);
  310. }
  311. }
  312. }
  313. }
  314. private string GetPasswordHash(User user)
  315. {
  316. return string.IsNullOrEmpty(user.Password)
  317. ? GetEmptyHashedString(user)
  318. : user.Password;
  319. }
  320. private string GetLocalPasswordHash(User user)
  321. {
  322. return string.IsNullOrEmpty(user.EasyPassword)
  323. ? GetEmptyHashedString(user)
  324. : user.EasyPassword;
  325. }
  326. private bool IsPasswordEmpty(User user, string passwordHash)
  327. {
  328. return string.Equals(passwordHash, GetEmptyHashedString(user), StringComparison.OrdinalIgnoreCase);
  329. }
  330. private string GetEmptyHashedString(User user)
  331. {
  332. return GetHashedString(user, string.Empty);
  333. }
  334. /// <summary>
  335. /// Gets the hashed string.
  336. /// </summary>
  337. private string GetHashedString(User user, string str)
  338. {
  339. var salt = user.Salt;
  340. if (salt != null)
  341. {
  342. // return BCrypt.HashPassword(str, salt);
  343. }
  344. // legacy
  345. return BitConverter.ToString(_cryptographyProvider.ComputeSHA1(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
  346. }
  347. /// <summary>
  348. /// Loads the users from the repository
  349. /// </summary>
  350. /// <returns>IEnumerable{User}.</returns>
  351. private List<User> LoadUsers()
  352. {
  353. var users = UserRepository.RetrieveAllUsers().ToList();
  354. // There always has to be at least one user.
  355. if (users.Count == 0)
  356. {
  357. var name = MakeValidUsername(Environment.UserName);
  358. var user = InstantiateNewUser(name);
  359. user.DateLastSaved = DateTime.UtcNow;
  360. UserRepository.SaveUser(user, CancellationToken.None);
  361. users.Add(user);
  362. user.Policy.IsAdministrator = true;
  363. user.Policy.EnableContentDeletion = true;
  364. user.Policy.EnableRemoteControlOfOtherUsers = true;
  365. UpdateUserPolicy(user, user.Policy, false);
  366. }
  367. return users;
  368. }
  369. public UserDto GetUserDto(User user, string remoteEndPoint = null)
  370. {
  371. if (user == null)
  372. {
  373. throw new ArgumentNullException("user");
  374. }
  375. var passwordHash = GetPasswordHash(user);
  376. var hasConfiguredPassword = !IsPasswordEmpty(user, passwordHash);
  377. var hasConfiguredEasyPassword = !IsPasswordEmpty(user, GetLocalPasswordHash(user));
  378. var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
  379. hasConfiguredEasyPassword :
  380. hasConfiguredPassword;
  381. var dto = new UserDto
  382. {
  383. Id = user.Id.ToString("N"),
  384. Name = user.Name,
  385. HasPassword = hasPassword,
  386. HasConfiguredPassword = hasConfiguredPassword,
  387. HasConfiguredEasyPassword = hasConfiguredEasyPassword,
  388. LastActivityDate = user.LastActivityDate,
  389. LastLoginDate = user.LastLoginDate,
  390. Configuration = user.Configuration,
  391. ConnectLinkType = user.ConnectLinkType,
  392. ConnectUserId = user.ConnectUserId,
  393. ConnectUserName = user.ConnectUserName,
  394. ServerId = _appHost.SystemId,
  395. Policy = user.Policy
  396. };
  397. if (!hasPassword && Users.Count() == 1)
  398. {
  399. dto.EnableAutoLogin = true;
  400. }
  401. var image = user.GetImageInfo(ImageType.Primary, 0);
  402. if (image != null)
  403. {
  404. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  405. try
  406. {
  407. _dtoServiceFactory().AttachPrimaryImageAspectRatio(dto, user);
  408. }
  409. catch (Exception ex)
  410. {
  411. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  412. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  413. }
  414. }
  415. return dto;
  416. }
  417. public UserDto GetOfflineUserDto(User user)
  418. {
  419. var dto = GetUserDto(user);
  420. dto.ServerName = _appHost.FriendlyName;
  421. return dto;
  422. }
  423. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  424. {
  425. try
  426. {
  427. return _imageProcessorFactory().GetImageCacheTag(item, image);
  428. }
  429. catch (Exception ex)
  430. {
  431. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  432. return null;
  433. }
  434. }
  435. /// <summary>
  436. /// Refreshes metadata for each user
  437. /// </summary>
  438. /// <param name="cancellationToken">The cancellation token.</param>
  439. /// <returns>Task.</returns>
  440. public async Task RefreshUsersMetadata(CancellationToken cancellationToken)
  441. {
  442. foreach (var user in Users)
  443. {
  444. await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false);
  445. }
  446. }
  447. /// <summary>
  448. /// Renames the user.
  449. /// </summary>
  450. /// <param name="user">The user.</param>
  451. /// <param name="newName">The new name.</param>
  452. /// <returns>Task.</returns>
  453. /// <exception cref="System.ArgumentNullException">user</exception>
  454. /// <exception cref="System.ArgumentException"></exception>
  455. public async Task RenameUser(User user, string newName)
  456. {
  457. if (user == null)
  458. {
  459. throw new ArgumentNullException("user");
  460. }
  461. if (string.IsNullOrEmpty(newName))
  462. {
  463. throw new ArgumentNullException("newName");
  464. }
  465. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  466. {
  467. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  468. }
  469. if (user.Name.Equals(newName, StringComparison.Ordinal))
  470. {
  471. throw new ArgumentException("The new and old names must be different.");
  472. }
  473. await user.Rename(newName);
  474. OnUserUpdated(user);
  475. }
  476. /// <summary>
  477. /// Updates the user.
  478. /// </summary>
  479. /// <param name="user">The user.</param>
  480. /// <exception cref="System.ArgumentNullException">user</exception>
  481. /// <exception cref="System.ArgumentException"></exception>
  482. public void UpdateUser(User user)
  483. {
  484. if (user == null)
  485. {
  486. throw new ArgumentNullException("user");
  487. }
  488. if (user.Id == Guid.Empty || !Users.Any(u => u.Id.Equals(user.Id)))
  489. {
  490. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  491. }
  492. user.DateModified = DateTime.UtcNow;
  493. user.DateLastSaved = DateTime.UtcNow;
  494. UserRepository.SaveUser(user, CancellationToken.None);
  495. OnUserUpdated(user);
  496. }
  497. public event EventHandler<GenericEventArgs<User>> UserCreated;
  498. private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
  499. /// <summary>
  500. /// Creates the user.
  501. /// </summary>
  502. /// <param name="name">The name.</param>
  503. /// <returns>User.</returns>
  504. /// <exception cref="System.ArgumentNullException">name</exception>
  505. /// <exception cref="System.ArgumentException"></exception>
  506. public async Task<User> CreateUser(string name)
  507. {
  508. if (string.IsNullOrWhiteSpace(name))
  509. {
  510. throw new ArgumentNullException("name");
  511. }
  512. if (!IsValidUsername(name))
  513. {
  514. throw new ArgumentException("Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
  515. }
  516. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  517. {
  518. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  519. }
  520. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  521. try
  522. {
  523. var user = InstantiateNewUser(name);
  524. var list = Users.ToList();
  525. list.Add(user);
  526. Users = list;
  527. user.DateLastSaved = DateTime.UtcNow;
  528. UserRepository.SaveUser(user, CancellationToken.None);
  529. EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  530. return user;
  531. }
  532. finally
  533. {
  534. _userListLock.Release();
  535. }
  536. }
  537. /// <summary>
  538. /// Deletes the user.
  539. /// </summary>
  540. /// <param name="user">The user.</param>
  541. /// <returns>Task.</returns>
  542. /// <exception cref="System.ArgumentNullException">user</exception>
  543. /// <exception cref="System.ArgumentException"></exception>
  544. public async Task DeleteUser(User user)
  545. {
  546. if (user == null)
  547. {
  548. throw new ArgumentNullException("user");
  549. }
  550. if (user.ConnectLinkType.HasValue)
  551. {
  552. await _connectFactory().RemoveConnect(user.Id.ToString("N")).ConfigureAwait(false);
  553. }
  554. var allUsers = Users.ToList();
  555. if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
  556. {
  557. 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));
  558. }
  559. if (allUsers.Count == 1)
  560. {
  561. throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
  562. }
  563. if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1)
  564. {
  565. 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));
  566. }
  567. await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  568. try
  569. {
  570. var configPath = GetConfigurationFilePath(user);
  571. UserRepository.DeleteUser(user, CancellationToken.None);
  572. try
  573. {
  574. _fileSystem.DeleteFile(configPath);
  575. }
  576. catch (IOException ex)
  577. {
  578. _logger.ErrorException("Error deleting file {0}", ex, configPath);
  579. }
  580. DeleteUserPolicy(user);
  581. Users = allUsers.Where(i => i.Id != user.Id).ToList();
  582. OnUserDeleted(user);
  583. }
  584. finally
  585. {
  586. _userListLock.Release();
  587. }
  588. }
  589. /// <summary>
  590. /// Resets the password by clearing it.
  591. /// </summary>
  592. /// <returns>Task.</returns>
  593. public void ResetPassword(User user)
  594. {
  595. ChangePassword(user, string.Empty, null);
  596. }
  597. public void ResetEasyPassword(User user)
  598. {
  599. ChangeEasyPassword(user, string.Empty, null);
  600. }
  601. public void ChangePassword(User user, string newPassword, string newPasswordHash)
  602. {
  603. if (user == null)
  604. {
  605. throw new ArgumentNullException("user");
  606. }
  607. if (newPassword != null)
  608. {
  609. newPasswordHash = GetHashedString(user, newPassword);
  610. }
  611. if (string.IsNullOrWhiteSpace(newPasswordHash))
  612. {
  613. throw new ArgumentNullException("newPasswordHash");
  614. }
  615. if (user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  616. {
  617. throw new ArgumentException("Passwords for guests cannot be changed.");
  618. }
  619. user.Password = newPasswordHash;
  620. UpdateUser(user);
  621. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  622. }
  623. public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
  624. {
  625. if (user == null)
  626. {
  627. throw new ArgumentNullException("user");
  628. }
  629. if (newPassword != null)
  630. {
  631. newPasswordHash = GetHashedString(user, newPassword);
  632. }
  633. if (string.IsNullOrWhiteSpace(newPasswordHash))
  634. {
  635. throw new ArgumentNullException("newPasswordHash");
  636. }
  637. user.EasyPassword = newPasswordHash;
  638. UpdateUser(user);
  639. EventHelper.FireEventIfNotNull(UserPasswordChanged, this, new GenericEventArgs<User>(user), _logger);
  640. }
  641. /// <summary>
  642. /// Instantiates the new user.
  643. /// </summary>
  644. /// <param name="name">The name.</param>
  645. /// <returns>User.</returns>
  646. private User InstantiateNewUser(string name)
  647. {
  648. return new User
  649. {
  650. Name = name,
  651. Id = Guid.NewGuid(),
  652. DateCreated = DateTime.UtcNow,
  653. DateModified = DateTime.UtcNow,
  654. UsesIdForConfigurationPath = true,
  655. //Salt = BCrypt.GenerateSalt()
  656. };
  657. }
  658. private string PasswordResetFile
  659. {
  660. get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); }
  661. }
  662. private string _lastPin;
  663. private PasswordPinCreationResult _lastPasswordPinCreationResult;
  664. private int _pinAttempts;
  665. private PasswordPinCreationResult CreatePasswordResetPin()
  666. {
  667. var num = new Random().Next(1, 9999);
  668. var path = PasswordResetFile;
  669. var pin = num.ToString("0000", CultureInfo.InvariantCulture);
  670. _lastPin = pin;
  671. var time = TimeSpan.FromMinutes(5);
  672. var expiration = DateTime.UtcNow.Add(time);
  673. var text = new StringBuilder();
  674. var localAddress = _appHost.GetLocalApiUrl().Result ?? string.Empty;
  675. text.AppendLine("Use your web browser to visit:");
  676. text.AppendLine(string.Empty);
  677. text.AppendLine(localAddress + "/web/forgotpasswordpin.html");
  678. text.AppendLine(string.Empty);
  679. text.AppendLine("Enter the following pin code:");
  680. text.AppendLine(string.Empty);
  681. text.AppendLine(pin);
  682. text.AppendLine(string.Empty);
  683. var localExpirationTime = expiration.ToLocalTime();
  684. // Tuesday, 22 August 2006 06:30 AM
  685. text.AppendLine("The pin code will expire at " + localExpirationTime.ToString("f1", CultureInfo.CurrentCulture));
  686. _fileSystem.WriteAllText(path, text.ToString(), Encoding.UTF8);
  687. var result = new PasswordPinCreationResult
  688. {
  689. PinFile = path,
  690. ExpirationDate = expiration
  691. };
  692. _lastPasswordPinCreationResult = result;
  693. _pinAttempts = 0;
  694. return result;
  695. }
  696. public ForgotPasswordResult StartForgotPasswordProcess(string enteredUsername, bool isInNetwork)
  697. {
  698. DeletePinFile();
  699. var user = string.IsNullOrWhiteSpace(enteredUsername) ?
  700. null :
  701. GetUserByName(enteredUsername);
  702. if (user != null && user.ConnectLinkType.HasValue && user.ConnectLinkType.Value == UserLinkType.Guest)
  703. {
  704. throw new ArgumentException("Unable to process forgot password request for guests.");
  705. }
  706. var action = ForgotPasswordAction.InNetworkRequired;
  707. string pinFile = null;
  708. DateTime? expirationDate = null;
  709. if (user != null && !user.Policy.IsAdministrator)
  710. {
  711. action = ForgotPasswordAction.ContactAdmin;
  712. }
  713. else
  714. {
  715. if (isInNetwork)
  716. {
  717. action = ForgotPasswordAction.PinCode;
  718. }
  719. var result = CreatePasswordResetPin();
  720. pinFile = result.PinFile;
  721. expirationDate = result.ExpirationDate;
  722. }
  723. return new ForgotPasswordResult
  724. {
  725. Action = action,
  726. PinFile = pinFile,
  727. PinExpirationDate = expirationDate
  728. };
  729. }
  730. public PinRedeemResult RedeemPasswordResetPin(string pin)
  731. {
  732. DeletePinFile();
  733. var usersReset = new List<string>();
  734. var valid = !string.IsNullOrWhiteSpace(_lastPin) &&
  735. string.Equals(_lastPin, pin, StringComparison.OrdinalIgnoreCase) &&
  736. _lastPasswordPinCreationResult != null &&
  737. _lastPasswordPinCreationResult.ExpirationDate > DateTime.UtcNow;
  738. if (valid)
  739. {
  740. _lastPin = null;
  741. _lastPasswordPinCreationResult = null;
  742. var users = Users.Where(i => !i.ConnectLinkType.HasValue || i.ConnectLinkType.Value != UserLinkType.Guest)
  743. .ToList();
  744. foreach (var user in users)
  745. {
  746. ResetPassword(user);
  747. if (user.Policy.IsDisabled)
  748. {
  749. user.Policy.IsDisabled = false;
  750. UpdateUserPolicy(user, user.Policy, true);
  751. }
  752. usersReset.Add(user.Name);
  753. }
  754. }
  755. else
  756. {
  757. _pinAttempts++;
  758. if (_pinAttempts >= 3)
  759. {
  760. _lastPin = null;
  761. _lastPasswordPinCreationResult = null;
  762. }
  763. }
  764. return new PinRedeemResult
  765. {
  766. Success = valid,
  767. UsersReset = usersReset.ToArray()
  768. };
  769. }
  770. private void DeletePinFile()
  771. {
  772. try
  773. {
  774. _fileSystem.DeleteFile(PasswordResetFile);
  775. }
  776. catch
  777. {
  778. }
  779. }
  780. class PasswordPinCreationResult
  781. {
  782. public string PinFile { get; set; }
  783. public DateTime ExpirationDate { get; set; }
  784. }
  785. public UserPolicy GetUserPolicy(User user)
  786. {
  787. var path = GetPolifyFilePath(user);
  788. try
  789. {
  790. lock (_policySyncLock)
  791. {
  792. return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path);
  793. }
  794. }
  795. catch (FileNotFoundException)
  796. {
  797. return GetDefaultPolicy(user);
  798. }
  799. catch (IOException)
  800. {
  801. return GetDefaultPolicy(user);
  802. }
  803. catch (Exception ex)
  804. {
  805. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  806. return GetDefaultPolicy(user);
  807. }
  808. }
  809. private UserPolicy GetDefaultPolicy(User user)
  810. {
  811. return new UserPolicy
  812. {
  813. EnableContentDownloading = true,
  814. EnableSyncTranscoding = true
  815. };
  816. }
  817. private readonly object _policySyncLock = new object();
  818. public void UpdateUserPolicy(string userId, UserPolicy userPolicy)
  819. {
  820. var user = GetUserById(userId);
  821. UpdateUserPolicy(user, userPolicy, true);
  822. }
  823. private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
  824. {
  825. // The xml serializer will output differently if the type is not exact
  826. if (userPolicy.GetType() != typeof(UserPolicy))
  827. {
  828. var json = _jsonSerializer.SerializeToString(userPolicy);
  829. userPolicy = _jsonSerializer.DeserializeFromString<UserPolicy>(json);
  830. }
  831. var path = GetPolifyFilePath(user);
  832. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  833. lock (_policySyncLock)
  834. {
  835. _xmlSerializer.SerializeToFile(userPolicy, path);
  836. user.Policy = userPolicy;
  837. }
  838. UpdateConfiguration(user, user.Configuration, true);
  839. }
  840. private void DeleteUserPolicy(User user)
  841. {
  842. var path = GetPolifyFilePath(user);
  843. try
  844. {
  845. lock (_policySyncLock)
  846. {
  847. _fileSystem.DeleteFile(path);
  848. }
  849. }
  850. catch (IOException)
  851. {
  852. }
  853. catch (Exception ex)
  854. {
  855. _logger.ErrorException("Error deleting policy file", ex);
  856. }
  857. }
  858. private string GetPolifyFilePath(User user)
  859. {
  860. return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml");
  861. }
  862. private string GetConfigurationFilePath(User user)
  863. {
  864. return Path.Combine(user.ConfigurationDirectoryPath, "config.xml");
  865. }
  866. public UserConfiguration GetUserConfiguration(User user)
  867. {
  868. var path = GetConfigurationFilePath(user);
  869. try
  870. {
  871. lock (_configSyncLock)
  872. {
  873. return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path);
  874. }
  875. }
  876. catch (FileNotFoundException)
  877. {
  878. return new UserConfiguration();
  879. }
  880. catch (IOException)
  881. {
  882. return new UserConfiguration();
  883. }
  884. catch (Exception ex)
  885. {
  886. _logger.ErrorException("Error reading policy file: {0}", ex, path);
  887. return new UserConfiguration();
  888. }
  889. }
  890. private readonly object _configSyncLock = new object();
  891. public void UpdateConfiguration(string userId, UserConfiguration config)
  892. {
  893. var user = GetUserById(userId);
  894. UpdateConfiguration(user, config, true);
  895. }
  896. private void UpdateConfiguration(User user, UserConfiguration config, bool fireEvent)
  897. {
  898. var path = GetConfigurationFilePath(user);
  899. // The xml serializer will output differently if the type is not exact
  900. if (config.GetType() != typeof(UserConfiguration))
  901. {
  902. var json = _jsonSerializer.SerializeToString(config);
  903. config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json);
  904. }
  905. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  906. lock (_configSyncLock)
  907. {
  908. _xmlSerializer.SerializeToFile(config, path);
  909. user.Configuration = config;
  910. }
  911. if (fireEvent)
  912. {
  913. EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  914. }
  915. }
  916. }
  917. }