DownloadPersonalData.cshtml.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 bitforum.Models.User;
  11. using Microsoft.AspNetCore.Identity;
  12. using Microsoft.AspNetCore.Mvc;
  13. using Microsoft.AspNetCore.Mvc.RazorPages;
  14. using Microsoft.Extensions.Logging;
  15. namespace bitforum.Areas.Identity.Pages.Account.Manage
  16. {
  17. public class DownloadPersonalDataModel : PageModel
  18. {
  19. private readonly UserManager<ApplicationUser> _userManager;
  20. private readonly ILogger<DownloadPersonalDataModel> _logger;
  21. public DownloadPersonalDataModel(
  22. UserManager<ApplicationUser> userManager,
  23. ILogger<DownloadPersonalDataModel> logger)
  24. {
  25. _userManager = userManager;
  26. _logger = logger;
  27. }
  28. public IActionResult OnGet()
  29. {
  30. return NotFound();
  31. }
  32. public async Task<IActionResult> OnPostAsync()
  33. {
  34. var user = await _userManager.GetUserAsync(User);
  35. if (user == null)
  36. {
  37. return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  38. }
  39. _logger.LogInformation("User with ID '{UserId}' asked for their personal data.", _userManager.GetUserId(User));
  40. // Only include personal data for download
  41. var personalData = new Dictionary<string, string>();
  42. var personalDataProps = typeof(ApplicationUser).GetProperties().Where(
  43. prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute)));
  44. foreach (var p in personalDataProps)
  45. {
  46. personalData.Add(p.Name, p.GetValue(user)?.ToString() ?? "null");
  47. }
  48. var logins = await _userManager.GetLoginsAsync(user);
  49. foreach (var l in logins)
  50. {
  51. personalData.Add($"{l.LoginProvider} external login provider key", l.ProviderKey);
  52. }
  53. personalData.Add($"Authenticator Key", await _userManager.GetAuthenticatorKeyAsync(user));
  54. Response.Headers.TryAdd("Content-Disposition", "attachment; filename=PersonalData.json");
  55. return new FileContentResult(JsonSerializer.SerializeToUtf8Bytes(personalData), "application/json");
  56. }
  57. }
  58. }