UserManager.cs 36 KB

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