Spaces:
Running
Running
added jwt auth
Browse files- app.py +157 -77
- jwtcoding.py +25 -0
- password.py +36 -0
- requirements.txt +5 -1
- tokenManagement.py +136 -0
- utils.py +13 -7
app.py
CHANGED
@@ -1,14 +1,18 @@
|
|
1 |
from io import BytesIO
|
2 |
from dotenv import load_dotenv
|
3 |
import os
|
4 |
-
from utils import
|
5 |
-
from fastapi import FastAPI, File, UploadFile
|
|
|
|
|
6 |
from fastapi.responses import JSONResponse
|
7 |
import docx
|
8 |
import fitz
|
9 |
from scraper import scrapeCourse
|
10 |
import asyncio
|
11 |
from google import genai
|
|
|
|
|
12 |
from pydantic import BaseModel
|
13 |
load_dotenv()
|
14 |
|
@@ -22,28 +26,32 @@ app = FastAPI()
|
|
22 |
import re
|
23 |
|
24 |
class UserBody(BaseModel):
|
25 |
-
|
26 |
-
|
|
|
|
|
27 |
|
28 |
class AiAnalysis(BaseModel):
|
29 |
-
|
30 |
-
|
|
|
|
|
|
|
31 |
|
32 |
class UserCourse(BaseModel):
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
userId:str
|
42 |
|
43 |
|
44 |
class CourseRecommendation(BaseModel):
|
45 |
-
|
46 |
-
|
47 |
|
48 |
def extract_course_info(text: str) -> CourseRecommendation:
|
49 |
# Example regex patterns – adjust these as needed based on the response format.
|
@@ -56,12 +64,12 @@ def extract_course_info(text: str) -> CourseRecommendation:
|
|
56 |
coursename = course_match.group(1).strip() if course_match else "Unknown"
|
57 |
completiontime = time_match.group(0).strip() if time_match else "Unknown"
|
58 |
|
59 |
-
return CourseRecommendation(
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
-
@app.get("/get/course")
|
65 |
def get_course(query):
|
66 |
# Example search query
|
67 |
results = google_search(query, API_KEY, CX)
|
@@ -74,10 +82,10 @@ def get_course(query):
|
|
74 |
snippet = item.get('snippet')
|
75 |
content_structure={}
|
76 |
|
77 |
-
content_structure["
|
78 |
-
content_structure["
|
79 |
-
content_structure["
|
80 |
-
content_structure["
|
81 |
content.append(content_structure)
|
82 |
|
83 |
|
@@ -97,10 +105,10 @@ def get_course_func(query):
|
|
97 |
link = item.get('link')
|
98 |
snippet = item.get('snippet')
|
99 |
content_structure={}
|
100 |
-
content_structure["
|
101 |
-
content_structure["
|
102 |
-
content_structure["
|
103 |
-
content_structure["
|
104 |
content.append(content_structure)
|
105 |
|
106 |
|
@@ -112,42 +120,60 @@ def get_course_func(query):
|
|
112 |
|
113 |
|
114 |
|
115 |
-
@app.post("/upload")
|
116 |
-
async def upload_file(
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
print(f"File name: {file.filename}")
|
121 |
-
print(f"File content type: {file.content_type}")
|
122 |
-
print(f"File size: {file.size} bytes")
|
123 |
|
|
|
|
|
|
|
|
|
|
|
|
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
extracted_text = ""
|
128 |
-
for page_num in range(pdf_document.page_count):
|
129 |
-
page = pdf_document.load_page(page_num)
|
130 |
-
extracted_text += page.get_text()
|
131 |
-
|
132 |
-
elif "docx" == file.filename.split('.')[1]:
|
133 |
-
docx_file = BytesIO(content)
|
134 |
-
doc = docx.Document(docx_file)
|
135 |
-
extracted_text = ""
|
136 |
-
for para in doc.paragraphs:
|
137 |
-
extracted_text += para.text + "\n"
|
138 |
-
|
139 |
-
sentences = split_text_into_chunks(extracted_text,chunk_size=200)
|
140 |
-
docs = generate_embedding_for_user_resume(data=sentences,user_id=file.filename)
|
141 |
-
response= insert_embeddings_into_pinecone_database(doc=docs,api_key=PINECONE_API_KEY,name_space=user_id)
|
142 |
-
|
143 |
-
return {"filename": file.filename,"response":str(response) }
|
144 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
145 |
|
146 |
|
147 |
-
|
148 |
-
|
|
|
149 |
# Retrieve context from your vector database
|
150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
|
152 |
# Ensure that an event loop is present in this thread.
|
153 |
try:
|
@@ -170,8 +196,8 @@ def ask_ai_about_resume(req:AiAnalysis):
|
|
170 |
|
171 |
return {"Ai_Response":response.text}
|
172 |
|
173 |
-
@app.post("/recommend/courses")
|
174 |
-
def ask_ai_about_resume(request:UserCourse):
|
175 |
"""
|
176 |
User Profile Information for Career Development
|
177 |
|
@@ -203,13 +229,18 @@ Parameters:
|
|
203 |
timeframe_to_achieve_dream_role (str):
|
204 |
The ideal timeframe the user has in mind for achieving their dream role (e.g., "6-12 months").
|
205 |
|
206 |
-
user_id (str):
|
207 |
-
A unique identifier for the user; used to query personalized data from a vector database or other services.
|
208 |
|
209 |
"""
|
210 |
|
211 |
|
212 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
213 |
|
214 |
# Ensure that an event loop is present in this thread.
|
215 |
try:
|
@@ -229,35 +260,84 @@ Parameters:
|
|
229 |
- "completiontime": an estimate of how long it would take to complete the course.
|
230 |
Do not include any extra text.
|
231 |
Recommend a course using this information below :
|
232 |
-
Which of the following best describes you?: {request.
|
233 |
Would you like to prepare for an interim role to gain experience and income while pursuing your dream job?: {request.InterimRole}
|
234 |
-
What is your desired role?: {request.
|
235 |
-
Why do you want to achieve this desired role?: {request.
|
236 |
-
How do you prefer to learn new skills?: {request.
|
237 |
-
How many hours per day can you dedicate to learning?: {request.
|
238 |
-
What are the biggest challenges or obstacles you face in reaching your dream role?: {request.
|
239 |
-
What is your ideal timeframe for achieving your dream role?: {request.
|
240 |
|
241 |
|
242 |
"""
|
243 |
)
|
244 |
questions=request.model_dump()
|
|
|
245 |
create_questionaire(db_uri=MONGO_URI,db_name="crayonics",collection_name="questionaire",document=questions)
|
246 |
course_info = extract_course_info(response.text)
|
247 |
-
courses = get_course_func(query=course_info.
|
248 |
-
return {"
|
249 |
|
250 |
|
251 |
|
252 |
-
@app.post("/login")
|
253 |
def login(user:UserBody):
|
254 |
-
user ={"email":user.
|
255 |
user_id= login_user(db_uri=MONGO_URI,db_name="crayonics",collection_name="users",document=user)
|
256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
257 |
|
258 |
|
259 |
-
@app.post("/signup")
|
260 |
def signUp(user:UserBody):
|
261 |
-
user ={"email":user.
|
262 |
user_id= create_user(db_uri=MONGO_URI,db_name="crayonics",collection_name="users",document=user)
|
263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
from io import BytesIO
|
2 |
from dotenv import load_dotenv
|
3 |
import os
|
4 |
+
from utils import *
|
5 |
+
from fastapi import FastAPI, File, HTTPException, Header, UploadFile,status
|
6 |
+
from tokenManagement import *
|
7 |
+
from jwtcoding import *
|
8 |
from fastapi.responses import JSONResponse
|
9 |
import docx
|
10 |
import fitz
|
11 |
from scraper import scrapeCourse
|
12 |
import asyncio
|
13 |
from google import genai
|
14 |
+
from fastapi.security import OAuth2PasswordBearer
|
15 |
+
from typing import Optional
|
16 |
from pydantic import BaseModel
|
17 |
load_dotenv()
|
18 |
|
|
|
26 |
import re
|
27 |
|
28 |
class UserBody(BaseModel):
|
29 |
+
firstName: Optional[str] = None
|
30 |
+
lastName: Optional[str] = None
|
31 |
+
email:str
|
32 |
+
password:str
|
33 |
|
34 |
class AiAnalysis(BaseModel):
|
35 |
+
query:str
|
36 |
+
|
37 |
+
class Token(BaseModel):
|
38 |
+
refreshToken:str
|
39 |
+
|
40 |
|
41 |
class UserCourse(BaseModel):
|
42 |
+
employmentStatus:str
|
43 |
+
interimRole:str
|
44 |
+
desiredRole:str
|
45 |
+
motivation:str
|
46 |
+
learningPreference:str
|
47 |
+
hoursSpentLearning:str
|
48 |
+
challenges:str
|
49 |
+
timeframeToAchieveDreamRole:str
|
|
|
50 |
|
51 |
|
52 |
class CourseRecommendation(BaseModel):
|
53 |
+
courseName: str
|
54 |
+
completionTime: str
|
55 |
|
56 |
def extract_course_info(text: str) -> CourseRecommendation:
|
57 |
# Example regex patterns – adjust these as needed based on the response format.
|
|
|
64 |
coursename = course_match.group(1).strip() if course_match else "Unknown"
|
65 |
completiontime = time_match.group(0).strip() if time_match else "Unknown"
|
66 |
|
67 |
+
return CourseRecommendation(courseName=coursename, completionTime=completiontime)
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
+
@app.get("/get/course",tags=["Scrape"])
|
73 |
def get_course(query):
|
74 |
# Example search query
|
75 |
results = google_search(query, API_KEY, CX)
|
|
|
82 |
snippet = item.get('snippet')
|
83 |
content_structure={}
|
84 |
|
85 |
+
content_structure["courseTitle"]=title
|
86 |
+
content_structure["courseLink"]=link
|
87 |
+
content_structure["courseSnippet"]= snippet
|
88 |
+
content_structure["scrapedCourseDetails"]= scrapeCourse(url=link)
|
89 |
content.append(content_structure)
|
90 |
|
91 |
|
|
|
105 |
link = item.get('link')
|
106 |
snippet = item.get('snippet')
|
107 |
content_structure={}
|
108 |
+
content_structure["courseTitle"]=title
|
109 |
+
content_structure["courseLink"]=link
|
110 |
+
content_structure["courseSnippet"]= snippet
|
111 |
+
content_structure["scrapedCourseDetails"]= scrapeCourse(url=link)
|
112 |
content.append(content_structure)
|
113 |
|
114 |
|
|
|
120 |
|
121 |
|
122 |
|
123 |
+
@app.post("/upload",tags=["AI"])
|
124 |
+
async def upload_file(file: UploadFile = File(...),authorization: str = Header(...)):
|
125 |
+
# Extract the token from the Authorization header (Bearer token)
|
126 |
+
token = authorization.split("Bearer ")[-1]
|
|
|
|
|
|
|
|
|
127 |
|
128 |
+
# Here, you would validate the token (e.g., check with a JWT library)
|
129 |
+
decoded_user_id,decoded_access_token = decode_jwt(token)
|
130 |
+
is_valid = verify_access_token(db_uri=MONGO_URI, user_id=decoded_user_id, access_token=decoded_access_token)
|
131 |
+
if is_valid != True: # Example check
|
132 |
+
raise HTTPException(status_code=401, detail="Invalid token")
|
133 |
+
else:
|
134 |
|
135 |
+
content = await file.read() # Read the file content (this will return bytes)
|
136 |
+
sentences=[]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
|
138 |
+
print(f"File name: {file.filename}")
|
139 |
+
print(f"File content type: {file.content_type}")
|
140 |
+
print(f"File size: {file.size} bytes")
|
141 |
+
|
142 |
+
|
143 |
+
if "pdf" == file.filename.split('.')[1]:
|
144 |
+
pdf_document = fitz.open(stream=BytesIO(content), filetype="pdf")
|
145 |
+
extracted_text = ""
|
146 |
+
for page_num in range(pdf_document.page_count):
|
147 |
+
page = pdf_document.load_page(page_num)
|
148 |
+
extracted_text += page.get_text()
|
149 |
+
|
150 |
+
elif "docx" == file.filename.split('.')[1]:
|
151 |
+
docx_file = BytesIO(content)
|
152 |
+
doc = docx.Document(docx_file)
|
153 |
+
extracted_text = ""
|
154 |
+
for para in doc.paragraphs:
|
155 |
+
extracted_text += para.text + "\n"
|
156 |
+
|
157 |
+
sentences = split_text_into_chunks(extracted_text,chunk_size=200)
|
158 |
+
docs = generate_embedding_for_user_resume(data=sentences,user_id=file.filename)
|
159 |
+
response= insert_embeddings_into_pinecone_database(doc=docs,api_key=PINECONE_API_KEY,name_space=decoded_user_id)
|
160 |
+
|
161 |
+
return {" name": file.filename,"response":str(response) }
|
162 |
|
163 |
|
164 |
+
|
165 |
+
@app.post("/ask",tags=["AI"])
|
166 |
+
def ask_ai_about_resume(req:AiAnalysis,authorization: str = Header(...)):
|
167 |
# Retrieve context from your vector database
|
168 |
+
token = authorization.split("Bearer ")[-1]
|
169 |
+
|
170 |
+
# Here, you would validate the token (e.g., check with a JWT library)
|
171 |
+
decoded_user_id,decoded_access_token = decode_jwt(token)
|
172 |
+
is_valid = verify_access_token(db_uri=MONGO_URI, user_id=decoded_user_id, access_token=decoded_access_token)
|
173 |
+
if is_valid != True: # Example check
|
174 |
+
raise HTTPException(status_code=401, detail="Invalid token")
|
175 |
+
|
176 |
+
context = query_vector_database(query=req.Query, api_key=PINECONE_API_KEY, name_space=decoded_user_id)
|
177 |
|
178 |
# Ensure that an event loop is present in this thread.
|
179 |
try:
|
|
|
196 |
|
197 |
return {"Ai_Response":response.text}
|
198 |
|
199 |
+
@app.post("/recommend/courses",tags=["AI"])
|
200 |
+
def ask_ai_about_resume(request:UserCourse,authorization:str=Header(...)):
|
201 |
"""
|
202 |
User Profile Information for Career Development
|
203 |
|
|
|
229 |
timeframe_to_achieve_dream_role (str):
|
230 |
The ideal timeframe the user has in mind for achieving their dream role (e.g., "6-12 months").
|
231 |
|
|
|
|
|
232 |
|
233 |
"""
|
234 |
|
235 |
|
236 |
+
# Extract the token from the Authorization header (Bearer token)
|
237 |
+
token = authorization.split("Bearer ")[-1]
|
238 |
+
|
239 |
+
# Here, you would validate the token (e.g., check with a JWT library)
|
240 |
+
decoded_user_id,decoded_access_token = decode_jwt(token)
|
241 |
+
is_valid = verify_access_token(db_uri=MONGO_URI, user_id=decoded_user_id, access_token=decoded_access_token)
|
242 |
+
if is_valid != True: # Example check
|
243 |
+
raise HTTPException(status_code=401, detail="Invalid token")
|
244 |
|
245 |
# Ensure that an event loop is present in this thread.
|
246 |
try:
|
|
|
260 |
- "completiontime": an estimate of how long it would take to complete the course.
|
261 |
Do not include any extra text.
|
262 |
Recommend a course using this information below :
|
263 |
+
Which of the following best describes you?: {request.employmentStatus}
|
264 |
Would you like to prepare for an interim role to gain experience and income while pursuing your dream job?: {request.InterimRole}
|
265 |
+
What is your desired role?: {request.desiredRole}
|
266 |
+
Why do you want to achieve this desired role?: {request.motivation}
|
267 |
+
How do you prefer to learn new skills?: {request.learningPreference}
|
268 |
+
How many hours per day can you dedicate to learning?: {request.hoursSpentLearning}
|
269 |
+
What are the biggest challenges or obstacles you face in reaching your dream role?: {request.challenges}
|
270 |
+
What is your ideal timeframe for achieving your dream role?: {request.timeframeToAchieveDreamRole}
|
271 |
|
272 |
|
273 |
"""
|
274 |
)
|
275 |
questions=request.model_dump()
|
276 |
+
questions['userId']=decoded_user_id
|
277 |
create_questionaire(db_uri=MONGO_URI,db_name="crayonics",collection_name="questionaire",document=questions)
|
278 |
course_info = extract_course_info(response.text)
|
279 |
+
courses = get_course_func(query=course_info.courseName)
|
280 |
+
return {"courseInfo":course_info,"courses":courses}
|
281 |
|
282 |
|
283 |
|
284 |
+
@app.post("/login",tags=["Authentication"])
|
285 |
def login(user:UserBody):
|
286 |
+
user ={"email":user.email,"password":user.password,"firstName":user.firstName,"lastName":user.lastName}
|
287 |
user_id= login_user(db_uri=MONGO_URI,db_name="crayonics",collection_name="users",document=user)
|
288 |
+
|
289 |
+
if user_id != False:
|
290 |
+
refreshToken=create_refreshToken(db_uri=MONGO_URI,user_id=user_id)
|
291 |
+
accessToken = create_accessToken(db_uri=MONGO_URI,user_id=user_id,refresh_token=refreshToken)
|
292 |
+
result = update_refreshTokenWithPreviouslyUsedAccessToken(db_uri=MONGO_URI,refresh_token=refreshToken,access_token=accessToken)
|
293 |
+
print(result)
|
294 |
+
access_token = encode_jwt(user_id=user_id,access_token=accessToken)
|
295 |
+
return {"userId":user_id,"refreshToken":refreshToken,"accessToken":access_token}
|
296 |
+
return JSONResponse(status_code=401,content="Invalid login details")
|
297 |
|
298 |
|
299 |
+
@app.post("/signup",tags=["Authentication"])
|
300 |
def signUp(user:UserBody):
|
301 |
+
user ={"email":user.email,"password":user.password}
|
302 |
user_id= create_user(db_uri=MONGO_URI,db_name="crayonics",collection_name="users",document=user)
|
303 |
+
if user_id != False:
|
304 |
+
refreshToken=create_refreshToken(db_uri=MONGO_URI,user_id=user_id)
|
305 |
+
accessToken = create_accessToken(db_uri=MONGO_URI,user_id=user_id,refresh_token=refreshToken)
|
306 |
+
result = update_refreshTokenWithPreviouslyUsedAccessToken(db_uri=MONGO_URI,refresh_token=refreshToken,access_token=accessToken)
|
307 |
+
print(result)
|
308 |
+
access_token = encode_jwt(user_id=user_id,access_token=accessToken)
|
309 |
+
return {"userId":user_id,"refreshToken":refreshToken,"accessToken":access_token}
|
310 |
+
return JSONResponse(status_code=401,content="Invalid Sign Up details")
|
311 |
+
|
312 |
+
|
313 |
+
@app.post("/accessToken",tags=["Authentication"])
|
314 |
+
def refresh_access_token(refresh_token:Token, authorization: str = Header(...)):
|
315 |
+
|
316 |
+
token = authorization.split("Bearer ")[-1]
|
317 |
+
|
318 |
+
# Here, you would validate the token (e.g., check with a JWT library)
|
319 |
+
decoded_user_id,decoded_access_token = decode_jwt(token)
|
320 |
+
is_valid = verify_access_token(db_uri=MONGO_URI, user_id=decoded_user_id, access_token=decoded_access_token)
|
321 |
+
print(decoded_user_id,decoded_access_token)
|
322 |
+
if is_valid != True: # Example check
|
323 |
+
raise HTTPException(status_code=401, detail="Invalid token")
|
324 |
+
new_access_token = create_accessToken(db_uri=MONGO_URI,user_id=decoded_user_id,refresh_token=refresh_token.refreshToken)
|
325 |
+
newly_encoded_access_token = encode_jwt(user_id=decoded_user_id,access_token=new_access_token)
|
326 |
+
return {"accessToken":newly_encoded_access_token}
|
327 |
+
|
328 |
+
|
329 |
+
|
330 |
+
|
331 |
+
@app.get("/protected-route")
|
332 |
+
def protected_route(authorization: str = Header(...)):
|
333 |
+
# Extract the token from the Authorization header (Bearer token)
|
334 |
+
token = authorization.split("Bearer ")[-1]
|
335 |
+
|
336 |
+
# Here, you would validate the token (e.g., check with a JWT library)
|
337 |
+
decoded_user_id,decoded_access_token = decode_jwt(token)
|
338 |
+
is_valid = verify_access_token(db_uri=MONGO_URI, user_id=decoded_user_id, access_token=decoded_access_token)
|
339 |
+
print(decoded_user_id,decoded_access_token)
|
340 |
+
if is_valid != True: # Example check
|
341 |
+
raise HTTPException(status_code=401, detail="Invalid token")
|
342 |
+
|
343 |
+
return {"message": "Access granted", "verification": "verified"}
|
jwtcoding.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from jose import jwt
|
2 |
+
import os
|
3 |
+
from dotenv import load_dotenv
|
4 |
+
from datetime import datetime, timedelta
|
5 |
+
load_dotenv()
|
6 |
+
SECRET_KEY = os.getenv("SECRET_KEY")
|
7 |
+
ALGORITHM = os.getenv("ALGORITHM")
|
8 |
+
|
9 |
+
def encode_jwt(user_id: str, access_token: str, expires_delta: timedelta = timedelta(minutes=130)) -> str:
|
10 |
+
"""Encode user_id and access_token into a JWT."""
|
11 |
+
payload = {
|
12 |
+
"user_id": user_id,
|
13 |
+
"access_token": access_token,
|
14 |
+
"exp": datetime.now() + expires_delta # Expiration time
|
15 |
+
}
|
16 |
+
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
17 |
+
|
18 |
+
def decode_jwt(encoded: str) -> tuple[str, str]:
|
19 |
+
"""Decode the JWT back into user_id and access_token."""
|
20 |
+
try:
|
21 |
+
payload = jwt.decode(encoded, SECRET_KEY, algorithms=[ALGORITHM])
|
22 |
+
return payload["user_id"], payload["access_token"]
|
23 |
+
except jwt.JWTError as e:
|
24 |
+
raise ValueError(f"Invalid or expired token: {str(e)}")
|
25 |
+
|
password.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import bcrypt
|
2 |
+
|
3 |
+
def hash_password(password):
|
4 |
+
"""
|
5 |
+
Hash a password using bcrypt.
|
6 |
+
|
7 |
+
Args:
|
8 |
+
password (str): The plain text password to hash
|
9 |
+
|
10 |
+
Returns:
|
11 |
+
bytes: The hashed password
|
12 |
+
"""
|
13 |
+
# Convert string to bytes and generate a salt
|
14 |
+
salt = bcrypt.gensalt()
|
15 |
+
# Hash the password with the salt
|
16 |
+
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
|
17 |
+
return hashed
|
18 |
+
|
19 |
+
def check_password(password, hashed_password):
|
20 |
+
"""
|
21 |
+
Check if a provided password matches the hashed password.
|
22 |
+
|
23 |
+
Args:
|
24 |
+
password (str): The plain text password to check
|
25 |
+
hashed_password (bytes): The previously hashed password
|
26 |
+
|
27 |
+
Returns:
|
28 |
+
bool: True if password matches, False otherwise
|
29 |
+
"""
|
30 |
+
try:
|
31 |
+
# Check if the password matches the hash
|
32 |
+
return bcrypt.checkpw(password.encode('utf-8'), hashed_password)
|
33 |
+
except Exception:
|
34 |
+
# Return False if there's any error (e.g., invalid hash)
|
35 |
+
return False
|
36 |
+
|
requirements.txt
CHANGED
@@ -8,4 +8,8 @@ einops
|
|
8 |
google-genai
|
9 |
python-docx
|
10 |
beautifulsoup4
|
11 |
-
pymongo
|
|
|
|
|
|
|
|
|
|
8 |
google-genai
|
9 |
python-docx
|
10 |
beautifulsoup4
|
11 |
+
pymongo
|
12 |
+
bcrypt
|
13 |
+
python-jose[cryptography]
|
14 |
+
passlib[bcrypt]
|
15 |
+
uvicorn
|
tokenManagement.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
import datetime
|
4 |
+
from bson import ObjectId
|
5 |
+
|
6 |
+
|
7 |
+
def is_current_date_greater_than_previous(previous_date):
|
8 |
+
# Get the current date and time
|
9 |
+
current_date =datetime.datetime.now()
|
10 |
+
|
11 |
+
# Convert the previous date (which is a string) to a datetime object
|
12 |
+
|
13 |
+
|
14 |
+
# Compare the two dates
|
15 |
+
if current_date > previous_date:
|
16 |
+
return True
|
17 |
+
else:
|
18 |
+
return False
|
19 |
+
|
20 |
+
|
21 |
+
|
22 |
+
def create_accessToken(db_uri: str, user_id: str, refresh_token: str) -> str:
|
23 |
+
from pymongo import MongoClient
|
24 |
+
current_time = datetime.datetime.now()
|
25 |
+
expire_at = current_time + datetime.timedelta(minutes=130)
|
26 |
+
"""
|
27 |
+
Inserts a new document into the specified MongoDB collection.
|
28 |
+
|
29 |
+
Parameters:
|
30 |
+
db_uri (str): MongoDB connection URI.
|
31 |
+
db_name (str): Name of the database.
|
32 |
+
collection_name (str): Name of the collection.
|
33 |
+
document (dict): The document to insert.
|
34 |
+
|
35 |
+
Returns:
|
36 |
+
str: The ID of the inserted document.
|
37 |
+
"""
|
38 |
+
# Connect to MongoDB
|
39 |
+
client = MongoClient(db_uri)
|
40 |
+
db = client["crayonics"]
|
41 |
+
collection = db["AccessToken"]
|
42 |
+
collection.find_one_and_delete({"refresh_token":refresh_token})
|
43 |
+
# Insert the document
|
44 |
+
result = collection.insert_one({"user_id":user_id,"refresh_token":refresh_token,"current_time":current_time,"expire_at":expire_at})
|
45 |
+
client.close()
|
46 |
+
return str(result.inserted_id)
|
47 |
+
|
48 |
+
|
49 |
+
# Close the connection
|
50 |
+
|
51 |
+
|
52 |
+
|
53 |
+
def create_refreshToken(db_uri: str, user_id: str) -> str:
|
54 |
+
from pymongo import MongoClient
|
55 |
+
current_time = datetime.datetime.now()
|
56 |
+
expire_at = current_time + datetime.timedelta(days=30)
|
57 |
+
|
58 |
+
"""
|
59 |
+
Inserts a new document into the specified MongoDB collection.
|
60 |
+
|
61 |
+
Parameters:
|
62 |
+
db_uri (str): MongoDB connection URI.
|
63 |
+
user_id (str): id of user .
|
64 |
+
|
65 |
+
|
66 |
+
Returns:
|
67 |
+
str: The ID of the inserted document.
|
68 |
+
"""
|
69 |
+
|
70 |
+
# Connect to MongoDB
|
71 |
+
client = MongoClient(db_uri)
|
72 |
+
db = client["crayonics"]
|
73 |
+
collection = db["RefreshToken"]
|
74 |
+
# Insert the document
|
75 |
+
result = collection.insert_one({"user_id":user_id,"current_time":current_time,"expire_at":expire_at,"previous_access_token":"None"})
|
76 |
+
client.close()
|
77 |
+
return str(result.inserted_id)
|
78 |
+
|
79 |
+
# Close the connection
|
80 |
+
|
81 |
+
|
82 |
+
|
83 |
+
|
84 |
+
def update_refreshTokenWithPreviouslyUsedAccessToken(db_uri: str, refresh_token: str,access_token:str) -> bool:
|
85 |
+
from pymongo import MongoClient
|
86 |
+
|
87 |
+
"""
|
88 |
+
|
89 |
+
"""
|
90 |
+
# Connect to MongoDB
|
91 |
+
client = MongoClient(db_uri)
|
92 |
+
db = client["crayonics"]
|
93 |
+
collection = db["RefreshToken"]
|
94 |
+
|
95 |
+
# Insert the document
|
96 |
+
try:
|
97 |
+
collection.update_one(
|
98 |
+
{"_id":ObjectId(oid=refresh_token) }, # Filter (find the document by user_id)
|
99 |
+
{"$set": {"previous_access_token": access_token}} # Add or update the field
|
100 |
+
)
|
101 |
+
client.close()
|
102 |
+
return True
|
103 |
+
except:
|
104 |
+
return False
|
105 |
+
|
106 |
+
|
107 |
+
|
108 |
+
def verify_access_token(db_uri: str, user_id: str, access_token: str) -> bool:
|
109 |
+
from pymongo import MongoClient
|
110 |
+
current_time = datetime.datetime.now()
|
111 |
+
expire_at = current_time + datetime.timedelta(minutes=15)
|
112 |
+
"""
|
113 |
+
|
114 |
+
"""
|
115 |
+
# Connect to MongoDB
|
116 |
+
client = MongoClient(db_uri)
|
117 |
+
db = client["crayonics"]
|
118 |
+
collection = db["AccessToken"]
|
119 |
+
doc = collection.find_one({"user_id":user_id})
|
120 |
+
|
121 |
+
|
122 |
+
if doc==None:
|
123 |
+
return False
|
124 |
+
else:
|
125 |
+
if str(doc['_id']) == access_token:
|
126 |
+
if is_current_date_greater_than_previous(doc['expire_at']):
|
127 |
+
return False
|
128 |
+
else:
|
129 |
+
return True
|
130 |
+
else:
|
131 |
+
print("doc exists",str(doc['_id']),access_token,str(doc['_id']) == access_token )
|
132 |
+
return False
|
133 |
+
|
134 |
+
|
135 |
+
|
136 |
+
|
utils.py
CHANGED
@@ -1,5 +1,6 @@
|
|
1 |
import requests
|
2 |
from pymongo import MongoClient
|
|
|
3 |
|
4 |
def google_search(query, api_key, cx):
|
5 |
url = f"https://www.googleapis.com/customsearch/v1?q={query}&key={api_key}&cx={cx}"
|
@@ -78,7 +79,7 @@ def query_vector_database(query,api_key,name_space):
|
|
78 |
response = index.query(
|
79 |
namespace=name_space,
|
80 |
vector=query_embedding.tolist(),
|
81 |
-
top_k=
|
82 |
include_metadata=True
|
83 |
)
|
84 |
|
@@ -131,14 +132,16 @@ def create_user(db_uri: str, db_name: str, collection_name: str, document: dict)
|
|
131 |
collection = db[collection_name]
|
132 |
|
133 |
# Insert the document
|
134 |
-
s = collection.find_one(document)
|
|
|
|
|
135 |
if s==None:
|
136 |
result = collection.insert_one(document)
|
137 |
client.close()
|
138 |
return str(result.inserted_id)
|
139 |
else:
|
140 |
client.close()
|
141 |
-
return
|
142 |
|
143 |
# Close the connection
|
144 |
|
@@ -193,15 +196,18 @@ def login_user(db_uri: str, db_name: str, collection_name: str, document: dict)
|
|
193 |
collection = db[collection_name]
|
194 |
|
195 |
# Insert the document
|
196 |
-
s = collection.find_one(document)
|
|
|
|
|
197 |
if s==None:
|
198 |
-
return
|
199 |
else:
|
200 |
-
|
|
|
201 |
client.close()
|
202 |
return str(s['_id'])
|
203 |
else:
|
204 |
-
return
|
205 |
# Close the connection
|
206 |
|
207 |
|
|
|
1 |
import requests
|
2 |
from pymongo import MongoClient
|
3 |
+
from password import *
|
4 |
|
5 |
def google_search(query, api_key, cx):
|
6 |
url = f"https://www.googleapis.com/customsearch/v1?q={query}&key={api_key}&cx={cx}"
|
|
|
79 |
response = index.query(
|
80 |
namespace=name_space,
|
81 |
vector=query_embedding.tolist(),
|
82 |
+
top_k=5,
|
83 |
include_metadata=True
|
84 |
)
|
85 |
|
|
|
132 |
collection = db[collection_name]
|
133 |
|
134 |
# Insert the document
|
135 |
+
s = collection.find_one({"email":document.get('email')})
|
136 |
+
password = hash_password(document.get('password'))
|
137 |
+
document['password']= password
|
138 |
if s==None:
|
139 |
result = collection.insert_one(document)
|
140 |
client.close()
|
141 |
return str(result.inserted_id)
|
142 |
else:
|
143 |
client.close()
|
144 |
+
return "User Already Exists"
|
145 |
|
146 |
# Close the connection
|
147 |
|
|
|
196 |
collection = db[collection_name]
|
197 |
|
198 |
# Insert the document
|
199 |
+
s = collection.find_one({"email":document.get("email")})
|
200 |
+
print(s)
|
201 |
+
print(document.get('email'))
|
202 |
if s==None:
|
203 |
+
return "User Doesn;t exist"
|
204 |
else:
|
205 |
+
|
206 |
+
if check_password(password=document['password'],hashed_password=s['password']):
|
207 |
client.close()
|
208 |
return str(s['_id'])
|
209 |
else:
|
210 |
+
return "Wrong Password"
|
211 |
# Close the connection
|
212 |
|
213 |
|