title: User Login Flask and Bcrypt
body: <p>I'm trying to implement user login using flask, I have setup a MySQL database that registers users and stores hashed passwords. The issue arises when trying to authenticate user login. The error is "TypeError: Unicode-objects must be encoded before checking",even when I've done so.</p>
  
  <pre><code># user login
  @app.route('/login',methods=['GET','POST'])
  def login():
      if request.method == 'POST':
      # Get Fields Username &amp; Password
      # Client Side Login &amp; Validation handled by wtforms in register class
      username = request.form['username']
      usr_entered = request.form['password']
  
      cursor = cnx.cursor(dictionary=True,buffered=True)
  
  # Get User By Username
      cursor.execute("SELECT * FROM users WHERE username =%s", [username])
      if cursor is not None:
          # Get Stored Hased and Salted password - Need to change fetch one to only return the one username
          data =cursor.fetchone()
          password = data['password']
  # Compare Password with hashed password- Bcrypt
          if bcrypt.checkpw(usr_entered.encode('utf-8'),password):
          #if (usr_entered==password):
              app.logger.info('Password Matched')
              session['logged_in'] = True 
              session['username'] = username
  
              flash('You are now logged in','success')
              return redirect(url_for('dashboard'))
              # Close Connection
              cursor.close()
          else:
              error = 'Invlaid Username or Password'
              return render_template('login.html',error=error)
  
  else: 
      error = 'Username not found'
      return render_template('login.html', error=error)
  
  return render_template('login.html')
  </code></pre>