I am having an issue when verifying a password in my mongodb.
from what i saw in other posts, it appears that I am using different salts to hash the password. but I am not sure how to fix it.
this is the sign up and log in controller::
import bcrypt
from flask import Blueprint, request, jsonify
from models.user import User
from services.cors_handler import CorsHandlerUtil
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from flask_bcrypt import check_password_hash
user_bp = Blueprint("user_routes", __name__, url_prefix="/api/user")
@user_bp.route("signup", methods=["POST","OPTIONS"])
def signup_controller():
print('signup_controller')
data = request.get_json()
if not data:
print('NO DATA')
return jsonify({'message': 'Invalid request'}), 400
if data.get('name') is None or data.get('email') is None or data.get('password') is None:
print('MISSING PARAMS')
return jsonify({"error": "Missing params"}), 400
name = data.get('name')
email = data.get('email')
password = data.get('password')
print(f'password being send in on signup:: {password}')
# Check if the email already exists
if User.objects(email=email).first():
print('USER EXISTS ALREADY')
return jsonify({"error": "Email already exists"}), 400
# Create a new user document
user = User(email=email, password=password, name=name)
print('Hashed Password:', user.password) # Add this line
try:
print('USER SAVED')
user.save()
access_token = create_access_token(identity=str(user.id))
return jsonify({"message":"User created", "token": access_token}), 200
except ValueError as e:
print(f'errro1: {str(e)}')
return jsonify({"error": str(e)}), 400
except Exception as e:
print(f'errro2: {str(e)}')
return jsonify({"error": "Internal server error"}), 500
@user_bp.route("/login", methods=["POST", "OPTIONS"])
def login_controller():
data = request.get_json()
if not data:
return jsonify({'error': 'Invalid request'}), 400
if data.get('email') is None or data.get('password') is None:
return jsonify({"error": "Missing params"}), 400
email = data.get('email')
password = data.get('password')
print('Password being send on login:', password) # Add this line
# Check if the user with the provided email exists
user = User.objects(email=email).first()
if not user:
print('USER NOT FOUND')
return jsonify({"error": "User not found"}), 404
print('Hashed Password in Database:', user.password) # Add this line
# Compare the provided password with the hashed password in the database
if not user.check_password(password):
print('INVALID CREDENTIALS')
return jsonify({"error": "Invalid credentials"}), 401
# If the provided credentials are correct, create an access token
access_token = create_access_token(identity=str(user.id))
return jsonify({"message": "Login successful", "token": access_token}), 200
this is the user model from mongodb::
from flask_mongoengine import MongoEngine
from mongoengine.errors import NotUniqueError
from flask_bcrypt import Bcrypt
db = MongoEngine()
bcrypt = Bcrypt()
class User(db.Document):
email = db.StringField(required=True, unique=True)
password = db.StringField(required=True)
name = db.StringField(required=True)
def __init__(self, email, password, name, *args, **kwargs):
super(User, self).__init__(*args, **kwargs)
self.email = email
self.password = bcrypt.generate_password_hash(password).decode('utf-8')
self.name = name
def check_password(self, password):
return bcrypt.check_password_hash(self.password, password)
# return bcrypt.check_password_hash(db_password, password)
# return True
def save(self, *args, **kwargs):
try:
return super(User, self).save(*args, **kwargs)
except NotUniqueError:
raise ValueError("Email already exists")
I found a post in a different laguage that appears to be what my issue is::
BCrypt Verify stored password hash
but I am not sure how to fix it
when i try to login I see the following logs::
signup_route()
signup_controller
password being send in on signup:: password
Hashed Password: $2b$12$hwfW5kuncMBHE0Z1B94I5OILc43RkMyuuMJKSw8HIAHzWn1iAy1hu
USER SAVED
127.0.0.1 - - [24/Jul/2023 19:13:55] "POST /api/user/signup HTTP/1.1" 200 -
loginup_route()
Password being send on login: password
Hashed Password in Database: $2b$12$W/H5KNBE3FWuadKDbuVkke6zE1iHnYDAgrRKtMypaZn6YFIZDYihW
INVALID CREDENTIALS
127.0.0.1 - - [24/Jul/2023 19:14:09] "POST /api/user/login HTTP/1.1" 401 -