Spaces:
Sleeping
Sleeping
import bcrypt | |
from pymongo import MongoClient | |
import re | |
import os | |
uri = f"mongodb+srv://{os.getenv('mongo_secret')}@void-uep.guig8vk.mongodb.net/?retryWrites=true&w=majority" | |
client = MongoClient(uri) | |
db = client["ImagiGen"] | |
users_collection = db["users"] | |
def hash_password(password: str) -> str: | |
# Generate a salt and hash the password | |
salt = bcrypt.gensalt() | |
hashed_password = bcrypt.hashpw(password.encode(), salt) | |
return hashed_password.decode() | |
def verify_password(entered_password: str, stored_hashed_password: str) -> bool: | |
# Check if the entered password matches the stored hashed password | |
return bcrypt.checkpw(entered_password.encode(), stored_hashed_password.encode()) | |
def validate_email(email): | |
# Define a regex pattern for validating an email | |
email_pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' | |
# Use re.match() to check if the email matches the pattern | |
if re.match(email_pattern, email): | |
return True | |
return False | |
def register(email_id, password): | |
if not validate_email(email_id): | |
return "Invalid Email Id" | |
# Check if username already exists | |
if users_collection.find_one({"email": email_id}): | |
return "Email ID already Registered" | |
# Insert new user into the collection | |
password = hash_password(password) | |
users_collection.insert_one({"email": email_id, "password": password}) | |
return "Registration successful" | |
def login(email_id, password): | |
# Check if username and password match | |
user = users_collection.find_one({"email": email_id}) | |
if user : | |
hash_password = user["password"] | |
verify = verify_password(entered_password= password, stored_hashed_password = hash_password) | |
if verify: | |
return "Login successful" | |
else : | |
return "Invalid credentials" | |
else: | |
return "Invalid credentials" |