DownloadPersonalData.cshtml.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. #nullable disable
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.Json;
  9. using System.Threading.Tasks;
  10. using Microsoft.AspNetCore.Identity;
  11. using Microsoft.AspNetCore.Mvc;
  12. using Microsoft.AspNetCore.Mvc.RazorPages;
  13. using Microsoft.Extensions.Logging;
  14. namespace bitforum.Areas.Identity.Pages.Account.Manage
  15. {
  16. public class DownloadPersonalDataModel : PageModel
  17. {
  18. private readonly UserManager<IdentityUser> _userManager;
  19. private readonly ILogger<DownloadPersonalDataModel> _logger;
  20. public DownloadPersonalDataModel(
  21. UserManager<IdentityUser> userManager,
  22. ILogger<DownloadPersonalDataModel> logger)
  23. {
  24. _userManager = userManager;
  25. _logger = logger;
  26. }
  27. public IActionResult OnGet()
  28. {
  29. return NotFound();
  30. }
  31. public async Task<IActionResult> OnPostAsync()
  32. {
  33. var user = await _userManager.GetUserAsync(User);
  34. if (user == null)
  35. {
  36. return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  37. }
  38. _logger.LogInformation("User with ID '{UserId}' asked for their personal data.", _userManager.GetUserId(User));
  39. // Only include personal data for download
  40. var personalData = new Dictionary<string, string>();
  41. var personalDataProps = typeof(IdentityUser).GetProperties().Where(
  42. prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute)));
  43. foreach (var p in personalDataProps)
  44. {
  45. personalData.Add(p.Name, p.GetValue(user)?.ToString() ?? "null");
  46. }
  47. var logins = await _userManager.GetLoginsAsync(user);
  48. foreach (var l in logins)
  49. {
  50. personalData.Add($"{l.LoginProvider} external login provider key", l.ProviderKey);
  51. }
  52. personalData.Add($"Authenticator Key", await _userManager.GetAuthenticatorKeyAsync(user));
  53. Response.Headers.TryAdd("Content-Disposition", "attachment; filename=PersonalData.json");
  54. return new FileContentResult(JsonSerializer.SerializeToUtf8Bytes(personalData), "application/json");
  55. }
  56. }
  57. }