1

I'm trying to use the bcryptjs library to hash passwords in my project, but when I add the functions necessary for the hashing process, I face some errors. I'm following the instructions in this link : bcryptjs instructions.

The idea is, when I call the SubmitClick function I have to hash the password provided, and then, using a fetch, add this to my database. Here is the code for my CreateUser.js page:

import React, { Component } from 'react';
import bcrypt from 'bcryptjs';

class CreateUser extends Component {

  constructor(props){
    super(props);
    this.state={
      id:'',
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:''
    }
  }

  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {

      bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(this.state.password, salt, function(err, hash) {
              console.log(hash); 
          });
      });

      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          //'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      })
      .then(response => response.json())
      .then(parsedJSON => this.setState({id : parsedJSON._id}, function(){
        this.props.history.push({
          pathname : '/get',
          state : { id : this.state.id }
        });
      }))
      .catch(error => alert('Check your data! Some of the values passed aren`t valid'))
    }
  }

  changeID(parsedJSON){
    this.setState({id : parsedJSON._id})
  }

  changeEmail(event){
    this.setState({email : event.target.value})
  }

  changeFname(event){
    this.setState({first_name : event.target.value})
  }

  changeLname(event){
    this.setState({last_name : event.target.value})
  }

  changePhone(event){
    this.setState({personal_phone : event.target.value})
  }

  changePassword(event){
    this.setState({password : event.target.value})
  }

  changeReTPassword(event){
    this.setState({reTypepassword : event.target.value})
  }

  render() {
    return (
      <div id="layout">
        <div id="main">
          <div className="App-header">
              <label htmlFor="title">Create User</label> 
          </div>
          <div className="content" id="content">
            <div className="infos">
              <input id="email" type="text" name="email" placeholder="Email" 
              onChange = {(event)=> this.changeEmail(event)}/>
            </div>
            <div className="infos">
              <input id="f_name" type="text" name="F_name" placeholder="First Name" 
              onChange = {(event)=> this.changeFname(event)}/>
            </div>
            <div className="infos">
              <input id="l_name" type="text" name="L_name" placeholder="Last Name" 
              onChange = {(event)=> this.changeLname(event)}/>
            </div>
            <div className="infos">
              <input id="phone" type="text" name="L_name" placeholder="Personal Phone" 
              onChange = {(event)=> this.changePhone(event)}/>
            </div>
            <div className="infos">
              <input id="senha" type="password" name="senha" placeholder="Password" 
              onChange = {(event)=> this.changePassword(event)}/>
            </div>
            <div className="infos">
              <input id="senha" type="password" name="senha" placeholder="Re-type password" 
              onChange = {(event)=> this.changeReTPassword(event)}/>
            </div>
            <div className="buttons">                                  
              <button type="submit" onClick={(event) => this.SubmitClick()} className="buttonsUser">Submit</button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default CreateUser;

If I remove the following part of the code, the code works perfectly, without hashing:

  bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(this.props.password, salt, function(err, hash) {
          console.log(hash); 
      });
  });

But with that part, I'm facing this error:

> CreateUser.js:26 Uncaught TypeError: Cannot read property 'state' of undefined
    at CreateUser.js:26
    at bcrypt.js:155
    at run (setImmediate.js:40)
    at runIfPresent (setImmediate.js:69)
    at onGlobalMessage (setImmediate.js:109)

I've search throughout the StackOverflow questions and found some questions similar to mine, and I have tried to use the solutions proposed in each one, but nothing changed. Here are the questions links for reference: Question1 Question2 Question3 Question4

I tried to bind my functions in the class constructor, as showed bellow, but got the same error.

  constructor(props){
    super(props);
    this.SubmitClick = this.SubmitClick.bind(this);
    this.state={
      id:'',
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:''
    }
  }

I tried to bind my functions inline, in this case nothing really happened when I clicked the button, which is weird.

    <div className="buttons">                                  
      <button type="submit" onClick={(event) => this.SubmitClick.bind(this)} className="buttonsUser">Submit</button>
    </div>

I have no clue what is going wrong with my code, any suggestions ?

rk_Tinelli
  • 79
  • 2
  • 3
  • 10

2 Answers2

2

You are loosing the context in callback method passed to genSalt:

bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash); 
    });
});

Solution:

One way is use arrow function here also:

bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(this.state.password, salt, (err, hash) => {
          console.log(hash); 
    });
});

Or use .bind(this):

bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash); 
    });
}.bind(this));

Or use extra variable, and use that variable in place of this:

SubmitClick(){
    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    }else {

        let that = this;    //here

        bcrypt.genSalt(10, function(err, salt) {
            bcrypt.hash(that.state.password, salt, function(err, hash) {
                console.log(hash); 
            });
        });
    }
    .....
}
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
1

You need to bind the callback or this will not be set:

  bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash); 
      });
  }.bind(this));

Or use an arrow function:

  bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash); 
      });
  });
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132