<commit_before>﻿using System.Web.Security;
using HRI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web.Mvc;
using Umbraco.Core.Models;
using Umbraco.Web;
using log4net;

namespace HRI.Controllers
{
    public class EmailSurfaceController : HriSufraceController
    {
        static readonly ILog logger = LogManager.GetLogger(typeof(EmailSurfaceController));

        private const string UsernameDoesNotExist = "Sorry, that user name does not exist in our system.";

        /// <summary>
        /// Emails the Web Administrator with a message from a member
        /// </summary>
        /// <param name="model">A Contact Form view model</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ContactUs(ContactFormViewModel model)
        {
            try
            {
                string mailData = CurrentPage.GetPropertyValue<string>("categoriesAndEmails");
                IDictionary<string, IEnumerable<string>> categoriesAndEmails = ContactFormViewModel.GetCategoriesAndEmails(mailData);
                IEnumerable<string> emails = categoriesAndEmails[model.MessageType];

                const string na = "N/A";
                var message = string.Join(
                    Environment.NewLine,
                    string.Format("Member ID: {0}", model.MemberId ?? na),
                    string.Format("First Name: {0}", model.FirstName),
                    string.Format("Last Name: {0}", model.LastName),
                    string.Format("Y Number: {0}", model.YNumber ?? na),
                    string.Format("Username: {0}", model.Username ?? na),
                    string.Format("Email: {0}", model.Email),
                    string.Format("Phone Number: {0}", model.PhoneNumber),
                    "Message:",
                    Environment.NewLine,
                    model.Message);

                foreach (string email in emails)
                    try
                    {
                        SendEmail(email, model.MessageType, message);
                    }
                    catch (Exception ex)
                    {
                        logger.Error("Send failed to " + email, ex);
                    }

                // Set the sucess flag to true and post back to the same page
                TempData["IsSuccessful"] = true;
                return RedirectToCurrentUmbracoPage();
            }
            catch (Exception) // If the message failed to send
            {
                // Set the success flag to false and post back to the same page
                TempData["IsSuccessful"] = false;
                return RedirectToCurrentUmbracoPage();
            }
        }

        [HttpPost]
        public ActionResult ForgotUserName([Bind(Prefix = "forgotUserNameViewModel")]ForgotUserNameViewModel model)
        {
            try
            {
                Dictionary<string,string> dynamicText = new Dictionary<string, string>();
                // Attempt to get the member based on the given email address
                var member = Services.MemberService.GetByEmail(model.Email);
                
                // If a member with that email exists
                if (member != null)
                {
                    // Build a dictionary for all teh dynamic text in the email template
                    dynamicText = new Dictionary<string,string>
                    {
                        {"<%FirstName%>", member.GetValue("firstName").ToString()},
                        {"<%UserName%>", member.Username}
                    };
                }
                else
                {
                    // try get user from API
                    var hriUser = MakeInternalApiCallJson("GetRegisteredUserByEmail", new Dictionary<string, string> { { "email", model.Email } });
                    if (hriUser != null)
                    {
                        dynamicText = new Dictionary<string, string>
                        {
                            {"<%FirstName%>", hriUser["FirstName"].ToString()},
                            {"<%UserName%>", hriUser["UserName"].ToString()}
                        };
                    }
                }

                if (dynamicText.Any())
                {
                    // Get the Umbraco root node to access dynamic information (phone numbers, emails, ect)
                    IPublishedContent root = Umbraco.TypedContentAtRoot().First();

                    // add phone number to dynamic text
                    dynamicText.Add("<%PhoneNumber%>", root.GetProperty("phoneNumber").Value.ToString());

                    //Get the Verification Email Template ID
                    var emailTemplateId = root.GetProperty("forgotUserNameEmailTemplate").Value;
                    
                    SendEmail(model.Email, "Health Republic Insurance - Username Recovery",
                        BuildEmail((int) emailTemplateId, dynamicText));

                    // Set the sucess flag to true and post back to the same page
                    TempData["ForgotUsernameIsSuccessful"] = true;
                    return RedirectToCurrentUmbracoPage();
                }

                // The email has no member associated with it
                // Set the success flag to false and post back to the same page
                TempData["ForgotUsernameIsSuccessful"] = false;
                TempData["EmailNotFound"] = true;
                return RedirectToCurrentUmbracoPage();
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("forgotUserNameViewModel", ex.Message + "\n" + ex.InnerException.Message + "\n");
                // Set the success flag to false and post back to the same page
                TempData["ForgotUsernameIsSuccessful"] = false;
                return RedirectToCurrentUmbracoPage();
            }
        }

        [HttpPost]
        public ActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return CurrentUmbracoPage();
            }

            // Get the member
            var member = Services.MemberService.GetByUsername(model.UserName);

            if (member == null)
            {
                // If the user doesn't exists, check the HRI API to see if this is a returning IWS user
                var currentUmbracoPage = InitiateSecurityUpgradeForIwsUser("model", model.UserName);
                if (currentUmbracoPage != null)
                {
                    return currentUmbracoPage;
                }

                // There is an API error
                ModelState.AddModelError("model", UsernameDoesNotExist);
                return CurrentUmbracoPage();
            }

            if (member.IsApproved && !Roles.IsUserInRole(model.UserName, "Registered"))
            { // User is in process of security upgrade
                return SendResetPasswordEmailAndRedirectToSecurityUpgradePage(model.UserName);
            }

            // Create a random Guid
            Guid key = Guid.NewGuid();
            // Update the user's Guid field
            member.SetValue("guid", key.ToString());
            // Save the updated information
            Services.MemberService.Save(member);

            SendResetPasswordEmail(member.Email, member.Username, key.ToString());

            TempData["ForgotPasswordIsSuccessful"] = true;
            return RedirectToCurrentUmbracoPage();
        }

        /// <summary>
        /// This version is called from the resend email page. It sends them a new verification email
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]<commit_msg>HR-283 Locked out users changing password receive a stack trace<commit_after>﻿using System.Web.Security;
using HRI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web.Mvc;
using Umbraco.Core.Models;
using Umbraco.Web;
using log4net;

namespace HRI.Controllers
{
    public class EmailSurfaceController : HriSufraceController
    {
        static readonly ILog logger = LogManager.GetLogger(typeof(EmailSurfaceController));

        private const string UsernameDoesNotExist = "Sorry, that user name does not exist in our system.";

        /// <summary>
        /// Emails the Web Administrator with a message from a member
        /// </summary>
        /// <param name="model">A Contact Form view model</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ContactUs(ContactFormViewModel model)
        {
            try
            {
                string mailData = CurrentPage.GetPropertyValue<string>("categoriesAndEmails");
                IDictionary<string, IEnumerable<string>> categoriesAndEmails = ContactFormViewModel.GetCategoriesAndEmails(mailData);
                IEnumerable<string> emails = categoriesAndEmails[model.MessageType];

                const string na = "N/A";
                var message = string.Join(
                    Environment.NewLine,
                    string.Format("Member ID: {0}", model.MemberId ?? na),
                    string.Format("First Name: {0}", model.FirstName),
                    string.Format("Last Name: {0}", model.LastName),
                    string.Format("Y Number: {0}", model.YNumber ?? na),
                    string.Format("Username: {0}", model.Username ?? na),
                    string.Format("Email: {0}", model.Email),
                    string.Format("Phone Number: {0}", model.PhoneNumber),
                    "Message:",
                    Environment.NewLine,
                    model.Message);

                foreach (string email in emails)
                    try
                    {
                        SendEmail(email, model.MessageType, message);
                    }
                    catch (Exception ex)
                    {
                        logger.Error("Send failed to " + email, ex);
                    }

                // Set the sucess flag to true and post back to the same page
                TempData["IsSuccessful"] = true;
                return RedirectToCurrentUmbracoPage();
            }
            catch (Exception) // If the message failed to send
            {
                // Set the success flag to false and post back to the same page
                TempData["IsSuccessful"] = false;
                return RedirectToCurrentUmbracoPage();
            }
        }

        [HttpPost]
        public ActionResult ForgotUserName([Bind(Prefix = "forgotUserNameViewModel")]ForgotUserNameViewModel model)
        {
            try
            {
                Dictionary<string,string> dynamicText = new Dictionary<string, string>();
                // Attempt to get the member based on the given email address
                var member = Services.MemberService.GetByEmail(model.Email);
                
                // If a member with that email exists
                if (member != null)
                {
                    // Build a dictionary for all teh dynamic text in the email template
                    dynamicText = new Dictionary<string,string>
                    {
                        {"<%FirstName%>", member.GetValue("firstName").ToString()},
                        {"<%UserName%>", member.Username}
                    };
                }
                else
                {
                    // try get user from API
                    var hriUser = MakeInternalApiCallJson("GetRegisteredUserByEmail", new Dictionary<string, string> { { "email", model.Email } });
                    if (hriUser != null)
                    {
                        dynamicText = new Dictionary<string, string>
                        {
                            {"<%FirstName%>", hriUser["FirstName"].ToString()},
                            {"<%UserName%>", hriUser["UserName"].ToString()}
                        };
                    }
                }

                if (dynamicText.Any())
                {
                    // Get the Umbraco root node to access dynamic information (phone numbers, emails, ect)
                    IPublishedContent root = Umbraco.TypedContentAtRoot().First();

                    // add phone number to dynamic text
                    dynamicText.Add("<%PhoneNumber%>", root.GetProperty("phoneNumber").Value.ToString());

                    //Get the Verification Email Template ID
                    var emailTemplateId = root.GetProperty("forgotUserNameEmailTemplate").Value;
                    
                    SendEmail(model.Email, "Health Republic Insurance - Username Recovery",
                        BuildEmail((int) emailTemplateId, dynamicText));

                    // Set the sucess flag to true and post back to the same page
                    TempData["ForgotUsernameIsSuccessful"] = true;
                    return RedirectToCurrentUmbracoPage();
                }

                // The email has no member associated with it
                // Set the success flag to false and post back to the same page
                TempData["ForgotUsernameIsSuccessful"] = false;
                TempData["EmailNotFound"] = true;
                return RedirectToCurrentUmbracoPage();
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("forgotUserNameViewModel", ex.Message + "\n" + ex.InnerException.Message + "\n");
                // Set the success flag to false and post back to the same page
                TempData["ForgotUsernameIsSuccessful"] = false;
                return RedirectToCurrentUmbracoPage();
            }
        }

        [HttpPost]
        public ActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return CurrentUmbracoPage();
            }

            // Get the member
            var member = Services.MemberService.GetByUsername(model.UserName);

            if (member == null)
            {
                // If the user doesn't exists, check the HRI API to see if this is a returning IWS user
                var currentUmbracoPage = InitiateSecurityUpgradeForIwsUser("model", model.UserName);
                if (currentUmbracoPage != null)
                {
                    return currentUmbracoPage;
                }

                // There is an API error
                ModelState.AddModelError("model", UsernameDoesNotExist);
                return CurrentUmbracoPage();
            }

            if (member.IsLockedOut)
                Membership.Provider.UnlockUser(model.UserName);

            if (member.IsApproved && !Roles.IsUserInRole(model.UserName, "Registered"))
            { // User is in process of security upgrade
                return SendResetPasswordEmailAndRedirectToSecurityUpgradePage(model.UserName);
            }

            // Create a random Guid
            Guid key = Guid.NewGuid();
            // Update the user's Guid field
            member.SetValue("guid", key.ToString());
            // Save the updated information
            Services.MemberService.Save(member);

            SendResetPasswordEmail(member.Email, member.Username, key.ToString());

            TempData["ForgotPasswordIsSuccessful"] = true;
            return RedirectToCurrentUmbracoPage();
        }

        /// <summary>
        /// This version is called from the resend email page. It sends them a new verification email
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
{'fraction_non_alphanumeric': 0.08991325270689546, 'fraction_numerical': 0.00120306464889508, 'mean_word_length': 1.5242128815726386, 'pattern_counts': {'":': 0, '<': 55, '<?xml version=': 0, '>': 55, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5204333', 'n_tokens_mistral': 3791, 'n_tokens_neox': 3501, 'n_words': 983}