Example #1
0
        public ActionResult SecurityQuestions(SecurityQuestionsModel model)
        {
            var sessionUser = Session["Username"] as string;
            var sessionRole = Session["UserRole"] as string;

            List <CreateUser> user;

            using (IDbConnection db = new SqlConnection(SqlAccess.GetConnectionString()))
            {
                user = db.Query <CreateUser>("Select * from dbo.UserTable where Username = @Username", new { Username = sessionUser }).ToList();
                string sql = $"Update dbo.UserTable set SecurityQuestion1 = @Question1, Answer1 = @Ans1," +
                             "SecurityQuestion2 = @Question2, Answer2 = @Ans2 where Username = @Username";
                db.Execute(sql, new
                {
                    Question1 = model.Security_Question1,
                    Ans1      = model.Answer_1,
                    Question2 = model.Security_Question2,
                    Ans2      = model.Answer_2,
                    Username  = sessionUser
                });
            }
            //using (Database1Entities5 dc = new Database1Entities5())
            //{
            //    var account = dc.CreateUsers.Where(a => a.Username == sessionUser).FirstOrDefault();

            //    account.Security_Question1 = model.Security_Question1;
            //    account.Answer_1 = model.Answer_1;
            //    account.Security_Question2 = model.Security_Question2;
            //    account.Answer_2 = model.Answer_2;
            //    dc.SaveChanges();

            //}

            if (sessionRole == "Admin")
            {
                return(Redirect("~/Admin/Dashboard"));
            }
            else if (sessionRole == "Accountant")
            {
                return(Redirect("~/Accountant/Dashboard"));
            }

            return(Redirect("~/Admin/Dashboard"));
        }
        public ActionResult SecurityQuestions(SecurityQuestionsModel model, string username, string failureCount, string questionID)
        {
            if (ModelState.IsValid)
            {
                // string username = model.UserName;
                if (WebSecurity.UserExists(username))
                {
                    //get the question being tested
                    var pwMgr = new PasswordManager(username);
                    //get the questions for this user
                    var questions = pwMgr.GetQuestions();



                    var question = questions.FirstOrDefault(x => x.QuestionNumber.ToString() == model.QuestionID);

                    //check to see if the answer is valid
                    bool questionMatch = false;
                    if (question != null)
                    {
                        question.Answer = model.QuestionValue;
                        questionMatch   = pwMgr.CheckAnswer(question);
                    }

                    //if it is, email the user the link and display the redirect to login view
                    if (questionMatch)
                    {
                        string token = WebSecurity.GeneratePasswordResetToken(username, 10);
                        string email = "";

                        using (var userContext = new PEMRBACEntities())
                        {
                            var profile = userContext.UserProfiles.SingleOrDefault(u => u.UserName == username);
                            if (profile != null)
                            {
                                email = profile.Email;
                            }
                        }

                        if (!String.IsNullOrEmpty(email) && !String.IsNullOrEmpty(token))
                        {
                            // Send password reset email
                            var mailer = new UserMailer();
                            mailer.PasswordReset(token, email).Send();
                        }
                        else
                        {
                            ModelState.AddModelError("",
                                                     "Could not send email at this time. If the problem perists please contact your system administrator");
                        }

                        //if everythign was successful, then we need to return the login redirect view
                        return(ReturnLoginRedirectView("You have been emailed a link to reset your password.",
                                                       "Password Reset - Emailed"));
                    }

                    //if the question didnt match, and this is the first failure (0), then retry with the other question
                    //also, lets make sure we are telling hte user why they have to answer again
                    if (model.FailureCount == "0")
                    {
                        ModelState.AddModelError("", "Incorrect Answer. Please Try Again.");
                        //get the question that we did NOT just ask
                        var unansweredQuestion = questions.FirstOrDefault(x => x.QuestionNumber.ToString() != model.QuestionID);
                        //re-ask them

                        var secModel = new SecurityQuestionsModel
                        {
                            UserName      = username,
                            FailureCount  = "1",
                            QuestionID    = unansweredQuestion.QuestionNumber.ToString(),
                            QuestionText  = unansweredQuestion.Question,
                            QuestionValue = string.Empty
                        };

                        return(View("SecurityQuestions", secModel));
                    }

                    //they didnt answer their quesitons correctly, display the system admin contact view.
                    return(View("CustomerService", new CustomerSupportModel()));
                }
                else
                {
                    ModelState.AddModelError("", "No account with that username found. Please enter a valid username");
                }
            }

            // If we got this far, something failed. redisplay form
            return(View(model));
        }
        public ActionResult ForgotPassword(string userName)
        {
            if (ModelState.IsValid)
            {
                string username = userName;
                //make sure the user exists
                if (WebSecurity.UserExists(username))
                {
                    //check if they have an email associated with their account.
                    if ((new UserFactory()).UserHasEmail(username))
                    {
                        //display the form that allows them to answer the seciryt questions
                        var pwMgr = new PasswordManager(username);

                        //get the questions for this user
                        var questions = pwMgr.GetQuestions();
                        //if they are both empty, send the user to the customer service page
                        bool validQs = false;
                        foreach (var passwordQuestion in questions)
                        {
                            if (!string.IsNullOrEmpty(passwordQuestion.Question))
                            {
                                validQs = true;
                                break;
                            }
                        }


                        if (!validQs)
                        {
                            //they didnt answer their quesitons correctly, display the system admin contact view.
                            return(View("CustomerService", new CustomerSupportModel {
                                Message = "Your security questions have not been defined."
                            }));
                        }

                        //get a random question
                        var rand = new Random();
                        var randomQuestionIndex = rand.Next(0, 2);
                        var question            = questions[randomQuestionIndex];

                        //setting the failure to 0 on the first go around
                        var secModel = new SecurityQuestionsModel
                        {
                            UserName     = username,
                            FailureCount = "0",
                            QuestionID   = question.QuestionNumber.ToString(),
                            QuestionText = question.Question
                        };

                        return(View("SecurityQuestions", secModel));
                    }
                    else
                    {
                        //otherwise, show the customer support page
                        return(View("CustomerService", new CustomerSupportModel()));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "No account with that username found. Please enter a valid username");
                }
            }

            // If we got this far, something failed. redisplay form
            return(View());
        }
        public async Task <ActionResult> AccountDetails(AccountDetails data, string prevBtn, string nextBtn)
        {
            UserModel              obj = GetUser();
            ToastModel             tm  = new ToastModel();
            SecurityQuestionsModel Sqm = new SecurityQuestionsModel();

            ContactDetails cd = new ContactDetails();

            cd.Address = obj.Address;
            cd.Country = obj.CountryId;
            ViewBag.SelectedCountry = obj.CountryId;
            cd.State = obj.StateId;
            ViewBag.SelectedState = obj.StateId;
            cd.City      = obj.City;
            cd.ZipCode   = obj.ZipCode;
            cd.HomePhone = obj.HomePhone;
            cd.CellPhone = obj.CellPhone;

            if (prevBtn != null)
            {
                TempData["ContactDetails"] = cd;
                return(RedirectToAction("ContactDetails"));
            }
            if (nextBtn != null)
            {
                Dictionary <int, string> SecurityQuestions = new Dictionary <int, string>();

                for (int i = 0; i < 5; i++)
                {
                    if ((Request.Form["AnswerTextbox_" + (i + 1)]) != "")
                    {
                        SecurityQuestions.Add((i + 1), Request.Form["AnswerTextbox_" + (i + 1)]);
                    }
                }

                AccountDetails Ad = new AccountDetails();
                Ad.Email                  = data.Email;
                Ad.Password               = data.Password;
                Ad.RetypePassword         = data.RetypePassword;
                Ad.AccountType            = data.AccountType;
                Ad.SecurityQuestionsModel = await _common.GetSecurityQuestions();

                ViewBag.SecurityQuestions = await _common.GetSecurityQuestions();

                foreach (var item in SecurityQuestions)
                {
                    Ad.SecurityQuestionsModel.ForEach(sq =>
                    {
                        if (sq.Id == item.Key)
                        {
                            sq.Value = item.Value;
                        }
                    });
                }

                if (SecurityQuestions.Count < 2)
                {
                    return(View("AccountDetails", Ad));
                }

                else
                {
                    if (ModelState.IsValid)
                    {
                        bool userRejected  = false;
                        bool isEmailExists = await _account.IsActiveUser(data.Email);

                        bool isFamilyMember = await _account.IsFamilyMember(data.Email);

                        int isAddressOrHomePhoneMatched = await _account.IsAddressOrHomePhoneMatched(cd);

                        if (isEmailExists)
                        {
                            tm.IsSuccess  = false;
                            tm.Message    = "Email already registered";
                            ViewBag.Toast = tm;
                            return(View("AccountDetails", Ad));
                        }

                        obj.Email    = data.Email;
                        obj.Password = data.Password;
                        EncryptDecrypt objEncryptDecrypt = new EncryptDecrypt();
                        obj.Password              = objEncryptDecrypt.Encrypt(data.Password, WebConfigurationManager.AppSettings["ServiceAccountPassword"]);
                        obj.IsIndividual          = Convert.ToBoolean(data.AccountType);
                        obj.UserSecurityQuestions = SecurityQuestions;
                        obj.Status = false;

                        // case: If user is added as a member of someone else's family
                        // send approval mail to primary account holder and user should be in inactive status until request has approved.
                        if (isFamilyMember || isAddressOrHomePhoneMatched != 0)
                        {
                            obj.IsIndividual      = true;
                            obj.IsApproveMailSent = true;
                            string primaryAccountEmail = string.Empty;

                            int emailTemplateId = isFamilyMember ? 2 : 9;
                            // if user has already requested for logins and again trying to get register
                            UserModel um = await _user.GetUserInfo(data.Email);

                            if (!string.IsNullOrEmpty(um.Id))
                            {
                                // if primary a/c holder Rejected the user request
                                if ((bool)um.IsApproveMailSent && um.IsApproved != null)
                                {
                                    userRejected = true;
                                    // so we have to reset the approval request
                                    um.IsApproved = null;
                                    // we need to update the user
                                    HttpResponseMessage userResponseMessage = await Utility.GetObject("/api/User/PostUser", um, true);
                                }

                                // approval mail sent to primary a/c and not yet decided
                                if ((bool)um.IsApproveMailSent && um.IsApproved == null && !userRejected)
                                {
                                    ViewBag.ApproveMailSent = true;
                                    ViewBag.ApproveContent  = "An approval email has been already sent to primary account holder of your family..! Please be patient until your request has been approved.";
                                    return(View("AccountDetails", Ad));
                                }
                            }

                            ViewBag.IsFamilyMember = true;
                            EmailTemplateModel etm1 = await _account.GetEmailTemplate(emailTemplateId);

                            string toUserFullname = string.IsNullOrEmpty(um.Id) ? obj.FirstName + " " + obj.LastName : await _user.GetUserFullName(data.Email);

                            if (isAddressOrHomePhoneMatched == 0)
                            {
                                primaryAccountEmail = await _account.GetFamilyPrimaryAccountEmail(data.Email);
                            }
                            else
                            {
                                primaryAccountEmail =
                                    isAddressOrHomePhoneMatched == 1
                                                                ? await _account.GetPrimaryAccountEmailByHomePhone(obj.HomePhone)
                                                                : await _account.GetPrimaryAccountEmailByAddress(cd);
                            }

                            string fromUserFullname = await _user.GetUserFullName(primaryAccountEmail);

                            string approvalLink1 = configMngr["SharedAccountRequestLink"]
                                                   + objEncryptDecrypt.Encrypt(data.Email, configMngr["ServiceAccountPassword"])
                                                   + "&aadm="
                                                   + isAddressOrHomePhoneMatched;

                            string emailBody1 = etm1.Body
                                                .Replace("[ToUsername]", toUserFullname)
                                                .Replace("[FromUsername]", fromUserFullname)
                                                .Replace("[URL]", approvalLink1);
                            etm1.Body = emailBody1;

                            EmailManager em1 = new EmailManager
                            {
                                Body    = etm1.Body,
                                To      = primaryAccountEmail,
                                Subject = etm1.Subject,
                                From    = ConfigurationManager.AppSettings["SMTPUsername"]
                            };
                            em1.Send();

                            obj.Id = null;
                            ViewBag.ApproveContent = "An approval email has been sent to primary account holder of your family..! Your account will be activated once your request has been approved.";
                            if (!userRejected)
                            {
                                HttpResponseMessage userResponseMessage = await Utility.GetObject("/api/User/PostUser", obj, true);

                                SharedAccountModel sam = new SharedAccountModel();
                                sam.To_UserId = await _account.GetUserIdByEmail(primaryAccountEmail);

                                sam.From_UserId = await _account.GetUserIdByEmail(obj.Email);

                                sam.CreatedDate = DateTime.Now;
                                HttpResponseMessage userResponseMessage2 = await Utility.GetObject("/api/User/PostSharedAccount", sam, true);
                            }

                            return(View("AccountDetails", Ad));
                        }

                        // If user is not a family member, allow him to register normally
                        HttpResponseMessage userResponseMessage1 = await Utility.GetObject("/api/User/PostUser", obj, true);

                        // if user registered successfully, then send an activation link
                        if (userResponseMessage1.IsSuccessStatusCode)
                        {
                            EmailTemplateModel etm = await _account.GetEmailTemplate(1);

                            string approvalLink = configMngr["UserActivationLink"]
                                                  + objEncryptDecrypt.Encrypt(data.Email, configMngr["ServiceAccountPassword"]);
                            string fullname  = obj.FirstName + " " + obj.LastName;
                            string emailBody = etm.Body
                                               .Replace("[Username]", fullname)
                                               .Replace("[URL]", approvalLink);
                            etm.Body = emailBody;

                            EmailManager em = new EmailManager
                            {
                                Body    = etm.Body,
                                To      = data.Email,
                                Subject = etm.Subject,
                                From    = ConfigurationManager.AppSettings["SMTPUsername"]
                            };
                            em.Send();
                            ViewBag.Message = "An email has been sent to registered email. Please activate your account";
                        }
                        return(View());
                    }
                }
            }
            return(View());
        }
Example #5
0
        public ActionResult SecurityQuestions()
        {
            var Security = new SecurityQuestionsModel();

            return(View(Security));
        }