Tejasva-Maurya commited on
Commit
e7275a7
·
verified ·
1 Parent(s): 51acb88

Create mongo_db.py

Browse files
Files changed (1) hide show
  1. mongo_db.py +52 -0
mongo_db.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import bcrypt
2
+ from pymongo import MongoClient
3
+ import re
4
+
5
+ uri = f"mongodb+srv://{os.getenv('mongo_secret')}@void-uep.guig8vk.mongodb.net/?retryWrites=true&w=majority"
6
+ client = MongoClient(uri)
7
+ db = client["ImagiGen"]
8
+ users_collection = db["users"]
9
+
10
+
11
+ def hash_password(password: str) -> str:
12
+ # Generate a salt and hash the password
13
+ salt = bcrypt.gensalt()
14
+ hashed_password = bcrypt.hashpw(password.encode(), salt)
15
+ return hashed_password.decode()
16
+
17
+ def verify_password(entered_password: str, stored_hashed_password: str) -> bool:
18
+ # Check if the entered password matches the stored hashed password
19
+ return bcrypt.checkpw(entered_password.encode(), stored_hashed_password.encode())
20
+
21
+ def validate_email(email):
22
+ # Define a regex pattern for validating an email
23
+ email_pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
24
+ # Use re.match() to check if the email matches the pattern
25
+ if re.match(email_pattern, email):
26
+ return True
27
+ return False
28
+
29
+ def register(email_id, password):
30
+ if not validate_email(email_id):
31
+ return "Invalid Email Id"
32
+ # Check if username already exists
33
+ if users_collection.find_one({"email": email_id}):
34
+ return "Email ID already Registered"
35
+ # Insert new user into the collection
36
+ password = hash_password(password)
37
+ users_collection.insert_one({"email": email_id, "password": password})
38
+ return "Registration successful"
39
+
40
+
41
+ def login(email_id, password):
42
+ # Check if username and password match
43
+ user = users_collection.find_one({"email": email_id})
44
+ if user :
45
+ hash_password = user["password"]
46
+ verify = verify_password(entered_password= password, stored_hashed_password = hash_password)
47
+ if verify:
48
+ return "Login successful"
49
+ else :
50
+ return "Invalid credentials"
51
+ else:
52
+ return "Invalid credentials"