UserManager.cs 34 KB

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