private User_Sec SetPassword(User user, string email, string pass = null, string subject = null)
        {
            string   passResult = string.IsNullOrEmpty(pass) ? Password.Generate(Password.minPasswordLength) : pass;
            User_Sec user_sec   = new User_Sec()
            {
                Id = user.Id, Pass = Password.ComputeHash(passResult)
            };

            ExecQuery((query) =>
            {
                query.ExecuteNonQuery(@"user\sec\[set]", new SqlParameter[] { new SqlParameter("@id", value: user_sec.Id), new SqlParameter("@pass", value: user_sec.Pass) });
            });

            //if (!string.IsNullOrEmpty(user.phone))
            //{
            //    string body = string.Concat("Ваш пароль для входа: ", user_sec.pass);
            //    var resultSMS = SMS.SendSMS("https://sms.ru/sms/send?api_id=112D81F5-A8AD-6687-4914-0DD89D0528A0&to=7", user.phone, body);
            //}

            if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(subject))
            {
                string body = string.Concat("Ваш пароль для входа: ", passResult);
                Core.Net.EMail.SendEMail(AppSettings.Smtp.Host, AppSettings.Smtp.Port, AppSettings.Smtp.EnableSsl, AppSettings.Mail.Address, AppSettings.Mail.Password, email, subject, body);
            }
            return(user_sec);
        }
Exemplo n.º 2
0
        public HttpMessage <UserWithRole> Login(LoginUser login)
        {
            return(TryCatchResponse(() =>
            {
                if (login == null || string.IsNullOrEmpty(login.Email) || string.IsNullOrEmpty(login.Pass))
                {
                    throw new Exception("Неверные параметры для входа.");
                }

                List <User> users = GetUsers(login.Email);

                if (users == null || users.Count == 0)
                {
                    throw new Exception("Пользователь не найден.");
                }

                User user = GetUserByPass(Password.ComputeHash(login.Pass), users);

                if (user == null || user.D != 0)
                {
                    throw new Exception("Пользователь не найден.");
                }

                UserWithRole result = new UserWithRole()
                {
                    Id = user.Id, Email = user.Email
                };
                result.Roles = GetUserRoles(user.Id);

                return CreateResponseOk(result);
            }));
        }
Exemplo n.º 3
0
        public ActionResult UpdatePassword(string password)
        {
            if (ValidationUtility.IsValidPassword(password))
            {
                var salt = Password.GenerateSalt();
                var hash = Password.ComputeHash(password, salt);

                Database.Instance.UpdatePassword(hash, salt);
            }

            return(RedirectToAction(nameof(Settings)));
        }
Exemplo n.º 4
0
        public ActionResult ChangePassword(PreferenceChangePasswordModel data)
        {
            SelectCustomerModel customerData = new SelectCustomerModel()
            {
                Email = data.email
            };
            CustomerResultModel customerResult = customerTable.SelectRecord(customerData);

            if (customerResult.CustomerUUID == null)
            {
                return(Json(new { result = "Fail", reason = "Invalid Customer" }));
            }

            bool verifyPassword = Password.VerifyHash(data.oldPassword, customerResult.Hash);

            if (!verifyPassword)
            {
                return(Json(new { result = "Fail", reason = "Invalid Password" }));
            }

            //Generate Password's Salt and Hash
            byte[] salt       = Password.ComputeSaltBytes();
            string hashString = Password.ComputeHash(data.newPassword, salt);
            string saltString = Convert.ToBase64String(salt);

            customerResult.Hash = hashString;
            customerResult.Salt = saltString;

            UpdateCustomerModel customerUpdate = new UpdateCustomerModel()
            {
                CustomerUUID = customerResult.CustomerUUID,
                Email        = customerResult.Email,
                FirstName    = customerResult.FirstName,
                LastName     = customerResult.LastName,
                Hash         = customerResult.Hash,
                Salt         = customerResult.Salt,
                Phone        = customerResult.Phone
            };

            NonQueryResultModel updateResult = customerTable.UpdateRecord(customerUpdate);

            if (updateResult.Success)
            {
                return(Json(new { result = "Success" }));
            }
            else
            {
                return(Json(new { result = "Fail", reason = "Password was not updated" }));
            }
        }
Exemplo n.º 5
0
        public HttpMessage <string> ChangePass(ProfileUser profile_user)
        {
            return(TryCatchResponse(() =>
            {
                if (profile_user == null || string.IsNullOrEmpty(profile_user.Email))
                {
                    throw new Exception("Неверные параметры для изменения пароля.");
                }

                List <User> users = GetUsers(profile_user.Email);

                if (users == null || users.Count == 0)
                {
                    throw new Exception("Пользователь не найден.");
                }

                User user = GetUserByPass(Password.ComputeHash(profile_user.Pass), users);
                if (user == null)
                {
                    throw new Exception("Неверно указан пароль.");
                }

                if (string.IsNullOrEmpty(profile_user.ChangePass))
                {
                    throw new Exception("Не указан новый пароль.");
                }

                switch (Password.Check(profile_user.ChangePass))
                {
                case 1: throw new Exception("Пароль слишком короткий.");

                case 2: throw new Exception("Не указан хотя бы один заглавный символ.");

                case 3: throw new Exception("Не указан хотя бы один прописной символ.");

                case 4: throw new Exception("Не указана хотя бы одна цифра.");

                default: break;
                }

                SetPassword(users[0], users[0].Email, profile_user.ChangePass, "Изменение пароля в Auto Parts Site");

                return CreateResponseOk("Ok");
            }));
        }
Exemplo n.º 6
0
        public async Task <HttpResponseMessage> UpdateActivities(Guid ID, string username, string password)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Username and password are required."));
            }

            string hashedPassword = Password.ComputeHash(password);
            Guid?  userID         = await DataContext.Users.Where(u => u.UserName == username && u.PasswordHash == hashedPassword && u.Active && !u.Deleted).Select(u => (Guid?)u.ID).FirstOrDefaultAsync();

            if (!userID.HasValue)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid credentials."));
            }

            string serviceUrl      = System.Web.Configuration.WebConfigurationManager.AppSettings["Activities.Url"];
            string serviceUser     = (System.Web.Configuration.WebConfigurationManager.AppSettings["Activities.Import.User"] ?? string.Empty).DecryptString();
            string servicePassword = (System.Web.Configuration.WebConfigurationManager.AppSettings["Activities.Import.Password"] ?? string.Empty).DecryptString();

            if (string.IsNullOrEmpty(serviceUrl) || string.IsNullOrEmpty(serviceUser) || string.IsNullOrEmpty(servicePassword))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "External service configuration is incomplete, make sure the service url and credentials have been configured correctly."));
            }

            var updater = new ProjectActivitiesUpdater(DataContext, serviceUrl, serviceUser, servicePassword);

            if (!await updater.CanUpdate(userID.Value, ID))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unable to determine project, confirm that the specified project ID is correct for an Active project and that the user has permission to Update Activities for the project."));
            }

            await updater.DoUpdate(ID);

            if (updater.StatusCode != HttpStatusCode.OK)
            {
                return(Request.CreateErrorResponse(updater.StatusCode, updater.StatusMessage));
            }

            //return ok for status if update was successful.
            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        public static bool TryToAuthenticate(string password)
        {
            var hash     = string.Empty;
            var settings = Database.Instance.GetSettings();

            try
            {
                hash = Password.ComputeHash(password, settings.PasswordSalt);
            }
            catch (Exception)
            {
                // Password validation failed
            }

            if (Password.AreEqual(settings.PasswordHash, hash))
            {
                HttpContext.Current.Session[AUTHENTICATED] = true;

                return(true);
            }

            return(false);
        }
Exemplo n.º 8
0
        public void PasswordHashingTest()
        {
            var passwordLength = Password.PASSWORD_HASH_SIZE * 2;
            var salt           = "73a7b6dc8d1d75a0352c3ba917266afa";
            var password       = "******";

            var hash1 = Password.ComputeHash(password, salt);
            var hash2 = Password.ComputeHash(password, salt);
            var hash3 = Password.ComputeHash(password, salt);
            var hash4 = Password.ComputeHash(password + "5", salt);

            Assert.IsTrue(hash1.Length == passwordLength);
            Assert.IsTrue(hash2.Length == passwordLength);
            Assert.IsTrue(hash3.Length == passwordLength);
            Assert.IsTrue(hash4.Length == passwordLength);

            Assert.IsTrue(Password.AreEqual(hash1, hash2));
            Assert.IsTrue(Password.AreEqual(hash1, hash3));
            Assert.IsTrue(Password.AreEqual(hash2, hash3));

            Assert.IsFalse(Password.AreEqual(hash1, hash4));
            Assert.IsFalse(Password.AreEqual(hash2, hash4));
            Assert.IsFalse(Password.AreEqual(hash3, hash4));
        }
Exemplo n.º 9
0
        public ActionResult Register(LoginRegisterModel id)
        {
            //Check if we already have a user registered with the same email address
            if (customerTable.SelectRecord(new SelectCustomerModel()
            {
                Email = id.email
            }).CustomerUUID != null)
            {
                return(Json(new { result = "Fail", reason = "Email address is already registered" }));
            }

            //Generate Password's Salt and Hash
            byte[] salt       = Password.ComputeSaltBytes();
            string hashString = Password.ComputeHash(id.password, salt);
            string saltString = Convert.ToBase64String(salt);

            //Insert into Customer table
            InsertCustomerModel newCustomer = new InsertCustomerModel()
            {
                FirstName = id.firstName,
                LastName  = id.lastName,
                Phone     = id.phone,
                Email     = id.email,
                Hash      = hashString,
                Salt      = saltString
            };
            CustomerResultModel customerResult = customerTable.InsertRecord(newCustomer);

            //If it didn't insert, then we won't get a UUID back
            if (customerResult.CustomerUUID == null)
            {
                return(Json(new { result = "Fail", reason = "Insert into the database was not successful" }));
            }

            //Insert customer's address into the address table
            InsertAddressModel customerAddress = new InsertAddressModel()
            {
                CustomerUUID = customerResult.CustomerUUID,

                BillingAddress  = id.address,
                BillingAddress2 = id.address2,
                BillingCity     = id.city,
                BillingState    = id.state,
                BillingZip      = Int32.Parse(id.postalCode),

                ShippingAddress  = id.address,
                ShippingAddress2 = id.address2,
                ShippingCity     = id.city,
                ShippingState    = id.state,
                ShippingZip      = Int32.Parse(id.postalCode)
            };

            NonQueryResultModel addressResult = addressTable.InsertRecord(customerAddress); //We have the option to 'do something' if the insert fails

            //Insert into Query table
            InsertQueryModel customerQuery = new InsertQueryModel()
            {
                CustomerUUID = customerResult.CustomerUUID,

                Category   = "",
                CategoryID = "",
                Frequency  = "",
                PriceLimit = ""
            };
            NonQueryResultModel queryResult = queryTable.InsertRecord(customerQuery); //If this fails, we have the option of doing something

            //Aaaand we're done.
            return(Json(new { result = "Success" }));
        }