Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save user last login date if he was logged in with external login provider using ASP .Net Identity?

I've extended AspNetUser class with LastLoginDate property to remember each time user makes login.

public sealed partial class User : IdentityUser<int, UserLogin, UserRole, UserClaim>, IUser<int>, IDatabaseEntity
{
    ...
    public DateTime? LastLoginDate { get; set; }   
}

Loging works fine each time user makes usual login using email and password as login credentials. In AccountController I have my login action:

[HttpPost]
public ActionResult Login(LoginModel model)
{
    ...
    var result = SignInManager.PasswordSignIn(model.Email, model.Password, model.RememberMe);

    if (result == SignInStatus.Success)
    {
        var user = UserManager.FindByEmail(email);
        UserManager.RememberLoginDate(user);  
        return Redirect(model.ReturnUrl);
    }

    ...
}

RememberLoginDate is just an extension methods which basically just sets current time to user LastLoginDate property:

public static IdentityResult RememberLoginDate(this ApplicationUserManager manager, User user)
{
     user.LastLoginDate = DateTime.UtcNow;;
     return manager.Update(user);
}

But when I do external login like below:

[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl, string provider)
{
     var loginInfo = AuthenticationManager.GetExternalLoginInfo();
     if (loginInfo == null)
          return RedirectToAction("ExternalLoginFail");

     // Sign in the user with this external login provider if the user already has a login
     var result = SignInManager.ExternalSignIn(loginInfo);
     if (result == SignInStatus.Success)
          return RedirectToLocal(returnUrl);

     if (result == SignInStatus.Failure)
     {
          return View("ExternalLoginConfirmation" ...) 
     }

     ...
}

How can I log user login date in this case? I have no info about the user such as email or Id to get him with UserManager at this point. I've already tried: User.Identity.GetUserId<int>() to get user Id after SignInManager.ExternalSignIn(loginInfo) but it is not updated after login, it still is default(int) - 0. SignInStatus is just an enum with no additional info about the logged user and use ExternalLoginInfo.Email is also not an option because this email can be different from user's actual registered email.

like image 345
Dmytro Avatar asked Dec 11 '14 01:12

Dmytro


1 Answers

You should be able to use UserManager.FindAsync(loginInfo.Login) to pull your user back via the provider and key - this is how the SignInManager itself works.

like image 90
Matt Lassam-Jones Avatar answered Oct 27 '22 23:10

Matt Lassam-Jones