Create User Automatically
Posted: Tue Dec 22, 2009 12:32 pm
I am trying to take a SOAP request and do the following
1.) Determine if user exists
2.) if not then create user
3.) log user in
I've been able to get a proof of concept working, but newly created users get the "Already Registered" message when checking out even though it appears that they are logged in. Any body know why this would be happening?
Here is my code:
1.) Determine if user exists
2.) if not then create user
3.) log user in
I've been able to get a proof of concept working, but newly created users get the "Already Registered" message when checking out even though it appears that they are logged in. Any body know why this would be happening?
Here is my code:
Code: Select all
protected void Page_Load(object sender, EventArgs e)
{
string UserName = "foo@baz.com";
string Password = "SomePassword";
int userIde = UserDataSource.GetUserIdByEmail(UserName);
int userIdu = UserDataSource.GetUserIdByUserName(UserName);
if (userIde == 0 && userIdu == 0)
{
MembershipCreateStatus status;
User newUser = UserDataSource.CreateUser(UserName, UserName, Password, string.Empty, string.Empty, true, 0, out status);
if (status == MembershipCreateStatus.Success)
{
// WE HAVE TO VALIDATE CREDENTIALS SO A MODIFIED FORM POST CANNOT ACCESS THIS CODE
if (Membership.ValidateUser(UserName, Password))
{
// SET A DEFAULT BILLING ADDRESS FOR THE USER
newUser.PrimaryAddress.Email = UserName;
newUser.PrimaryAddress.CountryCode = Token.Instance.Store.DefaultWarehouse.CountryCode;
newUser.PrimaryAddress.Residence = true;
newUser.Save();
//MIGRATE USER IF NEEDED
int newUserId = UserDataSource.GetUserIdByUserName(UserName);
if ((Token.Instance.UserId != newUserId) && (newUserId != 0))
{
User.Migrate(Token.Instance.User, newUser);
Token.Instance.UserId = newUserId;
}
// SET COOKIE TO REMEMBER USERNAME IF INDICATED
HttpCookie cookie = new HttpCookie("UserName", UserName);
cookie.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookie);
//REDIRECT TO APPROPRIATE PAGE
FormsAuthentication.RedirectFromLoginPage(UserName, false);
}
}
}
else
{
User loginUser = UserDataSource.LoadForUserName(UserName);
if (User.Login(UserName, Password))
{
int newUserId = loginUser.UserId;
int oldUserId = Token.Instance.UserId;
if ((oldUserId != newUserId) && (newUserId != 0))
{
User.Migrate(Token.Instance.User, UserDataSource.Load(newUserId));
Token.Instance.UserId = newUserId;
}
//HANDLE LOGIN PROCESSING
HttpCookie cookie = new HttpCookie("UserName", UserName);
cookie.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookie);
FormsAuthentication.RedirectFromLoginPage(UserName, false);
}
else
{
//login failed
}
}
}
}