0

Ok, an afternoon down the drain, I concede to SO assistance. My login method is pretty standard. As shown below, I'm using WebSecurity.Login.

Right after that, I want to run a check to see if the user's profile is completed and if it isn't, send them over to that view.

Controller

[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
    {

        if (!User.IsInRole("User"))
        {
            if (!IsProfileComplete(WebSecurity.GetUserId(User.Identity.Name)))
            {
                return RedirectToAction("ProfileCompletion");
            }

            if(!User.IsInRole("User")) Roles.AddUserToRole(User.Identity.Name, "Vendor");
        }
        else // user has role
        {
            return RedirectToAction("Index", "Dashboard");
        }
    }

    ModelState.AddModelError("", "Unknown username or password.");
    return View(model);
}

I've stepped through it a bunch....after WebSecurity.Login I was under the impression the WebSecurity user data would get set but WebSecurity.GetUserId(User.Identity.Name) comes back as -1

Even when a user has completed profile, it will redirect them to the profile completion because it is trying to look up profile for userid -1

Is there something about the http post and login context set that I'm missing? The end result I am looking for is to just make sure a user has completed the profile page before let into the system. maybe there is a better way to do this?

Edit-----

found this link but I'd still appreciate a quick comment if someone could suggest a better pattern for my desired functionality

MVC 4 SimpleMembership - Why WebSecurity.CurrentUserId -1 after login

Community
  • 1
  • 1
J Benjamin
  • 4,722
  • 6
  • 29
  • 39

1 Answers1

1

As the post you found pointed out the user identity is not set immediately after login, so User.Identity.Name does not contain the user name. Use model.UserName instead. Try changing this line:

if (!IsProfileComplete(WebSecurity.GetUserId(User.Identity.Name)))

To this:

if (!IsProfileComplete(WebSecurity.GetUserId(model.UserName)))
Kevin Junghans
  • 17,475
  • 4
  • 45
  • 62