Exemple #1
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null)
                {
                    //todo: user not found; email the person to get them to sign up, or do nothing?
                    GStoreDb.LogSecurityEvent_ForgotPasswordEmailNotFound(HttpContext, RouteData, model.Email, this);
                    return(View("ForgotPasswordNoUser", model));
                }

                UserProfile profile = GStoreDb.GetUserProfileByEmail(model.Email, false);
                if (profile == null)
                {
                    GStoreDb.LogSecurityEvent_ForgotPasswordProfileNotFound(HttpContext, RouteData, model.Email, this);
                    return(View("ForgotPasswordNoUser", model));
                }

                GStoreDb.LogSecurityEvent_ForgotPasswordSuccess(HttpContext, RouteData, model.Email, profile, this);

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                StoreFront storeFront  = CurrentStoreFrontOrNull;
                string     subject     = StoreFrontExtensions.ForgotPasswordSubject(storeFront, callbackUrl, Request.Url);
                string     messageText = StoreFrontExtensions.ForgotPasswordMessageText(storeFront, callbackUrl, Request.Url);
                string     messageHtml = StoreFrontExtensions.ForgotPasswordMessageHtml(storeFront, callbackUrl, Request.Url);
                bool       result;
                try
                {
                    result = this.SendEmail(profile.Email, profile.FullName, subject, messageText, messageHtml);
                    if (result)
                    {
                        AddUserMessage("Email Sent", "A password reset email was sent to " + model.Email, UserMessageType.Info);
                    }
                    else
                    {
                        AddUserMessage("Error sending Email", "Email to " + model.Email + " failed.", UserMessageType.Danger);
                    }
                }
                catch (Exception)
                {
                    string message = "There was an error sending email to " + model.Email;
                    AddUserMessage("Error sending Email", message, UserMessageType.Danger);
                }
                return(RedirectToAction("ForgotPasswordConfirmation", "Account", new { CheckingOut = model.CheckingOut }));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        private void SendEmailConfirmationCode(string userId, UserProfile profile)
        {
            if (profile == null)
            {
                throw new ArgumentNullException("profile");
            }

            // Send an email with this link
            string code        = UserManager.GenerateEmailConfirmationTokenAsync(userId).Result;
            var    callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = userId, code = code }, protocol: Request.Url.Scheme);

            StoreFront storeFront  = CurrentStoreFrontOrNull;
            string     subject     = StoreFrontExtensions.EmailConfirmationCodeSubject(storeFront, callbackUrl, Request.Url);
            string     messageHtml = StoreFrontExtensions.EmailConfirmationCodeMessageHtml(storeFront, callbackUrl, Request.Url);
            string     messageText = StoreFrontExtensions.EmailConfirmationCodeMessageText(storeFront, callbackUrl, Request.Url);

            bool result = this.SendEmail(profile.Email, profile.FullName, subject, messageText, messageHtml);
        }
Exemple #3
0
        private bool SendEmailConfirmationCode(string userId, UserProfile profile)
        {
            if (profile == null)
            {
                throw new ArgumentNullException("profile");
            }

            // Send an email with this link
            string code        = UserManager.GenerateEmailConfirmationTokenAsync(userId).Result;
            var    callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = userId, code = code }, protocol: Request.Url.Scheme);

            StoreFront storeFront  = CurrentStoreFrontOrNull;
            string     subject     = StoreFrontExtensions.EmailConfirmationCodeSubject(storeFront, callbackUrl, Request.Url);
            string     messageHtml = StoreFrontExtensions.EmailConfirmationCodeMessageHtml(storeFront, callbackUrl, Request.Url);
            string     messageText = StoreFrontExtensions.EmailConfirmationCodeMessageText(storeFront, callbackUrl, Request.Url);

            bool result;

            try
            {
                result = this.SendEmail(profile.Email, profile.FullName, subject, messageText, messageHtml);
                if (result)
                {
                    AddUserMessage("Email Sent", "Confirmation Email was sent to " + profile.Email, UserMessageType.Info);
                }
                else
                {
                    AddUserMessage("Email Failed", "Sorry, we could not send a Confirmation Email to " + profile.Email, UserMessageType.Info);
                }
            }
            catch
            {
                result = false;
                AddUserMessage("Email Failed", "Sorry, there was an error sending the confirmation email to " + profile.Email, UserMessageType.Info);
            }

            return(result);
        }
        public async Task <ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }


            var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number);

            StoreFront storeFront  = CurrentStoreFrontOrNull;
            string     messageBody = StoreFrontExtensions.AddPhoneNumberMessage(storeFront, code, Request.Url);

            if (!Settings.AppEnableSMS)
            {
                //if app set to not enable SMS, just store phone number unverified

                return(AddPhoneNumberNoSms(model, messageBody));
            }

            Client client = CurrentClientOrNull;

            if (client == null || !client.UseTwilioSms)
            {
                //if client is set to not enable SMS, just store phone number unverified
                return(AddPhoneNumberNoSms(model, messageBody));
            }

            GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Profile, UserActionActionEnum.Profile_AddPhoneNumber, model.Number, true, smsPhone: model.Number);

            // Generate the token and send it

            bool result = this.SendSms(model.Number, messageBody);

            return(RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number }));
        }
Exemple #5
0
        /// <summary>
        /// Runs Savechanges on the context, plus other automatic options, defaults are all true
        /// </summary>
        /// <param name="updateAuditableRecords"></param>
        /// <param name="runEmailNotifications"></param>
        /// <param name="runSmsNotifications"></param>
        /// <param name="updateCategoryCounts"></param>
        /// <returns></returns>
        public int SaveChangesEx(bool updateAuditableRecords, bool runEmailNotifications, bool runSmsNotifications, bool updateCategoryCounts)
        {
            ChangeTracker.DetectChanges();
            List <Notification> notificationsToProcess     = new List <Notification>();
            List <int>          storeFrontIdsToRecalculate = new List <int>();

            if (ChangeTracker.HasChanges())
            {
                foreach (DbEntityEntry item in ChangeTracker.Entries())
                {
                    if (updateAuditableRecords && (item.State == EntityState.Added || item.State == EntityState.Modified) && item.Entity is Models.BaseClasses.AuditFieldsAllRequired)
                    {
                        Models.BaseClasses.AuditFieldsAllRequired record = item.Entity as Models.BaseClasses.AuditFieldsAllRequired;
                        UserProfile userProfile = this.GetCurrentUserProfile(false, false);
                        if (userProfile == null)
                        {
                            string entityType = record.EntityTypeFullName();
                            throw new ApplicationException("User profile not found. User may be anonymous. Profile needed for entity: " + entityType);
                        }
                        record.UpdateAuditFields(userProfile);
                    }

                    if (updateAuditableRecords && (item.State == EntityState.Added || item.State == EntityState.Modified) && item.Entity is Models.BaseClasses.AuditFieldsUserProfileOptional)
                    {
                        Models.BaseClasses.AuditFieldsUserProfileOptional recordOptional = item.Entity as Models.BaseClasses.AuditFieldsUserProfileOptional;
                        UserProfile userProfileOptional = this.GetCurrentUserProfile(false, false);
                        recordOptional.UpdateAuditFields(userProfileOptional);
                    }

                    if (updateCategoryCounts && (item.State == EntityState.Added || item.State == EntityState.Modified || item.State == EntityState.Deleted) && item.Entity is Models.ProductCategory)
                    {
                        StoreFront storeFront   = ((ProductCategory)item.Entity).StoreFront;
                        int        storeFrontId = storeFront == null?item.OriginalValues.GetValue <int>("StoreFrontId") : storeFront.StoreFrontId;

                        if (!storeFrontIdsToRecalculate.Contains(storeFrontId))
                        {
                            storeFrontIdsToRecalculate.Add(storeFrontId);
                        }
                    }

                    if (updateCategoryCounts && (item.State == EntityState.Added || item.State == EntityState.Modified || item.State == EntityState.Deleted) && item.Entity is Models.Product)
                    {
                        StoreFront storeFront   = ((Product)item.Entity).StoreFront;
                        int        storeFrontId = storeFront == null?item.OriginalValues.GetValue <int>("StoreFrontId") : storeFront.StoreFrontId;

                        if (!storeFrontIdsToRecalculate.Contains(storeFrontId))
                        {
                            storeFrontIdsToRecalculate.Add(storeFrontId);
                        }
                    }

                    if (updateCategoryCounts && (item.State == EntityState.Added || item.State == EntityState.Modified || item.State == EntityState.Deleted) && item.Entity is Models.ProductBundle)
                    {
                        StoreFront storeFront   = ((ProductBundle)item.Entity).StoreFront;
                        int        storeFrontId = storeFront == null?item.OriginalValues.GetValue <int>("StoreFrontId") : storeFront.StoreFrontId;

                        if (!storeFrontIdsToRecalculate.Contains(storeFrontId))
                        {
                            storeFrontIdsToRecalculate.Add(storeFrontId);
                        }
                    }

                    if (updateCategoryCounts && (item.State == EntityState.Added || item.State == EntityState.Modified || item.State == EntityState.Deleted) && item.Entity is Models.ProductBundleItem)
                    {
                        StoreFront storeFront   = ((ProductBundleItem)item.Entity).StoreFront;
                        int        storeFrontId = storeFront == null?item.OriginalValues.GetValue <int>("StoreFrontId") : storeFront.StoreFrontId;

                        if (!storeFrontIdsToRecalculate.Contains(storeFrontId))
                        {
                            storeFrontIdsToRecalculate.Add(storeFrontId);
                        }
                    }

                    //new notification, process email and sms notification
                    if (item.Entity is Notification && item.State == EntityState.Added && (runEmailNotifications || runSmsNotifications))
                    {
                        notificationsToProcess.Add(item.Entity as Notification);
                    }
                }
            }

            int returnValue = -1;

            try
            {
                returnValue = base.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                string errorDetails = "DbEntityValidationException Error saving to database.";
                if (ex.EntityValidationErrors != null && ex.EntityValidationErrors.Count() > 0)
                {
                    errorDetails += "\nEntity Errors: " + ex.EntityValidationErrors.Count();
                    foreach (DbEntityValidationResult valError in ex.EntityValidationErrors)
                    {
                        DbEntityEntry errorRow = valError.Entry;
                        if (errorRow != null)
                        {
                            GStoreEntity entity = errorRow.Entity as GStoreEntity;
                            if (entity != null)
                            {
                                errorDetails += "\n\tGStore Entity: " + entity.GetPocoType().FullName;
                            }
                            else
                            {
                                errorDetails += "\n\tMisc Entity: " + errorRow.Entity.ToString();
                            }
                        }
                        else
                        {
                            errorDetails += "\n\tUnknown Entity";
                        }

                        errorDetails += " (" + errorRow.State.ToString() + ")";
                        errorDetails += " Errors: " + valError.ValidationErrors.Count();

                        foreach (DbValidationError dbValError in valError.ValidationErrors)
                        {
                            errorDetails += "\n\t\tError in " + dbValError.PropertyName + ": " + dbValError.ErrorMessage;
                        }

                        foreach (string propName in valError.Entry.CurrentValues.PropertyNames)
                        {
                            object fieldObjectValue = valError.Entry.CurrentValues[propName];
                            string fieldValue       = fieldObjectValue == null ? "(null)" : fieldObjectValue.ToString();
                            errorDetails += "\n\t\t" + propName + " = '" + fieldValue + "'";
                            if (errorRow.State == EntityState.Modified)
                            {
                                if ((valError.Entry.OriginalValues != null) && (valError.Entry.OriginalValues.PropertyNames.Contains(propName)))
                                {
                                    object originalValueObject = valError.Entry.OriginalValues[propName];
                                    string originalValue       = originalValueObject == null ? "(null)" : originalValueObject.ToString();
                                    errorDetails += " Original Value: '" + originalValue + "'";
                                }
                            }
                        }
                    }
                }
                errorDetails += " \n BaseException: " + ex.GetBaseException().ToString();
                ApplicationException exNew = new ApplicationException(errorDetails, ex);
                Debug.WriteLine(errorDetails);
                throw exNew;
            }
            catch (DbUpdateException exUpdate)
            {
                string errorDetails = "DBUpdateException Error updating database.";
                if (exUpdate.Entries != null && exUpdate.Entries.Count() > 0)
                {
                    errorDetails += "\nEntity DB Update Exception Error Entries: " + exUpdate.Entries.Count();
                    foreach (DbEntityEntry errorEntry in exUpdate.Entries)
                    {
                        if (errorEntry.Entity != null)
                        {
                            GStoreEntity entity = errorEntry.Entity as GStoreEntity;
                            if (entity != null)
                            {
                                errorDetails += "\n\tGStore Entity: " + entity.GetPocoType().FullName;
                            }
                            else
                            {
                                errorDetails += "\n\tMisc Entity: " + errorEntry.Entity.ToString();
                            }
                        }
                        else
                        {
                            errorDetails += "\n\tUnknown Entity";
                        }
                        errorDetails += " (Entity State: " + errorEntry.State.ToString() + ")";

                        if (errorEntry.State == EntityState.Deleted)
                        {
                            foreach (string propName in errorEntry.OriginalValues.PropertyNames)
                            {
                                object fieldObjectValue = errorEntry.OriginalValues[propName];
                                string fieldValue       = (fieldObjectValue == null ? "(null)" : fieldObjectValue.ToString());
                                errorDetails += "\n\t\t" + propName + " = '" + fieldValue + "'";
                            }
                        }
                        else
                        {
                            foreach (string propName in errorEntry.CurrentValues.PropertyNames)
                            {
                                object fieldObjectValue = errorEntry.CurrentValues[propName];
                                string fieldValue       = (fieldObjectValue == null ? "(null)" : fieldObjectValue.ToString());
                                errorDetails += "\n\t\t" + propName + " = '" + fieldValue + "'";

                                if ((errorEntry.State == EntityState.Modified) && (errorEntry.OriginalValues != null) && (errorEntry.OriginalValues.PropertyNames.Contains(propName)))
                                {
                                    object originalValueObject = errorEntry.OriginalValues[propName];
                                    string originalValue       = originalValueObject == null ? "(null)" : originalValueObject.ToString();
                                    errorDetails += " Original Value: '" + originalValue + "'";
                                }
                            }
                        }
                    }
                }

                errorDetails += " \n BaseException: " + exUpdate.GetBaseException().ToString();
                ApplicationException exNew = new ApplicationException(errorDetails, exUpdate);
                Debug.WriteLine(errorDetails);
                throw exNew;
            }
            catch (Exception ex)
            {
                if (ex is System.Data.SqlClient.SqlException || ex.GetBaseException() is System.Data.SqlClient.SqlException)
                {
                    throw new Exceptions.DatabaseErrorException("SQL Client Error in SaveChangesEx: " + ex.Message, ex);
                }
                else
                {
                    throw new Exceptions.DatabaseErrorException("Unknown Database Error in SaveChangesEx: " + ex.Message, ex);
                }
            }

            if (notificationsToProcess.Count != 0)
            {
                foreach (Notification item in notificationsToProcess)
                {
                    StoreFrontExtensions.ProcessEmailAndSmsNotifications(this, item, runEmailNotifications, runSmsNotifications);
                }
            }

            if (storeFrontIdsToRecalculate.Count != 0)
            {
                foreach (int storeFrontId in storeFrontIdsToRecalculate)
                {
                    this.RecalculateProductCategoryActiveCount(storeFrontId);
                }
            }

            return(returnValue);
        }