예제 #1
0
        public async Task <ActionResult> VerifyCode(VerifyCodeViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // The following code protects for brute force attacks against the two factor codes.
            // If a user enters incorrect codes for a specified amount of time then the user account
            // will be locked out for a specified amount of time.
            // You can configure the account lockout settings in IdentityConfig
            var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent : model.RememberMe, rememberBrowser : model.RememberBrowser);

            switch (result)
            {
            case SignInStatus.Success:
                UserProfile profile = CurrentUserProfileOrThrow;
                if (!PostLoginAuthCheck(profile))
                {
                    return(RedirectToAction("Login", new { CheckingOut = model.CheckingOut }));
                }

                profile.LastLogonDateTimeUtc = DateTime.UtcNow;
                GStoreDb.SaveChangesDirect();
                GStoreDb.LogSecurityEvent_VerificationCodeSuccess(HttpContext, RouteData, model.Code, model.Provider, model.ReturnUrl, profile, this);

                StoreFront storeFront = CurrentStoreFrontOrNull;
                if (storeFront != null)
                {
                    Cart cart = storeFront.GetCart(Session.SessionID, null);
                    cart = storeFront.MigrateCartToProfile(GStoreDb, cart, profile, this);
                }
                if (profile.NotifyAllWhenLoggedOn)
                {
                    string title = User.Identity.Name;
                    if (profile != null)
                    {
                        title = profile.FullName;
                    }
                    string message = "Logged on";


                    Microsoft.AspNet.SignalR.IHubContext hubCtx = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext <GStoreWeb.Hubs.NotifyHub>();
                    hubCtx.Clients.All.addNewMessageToPage(title, message);
                }

                if (model.CheckingOut.HasValue && model.CheckingOut.Value)
                {
                    return(RedirectToAction("Index", "Cart"));
                }
                return(RedirectToLocal(model.ReturnUrl));

            case SignInStatus.LockedOut:
                GStoreDb.LogSecurityEvent_VerificationCodeFailedLockedOut(HttpContext, RouteData, model.Code, model.Provider, model.ReturnUrl, null, this);
                ViewBag.CheckingOut = model.CheckingOut;
                return(View("Lockout"));

            case SignInStatus.Failure:
            default:
                GStoreDb.LogSecurityEvent_VerificationCodeFailedInvalidCode(HttpContext, RouteData, model.Code, model.Provider, model.ReturnUrl, null, this);
                ModelState.AddModelError("", "Invalid code.");
                return(View(model));
            }
        }
예제 #2
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : true);

            switch (result)
            {
            case SignInStatus.Success:
                AspNetIdentityUser user    = SignInManager.UserManager.Users.Single(u => u.UserName.ToLower() == model.Email.ToLower());
                string             userId  = user.Id;
                UserProfile        profile = GStoreDb.GetUserProfileByEmail(user.Email);
                if (!PostLoginAuthCheck(profile))
                {
                    return(RedirectToAction("Login", new { CheckingOut = model.CheckingOut }));
                }

                profile.LastLogonDateTimeUtc = DateTime.UtcNow;
                GStoreDb.SaveChangesDirect();
                GStoreDb.LogSecurityEvent_LoginSuccess(this.HttpContext, this.RouteData, profile, this);

                StoreFront storeFront = CurrentStoreFrontOrNull;
                if (storeFront != null)
                {
                    Cart cart = storeFront.GetCart(Session.SessionID, null);
                    cart = storeFront.MigrateCartToProfile(GStoreDb, cart, profile, this);
                }
                if (profile.NotifyAllWhenLoggedOn)
                {
                    string title = user.UserName;
                    if (profile != null)
                    {
                        title = profile.FullName;
                    }
                    string message = "Logged on";


                    Microsoft.AspNet.SignalR.IHubContext hubCtx = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext <GStoreWeb.Hubs.NotifyHub>();
                    hubCtx.Clients.All.addNewMessageToPage(title, message);
                }

                if (model.CheckingOut ?? false)
                {
                    return(RedirectToAction("Index", "Checkout", new { ContinueAsLogin = true }));
                }
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                UserProfile profileLockout = GStoreDb.GetUserProfileByEmail(model.Email);
                GStoreDb.LogSecurityEvent_LoginLockedOut(this.HttpContext, RouteData, model.Email, profileLockout, this);
                string notificationBaseUrl = Url.Action("Details", "Notifications", new { id = "" });
                string forgotPasswordUrl   = Request.Url.Host + (Request.Url.IsDefaultPort ? string.Empty : ":" + Request.Url.Port) + Url.Action("ForgotPassword", "Account");
                CurrentStoreFrontOrThrow.HandleLockedOutNotification(GStoreDb, Request, profileLockout, notificationBaseUrl, forgotPasswordUrl);
                ViewBag.CheckingOut = model.CheckingOut;
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                //allow pass-through even if storefront config is inactive because user may be an admin
                UserProfile profileVerify = GStoreDb.GetUserProfileByEmail(model.Email);
                GStoreDb.LogSecurityEvent_LoginNeedsVerification(this.HttpContext, RouteData, model.Email, profileVerify, this);
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe, CheckingOut = model.CheckingOut }));

            case SignInStatus.Failure:
            default:
                UserProfile userProfileFailure = GStoreDb.GetUserProfileByEmail(model.Email, false);
                GStoreDb.LogSecurityEvent_LoginFailed(this.HttpContext, RouteData, model.Email, model.Password, userProfileFailure, this);

                if (userProfileFailure == null)
                {
                    //unknown user, maybe ask to sign up?
                    ModelState.AddModelError("", "User Name or Password is invalid. Please correct it and try again. ");
                }
                else
                {
                    //looks like an existing user but wrong password
                    ModelState.AddModelError("", "User Name or Password is invalid. Please check your password and try again. ");
                }
                return(View(model));
            }
        }
예제 #3
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            StoreFront storeFront = CurrentStoreFrontOrNull;
            StoreFrontConfiguration storeFrontConfig = CurrentStoreFrontConfigOrNull;

            if ((storeFront != null) && (storeFrontConfig != null) && (storeFrontConfig.RegisterWebForm != null) && storeFrontConfig.RegisterWebForm.IsActiveBubble())
            {
                FormProcessorExtensions.ValidateFields(this, storeFrontConfig.RegisterWebForm);
            }

            if (ModelState.IsValid)
            {
                var user = new AspNetIdentityUser(model.Email)
                {
                    UserName = model.Email, Email = model.Email
                };
                user.TwoFactorEnabled = Settings.IdentityEnableTwoFactorAuth;
                IdentityResult result = null;
                try
                {
                    result = await UserManager.CreateAsync(user, model.Password);
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException exDbEx)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult valResult in exDbEx.EntityValidationErrors)
                    {
                        ICollection <System.Data.Entity.Validation.DbValidationError> valErrors = valResult.ValidationErrors;
                        foreach (System.Data.Entity.Validation.DbValidationError error in valErrors)
                        {
                            ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
                        }
                    }
                    return(View(model));
                }
                catch (Exception ex)
                {
                    string error = ex.ToString();
                    throw;
                }
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : true, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771

                    IGstoreDb   ctx        = GStoreDb;
                    UserProfile newProfile = ctx.UserProfiles.Create();
                    newProfile.UserId   = user.Id;
                    newProfile.UserName = user.UserName;
                    newProfile.Email    = user.Email;
                    newProfile.FullName = model.FullName;
                    newProfile.NotifyOfSiteUpdatesToEmail = model.NotifyOfSiteUpdates;
                    newProfile.SendMoreInfoToEmail        = model.SendMeMoreInfo;
                    newProfile.SignupNotes           = model.SignupNotes;
                    newProfile.NotifyAllWhenLoggedOn = true;
                    newProfile.IsPending             = false;
                    newProfile.Order            = CurrentStoreFrontOrThrow.UserProfiles.Max(up => up.Order) + 10;
                    newProfile.EntryDateTime    = Session.EntryDateTime().Value;
                    newProfile.EntryRawUrl      = Session.EntryRawUrl();
                    newProfile.EntryReferrer    = Session.EntryReferrer();
                    newProfile.EntryUrl         = Session.EntryUrl();
                    newProfile.StartDateTimeUtc = DateTime.UtcNow.AddMinutes(-1);
                    newProfile.EndDateTimeUtc   = DateTime.UtcNow.AddYears(100);
                    newProfile.StoreFrontId     = CurrentStoreFrontOrThrow.StoreFrontId;
                    newProfile.StoreFront       = CurrentStoreFrontOrThrow;
                    newProfile.ClientId         = this.CurrentClientOrThrow.ClientId;
                    newProfile.Client           = this.CurrentClientOrThrow;
                    newProfile = ctx.UserProfiles.Add(newProfile);
                    ctx.SaveChanges();

                    ctx.UserName          = user.UserName;
                    ctx.CachedUserProfile = null;


                    string customFields = string.Empty;
                    if (storeFrontConfig != null && storeFrontConfig.RegisterWebForm != null && storeFrontConfig.RegisterWebForm.IsActiveBubble())
                    {
                        FormProcessorExtensions.ProcessWebForm(this, storeFrontConfig.RegisterWebForm, null, true, null);
                        customFields = FormProcessorExtensions.BodyTextCustomFieldsOnly(this, storeFrontConfig.RegisterWebForm);
                    }

                    bool confirmResult = SendEmailConfirmationCode(user.Id, newProfile);

                    ctx.LogSecurityEvent_NewRegister(this.HttpContext, RouteData, newProfile, this);
                    string notificationBaseUrl = Url.Action("Details", "Notifications", new { id = "" });
                    CurrentStoreFrontOrThrow.HandleNewUserRegisteredNotifications(this.GStoreDb, Request, newProfile, notificationBaseUrl, true, true, customFields);

                    if (storeFront != null)
                    {
                        Cart cart = storeFront.GetCart(Session.SessionID, null);
                        cart = storeFront.MigrateCartToProfile(GStoreDb, cart, newProfile, this);
                        storeFront.MigrateOrdersToNewProfile(GStoreDb, newProfile, this);
                    }

                    if (Settings.IdentityEnableNewUserRegisteredBroadcast && CurrentClientOrThrow.EnableNewUserRegisteredBroadcast)
                    {
                        string title   = model.FullName;
                        string message = "Newly registered!";
                        Microsoft.AspNet.SignalR.IHubContext hubCtx = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext <GStoreWeb.Hubs.NotifyHub>();
                        hubCtx.Clients.All.addNewMessageToPage(title, message);
                    }

                    if (model.CheckingOut ?? false)
                    {
                        return(RedirectToAction("LoginOrGuest", "Checkout", new { ContinueAsLogin = true }));
                    }

                    if (storeFrontConfig != null && storeFrontConfig.RegisterSuccess_PageId.HasValue)
                    {
                        return(Redirect(storeFrontConfig.RegisterSuccessPage.UrlResolved(this.Url)));
                    }
                    return(RedirectToAction("RegisterSuccess"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }