How can I do to get the insert in the log with logged in user? Identity - Asp.net core 2.0

2

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");
    }
}
    
asked by anonymous 10.07.2018 / 16:50

2 answers

2

You can use UserManager to get the current user, your code looks like this:

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;
}

public async Task<IActionResult> FazAlgumaCoisa()
{
    ApplicationUser user = await _userManager.GetUserAsync(User);
    return View();
}


[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
    await _signInManager.SignOutAsync();
    _logger.LogInformation("User logged out.");
    return RedirectToPage("./Index");
}

In this way you have ApplicationUser and its Id

    
11.07.2018 / 15:59
1

In your Startup class, in the ConfigureServices method, check if there is a line like this, if it does not exist, add:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

In your controller, add the parameter to the HttpContextAccessor and a UserManager in the constructor (if it does not exist), create an attribute of type ApplicationUser in your controller and do this:

public Controller(IHttpContextAccessor httpContextAccessor, UserManager<ApplicationUser> userManager) {
    var user = httpContextAccessor.HttpUser.User;
    var getUserTask = userManager.GetUserAsync(user);
    getUserTask.Wait();

    User = getUserTask.Result;
}

If you want some specific information, there are synchronous methods like GetUserId, GetUserName, etc., it's worth looking at official documentation .

    
10.07.2018 / 17:08