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

Asked

Viewed 234 times

3

I need to get the logged-in user to log in, thus including which user included in the table, made changes, and delete. I’m learning the language, and I still have many doubts.

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 get the logged in user to log in? If it was in a webforms, or winforms, I would have the log table, and I would do the Insert right after the user action. Would it be the same way? And how to get the id and name of the user who is logged in, to do the Insert on all pages? Besides the log, I need to include in some tables, the user who did the action too, how to do this ?

Edit: This is the way 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 like this: 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");
    }
}

2 answers

3


You can use the UserManager to catch the current user, your code would look 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");
}

This way you have the ApplicationUser and your Id

2

In your Startup class, in the Configuraeservices method, check if there is a line like this, if it doesn’t exist, add:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

In your controller, add in the constructor (if it doesn’t exist) the parameter for Httpcontextaccessor and a Usermanager, create an Applicationuser attribute 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 is worth looking at official documentation.

  • In case then I get the name right? I need to get the Id. This way here I get the name, how do I get the id? string name = Httpcontext.User.Identity.Name;

  • With this object you have access to all user information, id, name, email, phone, etc

  • You can load the data individually with userManager.Getusername(user) or userManager.Getuserid(user)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.