Ejemplo n.º 1
0
        protected void RegisterButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                // Hash and salt the password using Bcyrpt before it gets sent to the database
                var saltedPassword = BCryptHelper.HashPassword(password.Text, Global.Salt);

                using (OracleConnection objConn = new OracleConnection(Global.ConnectionString))
                {
                    // Declare the stored procedure to execute and send it the parameters it needs
                    OracleCommand objCmd = new OracleCommand("tickets_api.insertGuest", objConn)
                    {
                        BindByName = true, CommandType = CommandType.StoredProcedure
                    };

                    objCmd.Parameters.Add("p_FirstName", OracleDbType.Varchar2, first_name.Text, ParameterDirection.Input);
                    objCmd.Parameters.Add("p_LastName", OracleDbType.Varchar2, last_name.Text, ParameterDirection.Input);
                    objCmd.Parameters.Add("p_Email", OracleDbType.Varchar2, email.Text, ParameterDirection.Input);
                    objCmd.Parameters.Add("p_Password", OracleDbType.Varchar2, saltedPassword, ParameterDirection.Input);

                    try
                    {
                        objConn.Open();
                        objCmd.ExecuteNonQuery();
                    }
                    catch (Exception)
                    {
                        labelMessage.Text = "Could not register. Try again later.";
                    }

                    objConn.Close();
                }

                if (string.IsNullOrEmpty(labelMessage.Text))
                {
                    Response.Redirect("Login.aspx");
                }
            }
        }
Ejemplo n.º 2
0
        public IActionResult EditUser(int id, [FromBody] UserUpdateModel input)
        {
            try
            {
                var daoManager   = HttpContext.RequestServices.GetService <DaoManager>();
                var databaseUser = daoManager.UserDao.Find(id);

                if (databaseUser == null)
                {
                    return(BadRequest("User not found"));
                }

                if (!BCryptHelper.CheckPassword(input.Password, databaseUser.PasswordHash))
                {
                    var salt           = BCryptHelper.GenerateSalt();
                    var hashedPassword = BCryptHelper.HashPassword(input.Password, salt);
                    databaseUser.PasswordHash = hashedPassword;
                }

                // TODO: Define and add constraints for these properties
                databaseUser.Firstname   = input.Firstname;
                databaseUser.Lastname    = input.Lastname;
                databaseUser.MailAddress = input.MailAddress;

                if (!Regex.IsMatch(input.MailAddress, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"))
                {
                    return(BadRequest("Email address not valid"));
                }

                daoManager.UserDao.Save(databaseUser);

                return(Ok());
            }
            catch (MySqlException ex)
            {
                return(LogError(ex));
            }
        }
Ejemplo n.º 3
0
        /// <exception cref="GameServer.Logic.Validation.InvalidLogicDataException">
        /// Baca se ako su podaci nevalidni
        /// </exception>
        public static void RegisterUser(string username, string password)
        {
            UserValidator.ValidateUserData(username, password);
            string salt = BCryptHelper.GenerateSalt();
            User   user = new User
            {
                Username     = username,
                PasswordHash = BCryptHelper.HashPassword(password, salt)
            };

            try
            {
                userRepo.Add(user);
            }
            catch (MySqlException e)
            {
                if (e.IsDuplicateEntry())
                {
                    throw new InvalidLogicDataException(
                              "Već postoji korisnik sa datim korisničkim imenom");
                }
            }
        }
Ejemplo n.º 4
0
        public override int Add(Model.Employee entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            using (var dataContext = GetDataContext())
            {
                entity.Password = BCryptHelper.HashPassword(entity.Password, BCryptHelper.GenerateSalt(10));
                entity.Username = entity.Username.ToLower();

                if (dataContext.Persons.OfType <DB.Employee>().Any(emp => !emp.Removed && emp.Username == entity.Username))
                {
                    throw new UsernameTakenException();
                }

                var newRecord = dataContext.Persons.Add(Mapper.Map <DB.Employee>(entity));
                dataContext.SaveChanges();

                return(newRecord.Id);
            }
        }
Ejemplo n.º 5
0
        public IActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Invalid input!");
                return(View());
            }

            if (model.NewPassword != model.ConfirmNewPassword)
            {
                ModelState.AddModelError("", "New Password does not match to Confirm New Password");
                return(View());
            }

            var user = this._context.Users.FirstOrDefault(u => u.Id == model.UserId);

            if (user != null)
            {
                if (BCryptHelper.CheckPassword(model.OldPassword, user.Password) == false)
                {
                    ModelState.AddModelError("", "Incorrect old Password.");
                    return(View());
                }

                user.Password    = BCryptHelper.HashPassword(model.NewPassword, BCryptHelper.GenerateSalt(8));
                user.LoginStatus = Infrastructures.Domain.Enums.LoginStatus.Active;

                this._context.Users.Update(user);
                this._context.SaveChanges();



                return(RedirectPermanent("Notify"));
            }

            return(View());
        }
Ejemplo n.º 6
0
        public async Task <IdentityResponse> LoginAsync(string username, string password)
        {
            var user = await _context.Users
                       .FirstOrDefaultAsync(x => x.username == username);

            if (user == null)
            {
                return(new IdentityResponse
                {
                    errors = new[] { "username does not exist." }
                });
            }

            var userHasValidPassword = BCryptHelper.CheckPassword(password, user.password);

            if (!userHasValidPassword)
            {
                return(new IdentityResponse
                {
                    errors = new[] { "email or password combination is wrong." }
                });
            }
            return(GenerateAuthenticationResultForUser(user));
        }
Ejemplo n.º 7
0
        public void SignUp(ISignUpDto dto)
        {
            signUpDtoValidator.Check(dto);

            if (dao.HasEmail(dto.Email))
            {
                throw new EmailAlreadyExistsException();
            }

            dao.CreateUser(new User
            {
                FirstName = dto.FirstName,
                LastName  = dto.LastName,
                Email     = dto.Email,
                Password  = BCryptHelper.HashPassword(dto.Password, BCryptHelper.GenerateSalt()),
                CreatedAt = DateTime.Now,
                Phones    = dto.Phones.Select(p => new UserPhone
                {
                    AreaCode    = p.AreaCode,
                    CountryCode = p.CountryCode,
                    Number      = p.Number,
                }).ToList()
            });
        }
Ejemplo n.º 8
0
 public IHttpActionResult Register(AdministratorUser model)
 {
     try
     {
         if (!ModelState.IsValid)
         {
             return(BadRequest(ModelState));
         }
         int id = adminHandler.CheckEmailAvailability(model.Email);
         if (id == 0)
         {
             //administrator info
             var administrator = new AdministratorModel()
             {
                 Email          = model.Email,
                 FirstName      = model.FirstName,
                 LastName       = model.LastName,
                 PhoneNumber    = model.PhoneNumber,
                 EmployeeNumber = model.employeeNumber,
             };
             //password hash
             string mySalt         = BCryptHelper.GenerateSalt();
             string hashedPassword = BCryptHelper.HashPassword(model.Password, mySalt);
             adminHandler.Create(administrator, hashedPassword);
             return(Ok("Success"));
         }
         else
         {
             return(Ok("Email taken"));
         }
     }
     catch (Exception)
     {
         return(Ok("Something went wrong"));
     }
 }
Ejemplo n.º 9
0
        public ActionResult Login(Users users)
        {
            try
            {
                var exist = db.Users.Where(x => x.Email == users.Email).Where(z => z.Active == 1).ToList();

                if (exist != null)
                {
                    string salt           = exist.Select(x => x.Salt).First().ToString();
                    string hashedpassword = exist.Select(x => x.Password).First().ToString();
                    string UserPassword   = BCryptHelper.HashPassword(users.Password, salt);

                    if (UserPassword == hashedpassword)
                    {
                        Session.Add("loggedin", 1);
                        TempData["Message"] = "Login Success!";
                        TempData["Type"]    = "Success";

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        TempData["Message"] = "Login Failed! Wrong Username or Password.";
                        TempData["Type"]    = "Danger";
                        return(View());
                    }
                }
            }
            catch
            {
                TempData["Type"]    = "Danger";
                TempData["Message"] = "Your account is not activated yet! Check your inbox.";
                return(View());
            }
            return(View());
        }
Ejemplo n.º 10
0
 public ActionResult verifyReset(string Code, Users users)
 {
     try
     {
         Code = TempData["resetCode"].ToString();
         var    UserReset      = db.Users.Where(x => x.resetCode == Code).Single();
         string salt           = BCryptHelper.GenerateSalt(7);
         string hashedPassword = BCryptHelper.HashPassword(users.Password, salt);
         UserReset.Salt            = salt;
         UserReset.Password        = hashedPassword;
         UserReset.resetCode       = null;
         db.Entry(UserReset).State = EntityState.Modified;
         db.SaveChanges();
         TempData["Type"]    = "Success";
         TempData["Message"] = "Your password was successfully changed! Please login with your new password.";
         return(RedirectToAction("login"));
     }
     catch
     {
         TempData["Type"]    = "Danger";
         TempData["Message"] = "An error ocurred! Please try to enter your new password again!";
         return(View());
     }
 }
Ejemplo n.º 11
0
 public static bool PasswordDecrypt(string Password, string HashedPassword)
 => BCryptHelper.CheckPassword(Password, HashedPassword);
Ejemplo n.º 12
0
 public static string PasswordEncrypt(this string Password)
 => BCryptHelper.HashPassword(Password, BCryptHelper.GenerateSalt());
Ejemplo n.º 13
0
 public bool CheckPassword(string plainText, string hashed, string salt)
 {
     //Easy-peasy
     return(BCryptHelper.CheckPassword(plainText, hashed));
 }
 public string GenerateSaltForHash([NotNull] int length = 8)
 {
     return(BCryptHelper.GenerateSalt(length));
 }
Ejemplo n.º 15
0
 public static bool ValidateHash(string srcString, string hash)
 {
     return(BCryptHelper.CheckPassword(srcString, hash));
 }
Ejemplo n.º 16
0
 public static bool ChecarSenha(string senha, string hash)
 {
     return(BCryptHelper.CheckPassword(senha, hash));
 }
Ejemplo n.º 17
0
 /// <summary>
 /// returns the given password in blowfish encryption
 /// </summary>
 /// <param name="password">plaintext password</param>
 /// <returns></returns>
 public static string EncryptPassword(string password)
 {
     return(BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt()));
 }
Ejemplo n.º 18
0
 public string GenerateRandomToken()
 {
     _logger.LogInformation("AuthenticationService.GenerateRandomToken - Service starts.");
     return(BCryptHelper.GenerateSalt(18, SaltRevision.Revision2A));
 }
Ejemplo n.º 19
0
 public static bool VerifyPassword(string candidatePassword, string hashedPassword)
 {
     return(BCryptHelper.CheckPassword(candidatePassword, hashedPassword));
 }
 public static string CreateHash(string password)
 {
     return(BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt(5)));
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Returns a hash generated of the passed keyword based on the
        /// Blowfish algorithm using a randomly generated salt with
        /// the set ammount of rounds.
        /// </summary>
        /// <param name="password">Clear text password string</param>
        /// <returns>Hash containing salt</returns>
        public static string CreatePasswordHash(string password)
        {
            var salt = BCryptHelper.GenerateSalt(Rounds);

            return(BCryptHelper.HashPassword(password, salt));
        }
        /// <summary>
        /// Matching the Password
        /// </summary>
        /// <param name="plainTextPassword"></param>
        /// <param name="hashedPassword"></param>
        /// <returns></returns>
        public bool CheckPassword(string plainTextPassword, string hashedPassword)
        {
            bool check = BCryptHelper.CheckPassword(plainTextPassword, hashedPassword);

            return(check);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Implements <see cref="IPasswordHashing.VerifyPassword(string, string)"/>
        /// </summary>
        public bool VerifyPassword(string actualPassword, string hashedPassword)
        {
            var isValid = BCryptHelper.CheckPassword(actualPassword, hashedPassword);

            return(isValid);
        }
Ejemplo n.º 24
0
 public static string GenerarSalt()
 {
     return(BCryptHelper.GenerateSalt());
 }
Ejemplo n.º 25
0
 private static string PasswordEncrypt(string password)
 {
     return(BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt()));
 }
Ejemplo n.º 26
0
 public static string GenerarHash(string contrasena, string salt)
 {
     return(BCryptHelper.HashPassword(contrasena, salt));
 }
Ejemplo n.º 27
0
 public static string RetornarHash(string senha)
 {
     return(BCryptHelper.HashPassword(senha, BCryptHelper.GenerateSalt((int)Configuracoes.Recuperar("SIAC_LOG_ROUNDS", 10))));
 }
Ejemplo n.º 28
0
 public static bool ValidarHash(string contrasena, string hashed)
 {
     return(BCryptHelper.CheckPassword(contrasena, hashed));
 }
Ejemplo n.º 29
0
 public static string Hash(string srcString)
 {
     return(BCryptHelper.HashPassword(srcString, BCryptHelper.GenerateSalt()));
 }
Ejemplo n.º 30
0
        public void HashPass()
        {
            var salt = BCryptHelper.GenerateSalt(13);

            Password = BCryptHelper.HashPassword(Password, salt);
        }