Example #1
0
        /// <summary>
        /// This method fires when the user clicks the Send Link button and it
        /// sends the user a reset password link via Email
        /// </summary>
        /// <param name="sender">The btnSendForgotLink DevEx button</param>
        /// <param name="e">The Click event</param>
        protected void btnSendForgotLink_Click(object sender, EventArgs e)
        {
            //Only continue if the page is valid
            if (ASPxEdit.AreEditorsValid(this, btnSendForgotLink.ValidationGroup))
            {
                // Validate the user's email address
                var         manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                PyramidUser user    = manager.FindByName(txtUsername.Text);

                if (user == null || !manager.IsEmailConfirmed(user.Id))
                {
                    msgSys.ShowMessageToUser("warning", "Email Failure", "The user either does not exist or is not confirmed.", 25000);
                }
                else
                {
                    //Send the reset link to the user
                    string code        = manager.GeneratePasswordResetToken(user.Id);
                    string callbackUrl = IdentityHelper.GetResetPasswordRedirectUrl(code, Request);
                    manager.SendEmail(user.Id, "Reset your password", Utilities.GetEmailHTML(callbackUrl, "Reset Password", true, "Password Reset Requested", "Please reset your password by clicking the Reset Password link below.", Request));

                    //Show the email sent div and hide the forgot div
                    divEmailSent.Visible = true;
                    divForgot.Visible    = false;
                }
            }
        }
        /// <summary>
        /// This method fires when the user sends a confirmation email
        /// </summary>
        /// <param name="sender">The lbSendConfirmEmail LinkButton</param>
        /// <param name="e">The Click event</param>
        protected void lbSendConfirmEmail_Click(object sender, EventArgs e)
        {
            //The user object
            PyramidUser user = null;

            //Get the user object
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                user = context.Users.Where(u => u.Id == hfUserPK.Value).FirstOrDefault();
            }

            //Make sure the user exists
            if (user != null && user.Id != null)
            {
                //Get the user manager
                var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();

                //If the user exists, send the user an email to confirm their account
                string emailcode   = manager.GenerateEmailConfirmationToken(user.Id);
                string callbackUrl = IdentityHelper.GetAccountConfirmationRedirectUrl(emailcode, user.Id, Request);
                manager.SendEmail(user.Id, "Confirm your account", Utilities.GetEmailHTML(callbackUrl, "Confirm Account", true, "Welcome " + user.FirstName + " " + user.LastName + "!", "Your user account for the Pyramid Model Implementation Data System was created by an administrator.<br/>Your username for this system is:<br/><br/>" + user.UserName + "<br/><br/>Once you confirm your account and create your password, you will be able to start using the system.<br/>To get started, please click the link below.", Request));

                //Show the user a success message
                msgSys.ShowMessageToUser("success", "Email Sent", "Confirmation email successfully sent!", 5000);
            }
            else
            {
                //Show an error message
                msgSys.ShowMessageToUser("danger", "Error", "The user could not be found!", 10000);
            }
        }
        /// <summary>
        /// This method fires when the user clicks the save button and
        /// it attempts to add a new user to the system with the information
        /// provided on the page
        /// </summary>
        /// <param name="sender">The submitUser control</param>
        /// <param name="e">The Click event</param>
        protected void submitUser_Click(object sender, EventArgs e)
        {
            //Get the user manager
            var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();

            //Create and fill the user object
            PyramidUser newUser = new PyramidUser();

            newUser.FirstName            = txtFirstName.Value.ToString();
            newUser.LastName             = txtLastName.Value.ToString();
            newUser.UserName             = txtUsername.Value.ToString();
            newUser.Email                = txtEmail.Value.ToString();
            newUser.EmailConfirmed       = false;
            newUser.TwoFactorEnabled     = false;
            newUser.PhoneNumber          = (txtPhoneNumber.Value == null ? null : txtPhoneNumber.Value.ToString());
            newUser.PhoneNumberConfirmed = false;

            //Attempt to create the user
            IdentityResult result = manager.Create(newUser, txtPassword.Value.ToString());

            if (result.Succeeded)
            {
                //If the user creation succeeded, send the user an email to confirm their account
                string emailcode   = manager.GenerateEmailConfirmationToken(newUser.Id);
                string callbackUrl = IdentityHelper.GetAccountConfirmationRedirectUrl(emailcode, newUser.Id, Request);
                manager.SendEmail(newUser.Id, "Confirm your account", Utilities.GetEmailHTML(callbackUrl, "Confirm Account", true, "Welcome " + newUser.FirstName + " " + newUser.LastName + "!", "Your user account for the Pyramid Model Implementation Data System was created by an administrator.<br/>Your username for this system is:<br/><br/>" + newUser.UserName + "<br/><br/>Once you confirm your account and create your password, you will be able to start using the system.<br/>To get started, please click the link below.", Request));

                //Add the user to their identity role
                manager.AddToRole(newUser.Id, ddIdentityRole.SelectedItem.Text.ToString());

                //Add the user to their program role
                using (PyramidContext context = new PyramidContext())
                {
                    //Create the UserProgramRole object and fill it
                    UserProgramRole userPrgRole = new UserProgramRole();
                    userPrgRole.CreateDate        = DateTime.Now;
                    userPrgRole.Creator           = User.Identity.Name;
                    userPrgRole.ProgramFK         = Convert.ToInt32(ddProgram.Value);
                    userPrgRole.ProgramRoleCodeFK = Convert.ToInt32(ddProgramRole.Value);
                    userPrgRole.Username          = newUser.UserName;

                    //Add the UserProgramRole to the database and save
                    context.UserProgramRole.Add(userPrgRole);
                    context.SaveChanges();
                }

                //Redirect the user
                Response.Redirect("/Admin/UserManagement?message=CreateUserSuccess");
            }
            else
            {
                msgSys.ShowMessageToUser("danger", "Error", result.Errors.FirstOrDefault(), 120000);
            }
        }
Example #4
0
        /// <summary>
        /// This method gets the UserProgramRoles rows for the user and
        /// it binds those results to the proper Repeater
        /// </summary>
        private void BindUserProgramRoles(PyramidContext currentContext, PyramidUser currentUser)
        {
            //Get the ProgramRoles for the user
            var userProgramRoles = currentContext.UserProgramRole
                                   .Include(upr => upr.Program)
                                   .Include(upr => upr.CodeProgramRole)
                                   .Where(upr => upr.Username == currentUser.UserName)
                                   .OrderBy(upr => upr.Program.ProgramName)
                                   .ToList();

            repeatUserRoles.DataSource = userProgramRoles;
            repeatUserRoles.DataBind();
        }
Example #5
0
        /// <summary>
        /// This method accepts a user object and updates the user in the database
        /// </summary>
        /// <param name="user">A PyramidUser object</param>
        /// <returns>True if the edit succeeded, false otherwise</returns>
        public bool UpdateUser(PyramidUser user)
        {
            //Get the user
            var founduser = appContext.Users.Where(x => x.Id == user.Id).AsQueryable().FirstOrDefault();

            if (founduser == null)
            {
                //If the user does not exist, add it
                appContext.Users.Add(user);
            }
            else
            {
                //Update the user's values
                appContext.Entry(founduser).CurrentValues.SetValues(user);
            }

            //Return a bool that indicates if the save succeeded
            return(appContext.SaveChanges() > 0);
        }
Example #6
0
        /// <summary>
        /// This method returns a user's Identity role from the database
        /// </summary>
        /// <param name="username">The user's username</param>
        /// <param name="userManager">The ApplicationUserManager</param>
        /// <returns>The identity role name if it can, null if it fails</returns>
        public static string GetIdentityRoleByUsername(string username, ApplicationUserManager userManager)
        {
            string returnVal;

            try
            {
                //Get the user
                PyramidUser user = userManager.FindByName(username);

                //Get the identity role (our system only allows for a user to have one)
                returnVal = userManager.GetRoles(user.Id).FirstOrDefault();
            }
            catch (Exception ex)
            {
                //If an error occurred, log it and return null
                LogException(ex);
                returnVal = null;
            }

            return(returnVal);
        }
Example #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //Get the current program role
            currentProgramRole = Utilities.GetProgramRoleFromSession(Session);

            //Get the user manager
            manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();

            //Get the user id from the query string
            string id = Request.QueryString["Id"];

            //Get the user object
            currentUser = manager.FindById(id);

            //Make sure the user exists
            if (currentUser == null)
            {
                Response.Redirect("/Admin/UserManagement.aspx?message=UserNotFound");
            }

            if (!IsPostBack)
            {
                using (PyramidContext context = new PyramidContext())
                {
                    //Show the user's program roles
                    BindUserProgramRoles(context, currentUser);

                    //Get the program list
                    var programs = context.Program.AsNoTracking().Include(p => p.Hub).OrderBy(p => p.ProgramName).Select(p => new {
                        p.ProgramPK,
                        ProgramName = p.ProgramName + " (" + p.Hub.Name + ")"
                    }).ToList();
                    ddProgram.DataSource = programs;
                    ddProgram.DataBind();

                    //Get the program role list, limited to the roles the user is allowed to add
                    var programRoles = context.CodeProgramRole.AsNoTracking()
                                       .Where(cpr => cpr.RolesAuthorizedToModify.Contains((currentProgramRole.RoleFK.Value.ToString() + ",")))
                                       .OrderBy(cpr => cpr.RoleName)
                                       .ToList();
                    ddProgramRole.DataSource = programRoles;
                    ddProgramRole.DataBind();
                }

                //Get the identity roles
                var identityRoles = appContext.Roles.OrderBy(r => r.Name).ToList();

                //Remove the guest role because it is not implemented in any way
                IdentityRole guestRole = identityRoles.Where(ir => ir.Name == "Guest").FirstOrDefault();
                if (guestRole != null)
                {
                    identityRoles.Remove(guestRole);
                }

                //Only allow super admins and application admins who are editing themselves to see the Admin identity role
                if (currentProgramRole.RoleFK.Value == (int)Utilities.ProgramRoleFKs.SUPER_ADMIN || (currentProgramRole.RoleFK.Value == (int)Utilities.ProgramRoleFKs.APPLICATION_ADMIN && User.Identity.Name == currentUser.UserName))
                {
                    //Do not remove the Admin identity role
                }
                else
                {
                    //Remove the Admin identity role
                    IdentityRole adminRole = identityRoles.Where(ir => ir.Name == "Admin").FirstOrDefault();
                    identityRoles.Remove(adminRole);
                }
                //Bind the identity role dropdown
                ddIdentityRole.DataSource = identityRoles;
                ddIdentityRole.DataBind();

                //If the user exists, fill the form
                txtFirstName.Value          = currentUser.FirstName;
                txtLastName.Value           = currentUser.LastName;
                txtEmail.Value              = currentUser.Email;
                txtPhoneNumber.Value        = currentUser.PhoneNumber;
                deLockoutEndDate.Value      = (currentUser.LockoutEndDateUtc.HasValue ? currentUser.LockoutEndDateUtc.Value.ToString("MM/dd/yyyy") : "");
                ddIdentityRole.SelectedItem = ddIdentityRole.Items.FindByValue(currentUser.Roles.FirstOrDefault().RoleId);

                //Set focus to the first name field
                txtFirstName.Focus();
            }
        }
Example #8
0
        /// <summary>
        /// When the user clicks the Save button, save the changes to the user
        /// </summary>
        /// <param name="sender">The submitUser control</param>
        /// <param name="e">The Click event</param>
        protected void submitUser_Click(object sender, EventArgs e)
        {
            //Make sure the current user is correct
            currentUser = manager.FindById(currentUser.Id);

            //Whether or not the email changed
            bool emailChanged = false;

            //Only continue if the page is valid
            if (ASPxEdit.AreEditorsValid(this, submitUser.ValidationGroup))
            {
                //Check to see if the user's email changed
                if (currentUser.Email != Convert.ToString(txtEmail.Value))
                {
                    //The email changed
                    emailChanged = true;
                }

                //Only de-confirm the user's phone if it changed
                if (txtPhoneNumber.Value == null || (currentUser.PhoneNumber != txtPhoneNumber.Value.ToString()))
                {
                    currentUser.PhoneNumberConfirmed = false;
                }

                //Update the user's role
                if (currentUser.Roles.FirstOrDefault().RoleId != Convert.ToString(ddIdentityRole.Value))
                {
                    //Get the old role and new role
                    string oldRole = appContext.Roles.Find(currentUser.Roles.FirstOrDefault().RoleId).Name;
                    string newRole = appContext.Roles.Find(Convert.ToString(ddIdentityRole.Value)).Name;

                    //Change the role
                    manager.RemoveFromRole(currentUser.Id, oldRole);
                    manager.AddToRole(currentUser.Id, newRole);
                }

                //Set the user's information
                currentUser.EmailConfirmed    = !emailChanged;
                currentUser.PhoneNumber       = (txtPhoneNumber.Value == null ? null : txtPhoneNumber.Value.ToString());
                currentUser.Email             = txtEmail.Value.ToString();
                currentUser.FirstName         = txtFirstName.Value.ToString();
                currentUser.LastName          = txtLastName.Value.ToString();
                currentUser.LockoutEndDateUtc = (String.IsNullOrWhiteSpace(Convert.ToString(deLockoutEndDate.Value)) ? (DateTime?)null : Convert.ToDateTime(deLockoutEndDate.Value));
                currentUser.UpdateTime        = DateTime.Now;

                //Update the user in the database
                IdentityResult result = manager.Update(currentUser);

                if (result.Succeeded)
                {
                    //Send an email if the email changed
                    if (emailChanged)
                    {
                        //Generate the confirmation token and url
                        string code        = manager.GenerateEmailConfirmationToken(currentUser.Id);
                        string callbackUrl = IdentityHelper.GetEmailConfirmationRedirectUrl(code, currentUser.Id, Request);

                        //Send the confirmation email to the user via email
                        manager.SendEmail(currentUser.Id, "Confirm your email address change", Utilities.GetEmailHTML(callbackUrl, "Confirm Email", true, "Email Updated", "Please confirm your email address change by clicking the Confirm Email link below.", Request));
                    }

                    //Redirect the user to the user management page
                    Response.Redirect("/Admin/UserManagement.aspx?message=EditUserSuccess");
                }
                else
                {
                    //Show the user an error message
                    msgSys.ShowMessageToUser("danger", "Error", result.Errors.FirstOrDefault(), 120000);
                }
            }
        }
Example #9
0
        protected void Page_Load()
        {
            //Get the user manager
            userManager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();

            //Get the current user
            CurrentUser = userManager.FindById(User.Identity.GetUserId());

            if (!IsPostBack)
            {
                //Fill the text boxes
                txtPhoneNumber.Value = CurrentUser.PhoneNumber;
                txtEmail.Text        = CurrentUser.Email;

                // Render success message
                var message = Request.QueryString["m"];
                if (message != null)
                {
                    // Strip the query string from action
                    Form.Action = ResolveUrl("~/Account/Manage");

                    SuccessMessage =
                        message == "ChangePwdSuccess" ? "Your password has been successfully changed!"
                        : message == "SetPwdSuccess" ? "Your password has been successfully set!"
                        : message == "RemoveLoginSuccess" ? "The account was successfully removed!"
                        : message == "AddPhoneNumberSuccess" ? "Phone number has been successfully added!"
                        : message == "VerifyPhoneNumberSuccess" ? "Phone number has been successfully verified!"
                        : message == "RemovePhoneNumberSuccess" ? "Phone number was successfully removed!"
                        : String.Empty;

                    //Show the message
                    msgSys.ShowMessageToUser("success", "Success", SuccessMessage, 15000);
                }

                //Show or hide the two-factor buttons
                ShowHideTwoFactorButtons(CurrentUser.TwoFactorEnabled);

                //Show or hide the phone buttons
                ShowHidePhoneButtons(CurrentUser.PhoneNumber, CurrentUser.PhoneNumberConfirmed);

                using (PyramidContext context = new PyramidContext())
                {
                    //Get the user's selected customization options
                    List <spGetUserCustomizationOptions_Result> selectedOptions = context.spGetUserCustomizationOptions(CurrentUser.UserName).ToList();

                    //Fill and set the user customization option dropdowns

                    //-----------------  Fireworks  -------------------------
                    List <CodeCustomizationOptionValue> fireworkOptions = context.CodeCustomizationOptionValue.AsNoTracking()
                                                                          .Include(ccov => ccov.CodeCustomizationOptionType)
                                                                          .Where(ccov => ccov.CodeCustomizationOptionType.Description.ToLower() == "fireworks")
                                                                          .OrderBy(ccov => ccov.OrderBy)
                                                                          .ToList();

                    ddFireworks.DataSource = fireworkOptions;
                    ddFireworks.DataBind();

                    //Set the selected value
                    int fireworksOption = selectedOptions.Where(so => so.OptionTypeDescription.ToLower() == "fireworks").Select(so => so.OptionValuePK).FirstOrDefault().GetValueOrDefault();
                    ddFireworks.SelectedItem = ddFireworks.Items.FindByValue(fireworksOption);
                    //-----------------  End Fireworks  -------------------------
                }
            }
        }
Example #10
0
        /// <summary>
        /// This method executes when the user clicks the save button for the  UserFileUploads
        /// and it saves the UserFileUpload information to the database
        /// </summary>
        /// <param name="sender">The submitUserFileUpload submit user control</param>
        /// <param name="e">The Click event</param>
        protected void submitFileUpload_Click(object sender, EventArgs e)
        {
            //Allow editors and hub data viewers to add files
            if (currentProgramRole.AllowedToEdit.Value ||
                currentProgramRole.RoleFK.Value == (int)Utilities.ProgramRoleFKs.HUB_DATA_VIEWER)
            {
                //Get the file to upload
                UploadedFile file = bucUploadFile.UploadedFiles[0];

                if (file.ContentLength > 0 && file.IsValid)
                {
                    //Get the actual file name
                    string actualFileName = Path.GetFileNameWithoutExtension(file.FileName) + "-" +
                                            Path.GetRandomFileName().Substring(0, 6) +
                                            Path.GetExtension(file.FileName);

                    //Get the display file name
                    string displayFileName = Path.GetFileNameWithoutExtension(file.FileName);

                    //Get the file type
                    string fileExtension = Path.GetExtension(file.FileName).ToLower();
                    string fileType;
                    switch (fileExtension)
                    {
                    case ".pdf":
                        fileType = "pdf";
                        break;

                    case ".doc":
                    case ".docx":
                        fileType = "word";
                        break;

                    case ".ppt":
                    case ".pptx":
                        fileType = "powerpoint";
                        break;

                    case ".xls":
                    case ".xlsx":
                        fileType = "excel";
                        break;

                    case ".jpeg":
                    case ".jpg":
                    case ".png":
                        fileType = "image";
                        break;

                    default:
                        fileType = "alt";
                        break;
                    }

                    //Upload the file to Azure storage
                    string filePath = Utilities.UploadFileToAzureStorage(file.FileBytes, actualFileName,
                                                                         Utilities.ConstantAzureStorageContainerName.UPLOADED_FILES.ToString());

                    if (!String.IsNullOrWhiteSpace(filePath))
                    {
                        PyramidUser currentUser = null;
                        // Validate the user password
                        using (var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>())
                        {
                            //Try to get the user
                            currentUser = manager.FindByName(User.Identity.Name);
                        }

                        using (PyramidContext context = new PyramidContext())
                        {
                            //Create the database object for the file
                            UserFileUpload currentUserFileUpload = new UserFileUpload();
                            currentUserFileUpload.CreateDate      = DateTime.Now;
                            currentUserFileUpload.Creator         = User.Identity.Name;
                            currentUserFileUpload.UploadedBy      = currentUser.FirstName + " " + currentUser.LastName;
                            currentUserFileUpload.Description     = txtFileDescription.Value.ToString();
                            currentUserFileUpload.FileType        = fileType;
                            currentUserFileUpload.DisplayFileName = displayFileName;
                            currentUserFileUpload.FileName        = actualFileName;
                            currentUserFileUpload.FilePath        = filePath;
                            currentUserFileUpload.TypeCodeFK      = Convert.ToInt32(ddFileType.Value);

                            //Set the proper FKs
                            if (currentUserFileUpload.TypeCodeFK == (int)Utilities.FileTypeFKs.PROGRAM_WIDE)
                            {
                                currentUserFileUpload.ProgramFK = Convert.ToInt32(ddProgram.Value);
                                currentUserFileUpload.HubFK     = null;
                                currentUserFileUpload.StateFK   = null;
                                currentUserFileUpload.CohortFK  = null;
                            }
                            else if (currentUserFileUpload.TypeCodeFK == (int)Utilities.FileTypeFKs.HUB_WIDE)
                            {
                                currentUserFileUpload.ProgramFK = null;
                                currentUserFileUpload.HubFK     = Convert.ToInt32(ddHub.Value);
                                currentUserFileUpload.StateFK   = null;
                                currentUserFileUpload.CohortFK  = null;
                            }
                            else if (currentUserFileUpload.TypeCodeFK == (int)Utilities.FileTypeFKs.STATE_WIDE)
                            {
                                currentUserFileUpload.ProgramFK = null;
                                currentUserFileUpload.HubFK     = null;
                                currentUserFileUpload.StateFK   = Convert.ToInt32(ddState.Value);
                                currentUserFileUpload.CohortFK  = null;
                            }
                            else if (currentUserFileUpload.TypeCodeFK == (int)Utilities.FileTypeFKs.COHORT_WIDE)
                            {
                                currentUserFileUpload.ProgramFK = null;
                                currentUserFileUpload.HubFK     = null;
                                currentUserFileUpload.StateFK   = null;
                                currentUserFileUpload.CohortFK  = Convert.ToInt32(ddCohort.Value);
                            }

                            //Save to the database
                            context.UserFileUpload.Add(currentUserFileUpload);
                            context.SaveChanges();

                            //Redirect the user back to this page with a message
                            Response.Redirect("/Pages/UploadedFiles.aspx?messageType=UploadSuccess");
                        }
                    }
                    else
                    {
                        msgSys.ShowMessageToUser("danger", "Upload Failed", "The file failed to upload properly, please try again.", 10000);
                    }
                }
                else
                {
                    msgSys.ShowMessageToUser("danger", "Error", "No valid file was selected to be uploaded!", 120000);
                }
            }
            else
            {
                msgSys.ShowMessageToUser("danger", "Error", "You are not authorized to make changes!", 120000);
            }
        }
Example #11
0
        /// <summary>
        /// This method fires when the user clicks the Login button and it attempts to log
        /// the user in
        /// </summary>
        /// <param name="sender">The btnLogin DevExpress button</param>
        /// <param name="e">The Click event</param>
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (ASPxEdit.AreEditorsValid(this, btnLogin.ValidationGroup))
            {
                // Validate the user password
                var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();

                //Try to get the user
                PyramidUser user = manager.FindByName(txtUsername.Text);

                //Make sure that the user is confirmed
                if (user != null && manager.IsEmailConfirmed(user.Id))
                {
                    //Try to sign the user in
                    var result = signinManager.PasswordSignIn(txtUsername.Text, txtPassword.Text, false, user.LockoutEnabled);

                    switch (result)
                    {
                    case SignInStatus.Success:
                        //The user successfully logged in

                        List <UserProgramRole> userProgramRoles;
                        List <spGetUserCustomizationOptions_Result> userCustomizationOptions;
                        using (PyramidContext context = new PyramidContext())
                        {
                            //Get the user's program roles
                            userProgramRoles = context.UserProgramRole.AsNoTracking()
                                               .Include(upr => upr.CodeProgramRole)
                                               .Include(upr => upr.Program)
                                               .Where(upr => upr.Username == txtUsername.Text).ToList();

                            //Get the user's customization options
                            userCustomizationOptions = context.spGetUserCustomizationOptions(txtUsername.Text).ToList();

                            //Keep a record of successful logins
                            LoginHistory history = new LoginHistory();
                            history.Username  = txtUsername.Text;
                            history.LoginTime = DateTime.Now;

                            //If the user only has one program role, record it in the login history
                            if (userProgramRoles.Count == 1)
                            {
                                history.ProgramFK = userProgramRoles.First().ProgramFK;
                                history.Role      = userProgramRoles.First().CodeProgramRole.RoleName;
                            }

                            //Save the login history
                            context.LoginHistory.Add(history);
                            context.SaveChanges();

                            //Save the LoginHistory primary key to the session for later access
                            Session["LoginHistoryPK"] = history.LoginHistoryPK;
                        }

                        //Set the user customization options cookie
                        Utilities.SetCustomizationOptionCookie(userCustomizationOptions);

                        //Redirect the user based on the number of roles they have
                        if (userProgramRoles.Count > 1)
                        {
                            Response.Redirect(String.Format("/Account/SelectRole.aspx?ReturnUrl={0}",
                                                            (Request.QueryString["ReturnUrl"] != null ? Request.QueryString["ReturnUrl"].ToString() : "/Default.aspx")));
                        }
                        else
                        {
                            //To hold the role information
                            ProgramAndRoleFromSession roleInfo = new ProgramAndRoleFromSession();

                            //Get the UserProgramRole
                            UserProgramRole userRole = userProgramRoles.FirstOrDefault();

                            //Set the session variables for the program roles
                            roleInfo.RoleFK           = userRole.CodeProgramRole.CodeProgramRolePK;
                            roleInfo.RoleName         = userRole.CodeProgramRole.RoleName;
                            roleInfo.AllowedToEdit    = userRole.CodeProgramRole.AllowedToEdit;
                            roleInfo.CurrentProgramFK = userRole.ProgramFK;
                            roleInfo.ProgramName      = userRole.Program.ProgramName;

                            //Get the hub and state information
                            using (PyramidContext context = new PyramidContext())
                            {
                                Program currentProgram = context.Program.AsNoTracking()
                                                         .Include(p => p.Hub)
                                                         .Include(p => p.State)
                                                         .Include(p => p.ProgramType)
                                                         .Where(p => p.ProgramPK == userRole.ProgramFK).FirstOrDefault();

                                roleInfo.HubFK             = currentProgram.HubFK;
                                roleInfo.HubName           = currentProgram.Hub.Name;
                                roleInfo.StateFK           = currentProgram.StateFK;
                                roleInfo.StateName         = currentProgram.State.Name;
                                roleInfo.StateLogoFileName = currentProgram.State.LogoFilename;
                                roleInfo.StateCatchphrase  = currentProgram.State.Catchphrase;
                                roleInfo.StateDisclaimer   = currentProgram.State.Disclaimer;

                                //Set the allowed program fks
                                if (roleInfo.RoleFK == (int)Utilities.ProgramRoleFKs.HUB_DATA_VIEWER)
                                {
                                    //Hub viewer, allow them to see the programs in that hub
                                    var hubPrograms = context.Program.AsNoTracking()
                                                      .Where(p => p.HubFK == roleInfo.HubFK.Value)
                                                      .ToList();
                                    roleInfo.ProgramFKs = hubPrograms
                                                          .Select(hp => hp.ProgramPK)
                                                          .ToList();

                                    //Allow them to see all cohorts in their hub
                                    roleInfo.CohortFKs = hubPrograms
                                                         .Select(hp => hp.CohortFK)
                                                         .Distinct()
                                                         .ToList();

                                    //Don't restrict their view of the BOQs
                                    roleInfo.ShowBOQ    = true;
                                    roleInfo.ShowBOQFCC = true;
                                }
                                else if (roleInfo.RoleFK == (int)Utilities.ProgramRoleFKs.APPLICATION_ADMIN)
                                {
                                    //App admin, allow them to see all programs in a state
                                    roleInfo.ProgramFKs = context.Program.AsNoTracking()
                                                          .Where(p => p.StateFK == roleInfo.StateFK.Value)
                                                          .Select(p => p.ProgramPK).ToList();

                                    //Allow them to see all cohorts in a state
                                    roleInfo.CohortFKs = context.Cohort.AsNoTracking()
                                                         .Where(c => c.StateFK == roleInfo.StateFK.Value)
                                                         .Select(c => c.CohortPK).ToList();

                                    //Don't restrict their view of the BOQs
                                    roleInfo.ShowBOQ    = true;
                                    roleInfo.ShowBOQFCC = true;
                                }
                                else if (roleInfo.RoleFK == (int)Utilities.ProgramRoleFKs.SUPER_ADMIN)
                                {
                                    //Super admin, all programs in all states
                                    roleInfo.ProgramFKs = context.Program.AsNoTracking()
                                                          .Select(p => p.ProgramPK).ToList();

                                    //All cohorts
                                    roleInfo.CohortFKs = context.Cohort.AsNoTracking()
                                                         .Select(c => c.CohortPK).ToList();

                                    //Don't restrict their view of the BOQs
                                    roleInfo.ShowBOQ    = true;
                                    roleInfo.ShowBOQFCC = true;
                                }
                                else
                                {
                                    //Something else, limit to the current program fk
                                    List <int> programFKs = new List <int>();
                                    programFKs.Add(roleInfo.CurrentProgramFK.Value);
                                    roleInfo.ProgramFKs = programFKs;

                                    //Limit to current cohort fk
                                    List <int> cohortFKs = new List <int>();
                                    cohortFKs.Add(currentProgram.CohortFK);
                                    roleInfo.CohortFKs = cohortFKs;

                                    //Determine if this program is a FCC program
                                    var fccProgramTypes = currentProgram.ProgramType
                                                          .Where(pt => pt.TypeCodeFK == (int)Utilities.ProgramTypeFKs.FAMILY_CHILD_CARE ||
                                                                 pt.TypeCodeFK == (int)Utilities.ProgramTypeFKs.GROUP_FAMILY_CHILD_CARE)
                                                          .ToList();

                                    //Limit their view to the right BOQ type
                                    if (fccProgramTypes.Count > 0)
                                    {
                                        roleInfo.ShowBOQ    = false;
                                        roleInfo.ShowBOQFCC = true;
                                    }
                                    else
                                    {
                                        roleInfo.ShowBOQ    = true;
                                        roleInfo.ShowBOQFCC = false;
                                    }
                                }
                            }

                            //Add the role information to the session
                            Utilities.SetProgramRoleInSession(Session, roleInfo);

                            //Redirect the user
                            Response.Redirect(Request.QueryString["ReturnUrl"] != null ? Request.QueryString["ReturnUrl"].ToString() : "/Default.aspx");
                        }
                        break;

                    case SignInStatus.LockedOut:
                        Response.Redirect("/Account/Lockout");
                        break;

                    case SignInStatus.RequiresVerification:
                        Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}",
                                                        Request.QueryString["ReturnUrl"]), true);
                        break;

                    case SignInStatus.Failure:
                    default:
                        //Show the user an error message
                        msgSys.ShowMessageToUser("danger", "Error", "Invalid login attempt", 120000);

                        //Focus the password text box
                        txtPassword.Focus();
                        break;
                    }
                }
                else
                {
                    msgSys.ShowMessageToUser("danger", "Error", "Invalid login attempt", 120000);
                }
            }
        }