Spaces:
Sleeping
Sleeping
File size: 1,887 Bytes
e7275a7 cb1e87a e7275a7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
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" |