UserManager.cs 34 KB

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