//*****************USERS **********************************
        public static int CreateT_OE_USERS(global::System.String uSER_ID, global::System.String pWD_HASH, global::System.String pWD_SALT, global::System.String fNAME, global::System.String lNAME, global::System.String eMAIL, global::System.Boolean aCT_IND, global::System.Boolean iNITAL_PWD_FLAG, global::System.DateTime?lASTLOGIN_DT, global::System.String pHONE, global::System.String pHONE_EXT, global::System.String cREATE_USER)
        {
            try
            {
                TOeUsers u = new TOeUsers();
                u.UserId        = uSER_ID;
                u.PwdHash       = pWD_HASH;
                u.PwdSalt       = pWD_SALT;
                u.Fname         = fNAME;
                u.Lname         = lNAME;
                u.Email         = eMAIL;
                u.ActInd        = aCT_IND;
                u.InitalPwdFlag = iNITAL_PWD_FLAG;
                u.EffectiveDt   = System.DateTime.Now;
                u.LastloginDt   = lASTLOGIN_DT;
                u.Phone         = pHONE;
                u.PhoneExt      = pHONE_EXT;
                u.CreateDt      = System.DateTime.Now;
                u.CreateUserid  = cREATE_USER;

                _db.TOeUsers.Add(u);
                _db.SaveChanges();
                return(u.UserIdx);
            }
            catch (Exception ex)
            {
                return(0);
            }
        }
        public static void SetOrgSessionID(string UserID, string url, IHttpContextAccessor httpContextAccessor)
        {
            TOeUsers u = GetT_OE_USERSByID(UserID);

            if (u != null)
            {
                if (u.DefaultOrgId == null)
                {
                    List <TWqxOrganization> os = db_WQX.GetWQX_USER_ORGS_ByUserIDX(u.UserIdx, false);
                    //if user only belongs to 1 org, update the default org id
                    if (os.Count == 1)
                    {
                        UpdateT_OE_USERSDefaultOrg(u.UserIdx, os[0].OrgId);
                        //HttpContext.Current.Session["OrgID"] = os[0].OrgId;
                        httpContextAccessor.HttpContext.Session.SetString("OrgID", os[0].OrgId);
                    }
                    else if (os.Count > 1)
                    {
                        //TODO: Handle this
                        //HttpContext.Current.Response.Redirect("~/App_Pages/Secure/SetOrg.aspx?ReturnUrl=" + url);
                    }
                    else if (os.Count == 0)
                    {
                        //TODO: Handle this
                        //HttpContext.Current.Response.Redirect("~/App_Pages/Secure/WQXOrgNew.aspx");
                    }
                }
                else
                {
                    //HttpContext.Current.Session["OrgID"] = u.DefaultOrgId;
                    httpContextAccessor.HttpContext.Session.SetString("OrgID", u.DefaultOrgId);
                }
            }
        }
        //public CustomMembership()
        //{
        //    Initialize();
        //}

        public bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            //validate new password length
            if (!Utils.ValidateParameter(ref newPassword, true, true, false, 0, _MinRequiredPasswordLength))
            {
                return(false);
            }

            //Validate Non-AlphaNumeric characters
            char[] charpwd            = newPassword.ToCharArray();
            int    pwdNonNumericCount = 0;

            for (int i = 1; i < newPassword.Length; i++)
            {
                if (!char.IsLetterOrDigit(charpwd[i]))
                {
                    pwdNonNumericCount += 1;
                }
            }

            if (pwdNonNumericCount < _MinRequiredNonalphanumericCharacters)
            {
                return(false);
            }

            TOeUsers u = _unitOfWork.oeUsersRepostory.GetFirstOrDefault(x => x.UserId == username);

            if (u != null)
            {
                //first check accuracy of old password
                if (!CheckPassword(oldPassword, u.PwdHash, u.PwdSalt))
                {
                    return(false);
                }

                //generate new password
                string salt     = GenerateSalt();
                string hashpass = HashPassword(newPassword, MembershipPasswordFormat.Hashed, salt);
                //save updated information
                u.PwdSalt = salt;
                u.PwdHash = hashpass;
                _unitOfWork.oeUsersRepostory.Update(u);
                _unitOfWork.Save();
                return(true);
                //if (db_Accounts.UpdateT_OE_USERS(u.UserIdx, hashpass, salt, null, null, null, null, false, null, null, null, null, "system") > 0)
                //    return true;
                //else
                //    return false;
            }

            return(true);
        }
 public static int DeleteT_OE_USERS(int idx)
 {
     try
     {
         TOeUsers row = new TOeUsers();
         row = (from c in _db.TOeUsers where c.UserIdx == idx select c).First();
         _db.TOeUsers.Remove(row);
         _db.SaveChanges();
         return(1);
     }
     catch (Exception ex)
     {
         return(0);
     }
 }
 public static int UpdateT_OE_USERSDefaultOrg(int idx, string dEFAULT_ORG_ID)
 {
     try
     {
         TOeUsers row = new TOeUsers();
         row = (from c in _db.TOeUsers where c.UserIdx == idx select c).First();
         if (dEFAULT_ORG_ID != null)
         {
             row.DefaultOrgId = dEFAULT_ORG_ID;
         }
         _db.TOeUsers.Update(row);
         _db.SaveChanges();
         return(row.UserIdx);
     }
     catch (Exception ex)
     {
         return(0);
     }
 }
        public bool ValidateUser(string username, string password)
        {
            //raise error if null username/password or too long
            //if (!Utils.ValidateParameter(ref username, true, true, false, 25))
            //    return false;

            //if (!Utils.ValidateParameter(ref password, true, true, false, 100))
            //    return false;

            //check if password matches hashed/salted password
            TOeUsers u = _unitOfWork.oeUsersRepostory.GetFirstOrDefault(x => x.Email == username);

            if (u != null)
            {
                if (u.ActInd == false)
                {
                    return(false); //fail if user is inactive
                }
                if (CheckPassword(password, u.PwdHash, u.PwdSalt))
                {
                    return(true);
                }
                else
                {
                    //db_Accounts.UpdateT_OE_USERS(u.USER_IDX, null, null, null, null, null, null, u.LOG_ATMPT.ConvertOrDefault<int>() < MaxInvalidPasswordAttempts, null, null, null, null, null, u.LOG_ATMPT.ConvertOrDefault<int>() + 1, null, null, null);

                    //user account is locked due to too many invalid login attempts
                    //if (u.LOG_ATMPT.ConvertOrDefault<int>() + 1 > MaxInvalidPasswordAttempts)
                    //    Utils.SendEmail(null, u.EMAIL, "Your account is locked.", "Your user account has been locked due to too many incorrect login attempts. Please contact the system administrator to reset your user account.");

                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
        public string ResetPassword(string username, string answer)
        {
            //T_OE_USERS u = db_Accounts.GetT_OE_USERSByID(username);
            TOeUsers u = _unitOfWork.oeUsersRepostory.GetFirstOrDefault(x => x.UserId == username);

            if (u != null)
            {
                //generate new password
                string newPass = RandomString(8);
                string salt    = GenerateSalt();

                string hashpass = HashPassword(newPass, _PasswordFormat, salt);
                //save updated information
                u.PwdHash = hashpass;
                _unitOfWork.oeUsersRepostory.Update(u);
                _unitOfWork.Save();
                //send email
                string msg = "Your password has been reset. Your new temporary password is: " + "\r\n\r\n";
                msg += newPass + "\r\n\r\n";
                msg += "When you login for the first time you will be asked to set a permanent password.";
                if (string.IsNullOrEmpty(u.Email))
                {
                    return("User does not have email address.");
                }
                if (Utils.SendEmail(null, u.Email.Split(';').ToList(), null, null, "Open Waters Password Reset", msg, null))
                {
                    return("Email has been sent.");
                }
                else
                {
                    return("Error in sending email");
                }
            }
            else
            {
                return("Email does not exist in the system.");
            }
        }
        public static int UpdateT_OE_USERS(int idx, string newPWD_HASH, string newPWD_SALT, string newFNAME, string newLNAME, string newEMAIL, bool?newACT_IND, bool?newINIT_PWD_FLG, DateTime?newEFF_DATE, DateTime?newLAST_LOGIN_DT, string newPHONE, string newPHONE_EXT, string newMODIFY_USR)
        {
            try
            {
                TOeUsers row = new TOeUsers();
                row = (from c in _db.TOeUsers where c.UserIdx == idx select c).First();

                if (newPWD_HASH != null)
                {
                    row.PwdHash = newPWD_HASH;
                }

                if (newPWD_SALT != null)
                {
                    row.PwdSalt = newPWD_SALT;
                }

                if (newFNAME != null)
                {
                    row.Fname = newFNAME;
                }

                if (newLNAME != null)
                {
                    row.Lname = newLNAME;
                }

                if (newEMAIL != null)
                {
                    row.Email = newEMAIL;
                }

                if (newACT_IND != null)
                {
                    row.ActInd = (bool)newACT_IND;
                }

                if (newINIT_PWD_FLG != null)
                {
                    row.InitalPwdFlag = (bool)newINIT_PWD_FLG;
                }

                if (newEFF_DATE != null)
                {
                    row.EffectiveDt = (DateTime)newEFF_DATE;
                }

                if (newLAST_LOGIN_DT != null)
                {
                    row.LastloginDt = (DateTime)newLAST_LOGIN_DT;
                }

                if (newPHONE != null)
                {
                    row.Phone = newPHONE;
                }

                if (newPHONE_EXT != null)
                {
                    row.PhoneExt = newPHONE_EXT;
                }

                if (newMODIFY_USR != null)
                {
                    row.ModifyUserid = newMODIFY_USR;
                }

                row.ModifyDt = System.DateTime.Now;
                _db.TOeUsers.Update(row);
                _db.SaveChanges();
                return(row.UserIdx);
            }
            catch (Exception ex)
            {
                return(0);
            }
        }
Example #9
0
        //***************** EXCEL EXPORT *****************************************
        /// <summary>
        /// Excel Export
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="gv"></param>
        //TODO: Web.UI not supported in core, need to fix
        //public static void RenderGridToExcelFormat(string fileName, GridView gv)
        //{
        //    HttpContext.Current.Response.Clear();
        //    HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
        //    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

        //    using (StringWriter sw = new StringWriter())
        //    {
        //        using (HtmlTextWriter htw = new HtmlTextWriter(sw))
        //        {
        //            //  Create a form to contain the grid
        //            Table table = new Table();

        //            //  add the header row to the table
        //            if (gv.HeaderRow != null)
        //            {
        //                PrepareControlForExport(gv.HeaderRow);
        //                table.Rows.Add(gv.HeaderRow);
        //            }

        //            //  add each of the data rows to the table
        //            foreach (GridViewRow row in gv.Rows)
        //            {
        //                PrepareControlForExport(row);
        //                table.Rows.Add(row);
        //            }

        //            //  add the footer row to the table
        //            if (gv.FooterRow != null)
        //            {
        //                PrepareControlForExport(gv.FooterRow);
        //                table.Rows.Add(gv.FooterRow);
        //            }

        //            //  render the table into the htmlwriter
        //            table.RenderControl(htw);

        //            //  render the htmlwriter into the response
        //            HttpContext.Current.Response.Write(sw.ToString());
        //            HttpContext.Current.Response.End();
        //        }
        //    }

        //}

        /// <summary>
        /// Replace any of the contained controls with literals
        /// </summary>
        /// <param name="control"></param>

        //TODO: Web.UI not supported in core, need to fix
        //private static void PrepareControlForExport(Control control)
        //{
        //    for (int i = 0; i < control.Controls.Count; i++)
        //    {
        //        Control current = control.Controls[i];
        //        if (current is LinkButton)
        //        {
        //            control.Controls.Remove(current);
        //            control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
        //        }
        //        else if (current is ImageButton)
        //        {
        //            control.Controls.Remove(current);
        //            control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
        //        }
        //        else if (current is Image)
        //        {
        //            control.Controls.Remove(current);
        //        }
        //        else if (current is HyperLink)
        //        {
        //            control.Controls.Remove(current);
        //            control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
        //        }
        //        else if (current is DropDownList)
        //        {
        //            control.Controls.Remove(current);
        //            control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
        //        }
        //        else if (current is CheckBox)
        //        {
        //            control.Controls.Remove(current);
        //            control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
        //        }

        //        if (current.HasControls())
        //        {
        //            PrepareControlForExport(current);
        //        }
        //    }
        //}


        /// <summary>
        /// Returns the internal ID of the authenticated user. If using membership, returns membership user. If using external ID provider, returns IPrincipal USERIDX claim
        /// </summary>
        /// <param name="User"></param>
        /// <returns></returns>
        //public static int GetUserIDX(System.Security.Principal.IPrincipal User)
        //{
        //    try
        //    {
        //        if (System.Configuration.ConfigurationManager.AppSettings["UseIdentityServer"] == "true")
        //        {
        //            var identity = (System.Security.Claims.ClaimsIdentity)User.Identity;
        //            IEnumerable<System.Security.Claims.Claim> claims2 = identity.Claims;
        //            var UserIDXLoc = (from p in claims2 where p.Type == "UserIDX" select p.Value).FirstOrDefault();
        //            return UserIDXLoc.ConvertOrDefault<int>();
        //        }
        //        else
        //            return (int)System.Web.Security.Membership.GetUser().ProviderUserKey;
        //    }
        //    catch
        //    {
        //        //if fails, we don't care why, but need to return 0 to indicate not authenticated
        //        return 0;
        //    }
        //}



        public static void PostLoginUser(string UserID, IHttpContextAccessor httpcontextaccessor)
        {
            TOeUsers u = db_Accounts.GetT_OE_USERSByID(UserID);

            if (u != null)
            {
                //if user only belongs to 1 org, update the default org id
                if (u.DefaultOrgId == null)
                {
                    List <TWqxOrganization> os = db_WQX.GetWQX_USER_ORGS_ByUserIDX(u.UserIdx, false);
                    if (os.Count == 1)
                    {
                        db_Accounts.UpdateT_OE_USERSDefaultOrg(u.UserIdx, os[0].OrgId);
                        httpcontextaccessor.HttpContext.Session.SetString("OrgID", os[0].OrgId);
                        //HttpContext.Current.Session["OrgID"] = os[0].OrgId; //added 1/6/2014
                    }
                }

                if (u.InitalPwdFlag == false)
                {
                    db_Accounts.UpdateT_OE_USERS(u.UserIdx, null, null, null, null, null, null, null, null, System.DateTime.Now, null, null, "system");

                    //set important session variables
                    httpcontextaccessor.HttpContext.Session.SetInt32("UserIDX", u.UserIdx);
                    //HttpContext.Current.Session["UserIDX"] = u.USER_IDX;
                    httpcontextaccessor.HttpContext.Session.SetString("UserIDX", u.DefaultOrgId);
                    //HttpContext.Current.Session["OrgID"] = u.DEFAULT_ORG_ID; //added 1/6/2014
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_HUC_EIGHT", "false");
                    //HttpContext.Current.Session["MLOC_HUC_EIGHT"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_HUC_TWELVE", "false");
                    //HttpContext.Current.Session["MLOC_HUC_TWELVE"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_TRIBAL_LAND", "false");
                    //HttpContext.Current.Session["MLOC_TRIBAL_LAND"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_SOURCE_MAP_SCALE", "false");
                    //HttpContext.Current.Session["MLOC_SOURCE_MAP_SCALE"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_HORIZ_COLL_METHOD", "true");
                    //HttpContext.Current.Session["MLOC_HORIZ_COLL_METHOD"] = true;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_HORIZ_REF_DATUM", "true");
                    //HttpContext.Current.Session["MLOC_HORIZ_REF_DATUM"] = true;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_VERT_MEASURE", "false");
                    //HttpContext.Current.Session["MLOC_VERT_MEASURE"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_COUNTRY_CODE", "true");
                    //HttpContext.Current.Session["MLOC_COUNTRY_CODE"] = true;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_STATE_CODE", "true");
                    //HttpContext.Current.Session["MLOC_STATE_CODE"] = true;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_COUNTY_CODE", "true");
                    //HttpContext.Current.Session["MLOC_COUNTY_CODE"] = true;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_WELL_DATA", "false");
                    //HttpContext.Current.Session["MLOC_WELL_DATA"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_WELL_TYPE", "false");
                    //HttpContext.Current.Session["MLOC_WELL_TYPE"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_AQUIFER_NAME", "false");
                    //HttpContext.Current.Session["MLOC_AQUIFER_NAME"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_FORMATION_TYPE", "false");
                    //HttpContext.Current.Session["MLOC_FORMATION_TYPE"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("MLOC_WELLHOLE_DEPTH", "false");
                    //HttpContext.Current.Session["MLOC_WELLHOLE_DEPTH"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("PROJ_SAMP_DESIGN_TYPE_CD", "false");
                    //HttpContext.Current.Session["PROJ_SAMP_DESIGN_TYPE_CD"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("PROJ_QAPP_APPROVAL", "false");
                    //HttpContext.Current.Session["PROJ_QAPP_APPROVAL"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("SAMP_ACT_END_DT", "false");
                    //HttpContext.Current.Session["SAMP_ACT_END_DT"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("SAMP_COLL_METHOD", "false");
                    //HttpContext.Current.Session["SAMP_COLL_METHOD"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("SAMP_COLL_EQUIP", "false");
                    //HttpContext.Current.Session["SAMP_COLL_EQUIP"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("SAMP_PREP", "false");
                    //HttpContext.Current.Session["SAMP_PREP"] = false;
                    httpcontextaccessor.HttpContext.Session.SetString("SAMP_DEPTH", "false");
                    //HttpContext.Current.Session["SAMP_DEPTH"] = false;
                }
            }
        }
        public User CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            status = MembershipCreateStatus.Success;

            //******************************** BEGIN VALIDATION ********************************************************
            //Validate Username Length
            if (!Utils.ValidateParameter(ref username, true, true, true, 25))
            {
                status = MembershipCreateStatus.InvalidUserName;
                return(null);
            }

            //T_OE_USERS u = db_Accounts.GetT_OE_USERSByID(username);
            TOeUsers u = _unitOfWork.oeUsersRepostory.GetFirstOrDefault(x => x.UserId == username);

            if (u != null)
            {
                //Duplicate username found -return error
                status = MembershipCreateStatus.DuplicateUserName;
                return(null);
            }

            if (Utils.IsEmail(email) == false)
            {
                status = MembershipCreateStatus.InvalidEmail;
                return(null);
            }
            //******************************** END VALIDATION ***********************************************************


            try
            {
                //Generate password and hash it
                password = RandomString(10);
                string salt     = GenerateSalt();
                string hashpass = HashPassword(password, MembershipPasswordFormat.Hashed, salt);

                //create user record
                //int createUser = db_Accounts.CreateT_OE_USERS(username, hashpass, salt, "", "", email, true, true, null, null, null, "system");
                TOeUsers newUser = new TOeUsers
                {
                    UserId        = username,
                    PwdHash       = hashpass,
                    PwdSalt       = salt,
                    Email         = email,
                    ActInd        = true,
                    InitalPwdFlag = true,
                    CreateUserid  = "system"
                };
                _unitOfWork.oeUsersRepostory.Add(newUser);
                _unitOfWork.Save();
                int createUser = newUser.UserIdx;
                //Add user to PUBLIC Role
                //db_Accounts.CreateT_VCCB_USER_ROLE(3, createUser, "system");
                TOeUserRoles newUserRole = new TOeUserRoles
                {
                    UserIdx      = newUser.UserIdx,
                    RoleIdx      = 3,
                    CreateUserid = "system"
                };
                _unitOfWork.oeUserRolesRepository.Add(newUserRole);
                _unitOfWork.Save();
                //encrypt username for email
                string encryptOauth = new SimpleAES().Encrypt(password + "||" + username);
                encryptOauth = System.Web.HttpUtility.UrlEncode(encryptOauth);

                //send verification email to user
                string message = "Welcome to Open Waters. Open Waters allows you to manage your water quality data and synchronize it with EPA-WQX.  "
                                 + "\r\n\r\n Your username is: " + username
                                 + "\r\n\r\n You must activate your account by clicking the following link: "
                                 + "\r\n\r\n " + db_Ref.GetT_OE_APP_SETTING("Public App Path") + "Account/Verify.aspx?oauthcrd=" + encryptOauth
                                 + "\r\n\r\n After verifying your account you will be prompted to enter a permanent password.";


                bool EmailStatus = Utils.SendEmail(null, email.Split(';').ToList(), null, null, "Confirm Your Open Waters Account", message, null);
                if (EmailStatus == false)
                {
                    status = MembershipCreateStatus.InvalidEmail;
                    //db_Accounts.DeleteT_OE_USERS(createUser);
                    _unitOfWork.oeUserRolesRepository.Remove(newUserRole);
                    _unitOfWork.Save();
                }

                //if enabled, send email to admin notifying of account creation

                if (_unitOfWork.oeAppSettingsRepository.GetAppSetting("Notify Register") == "Y")
                {
                    //T_OE_USERS adm = db_Accounts.GetT_OE_USERSInRole(2).FirstOrDefault();
                    TOeUsers adm = _unitOfWork.oeUsersRepostory.GetUserByRole(2).FirstOrDefault();
                    if (adm != null)
                    {
                        Utils.SendEmail(null, adm.Email.Split(';').ToList(), null, null, "Notification: Open Waters Account", "An Open Waters account has just been created by " + username + " (" + email + ")", null);
                    }
                }

                //return new MembershipUser("CustMembershipProvider", username, createUser, email, passwordQuestion, null, isApproved, false, System.DateTime.Now, System.DateTime.Now, System.DateTime.Now, System.DateTime.Now, System.DateTime.Now);
                return(new User(newUser.Fname, newUser.Lname, username, password, ""));
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }