I need to get the user logged in, to do an insert in the log, thus including which user included in the table, made change, and delete. I'm learning language, and I still have a lot of questions.
This is my AccountController controller:
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger _logger;
public AccountController(SignInManager<ApplicationUser> signInManager, ILogger<AccountController> logger)
{
_signInManager = signInManager;
_logger = logger;
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
return RedirectToPage("./Index");
}
But how can I, to get the user logged in, to insert into the log? If it were in a webforms, or winforms, I would have the log table, and would do the insert, shortly after the user action. Was it the same way? And how to get the id and the name of the user that is logged in, to insert it on all pages? In addition to the log, I need to include in some tables, the user who did the action too, how to do this?
Edit: Here's how you log in:
public class LoginModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<LoginModel> _logger;
private readonly ApplicationDbContext _db;
private readonly UserManager<ApplicationUser> _userManager;
public LoginModel(SignInManager<ApplicationUser> signInManager, ILogger<LoginModel> logger,
ApplicationDbContext db, UserManager<ApplicationUser> userManager)
{
_signInManager = signInManager;
_logger = logger;
_db = db;
_userManager = userManager;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
ReturnUrl = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
var user = await _userManager.FindByEmailAsync(Input.Email);
//var count = _db.ShoppingCart.Where(u => u.ApplicationUserId == user.Id).ToList().Count;
//HttpContext.Session.SetInt32("CartCount", count);
_logger.LogInformation("User logged in.");
return LocalRedirect(Url.GetLocalUrl(returnUrl));
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
Edit: I did so: I added this line in the page controller:
private readonly UserManager<ApplicationUser> _userManager;
And I'm trying to get the user id like this:
ApplicationUser user = await _userManager.GetUserAsync(User);
Id = user.Id;
It returns me this error:
Object reference not set to an instance of an object.
In this line:
ApplicationUser user = await _userManager.GetUserAsync(User);
Edit: Controller is this:
[Route("[controller]/[action]")]
public class AccountController : Controller
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger _logger;
private readonly UserManager<ApplicationUser> _userManager;
public AccountController(SignInManager<ApplicationUser> signInManager, ILogger<AccountController> logger, UserManager<ApplicationUser> userManager)
{
_signInManager = signInManager;
_logger = logger;
_userManager = userManager;
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
return RedirectToPage("./Index");
}
}