Spaces:
Sleeping
Sleeping
Cleanup API responses
Browse files- app/api/userchat.py +6 -1
- app/api/userlogin.py +9 -1
- app/api/userupload.py +16 -4
- app/dependencies.py +15 -12
- app/utils/jwt_utils.py +19 -19
- docker-compose.yml +0 -1
app/api/userchat.py
CHANGED
@@ -9,4 +9,9 @@ async def chat_with_llama(user_input: str = Body(..., embed=True), current_user:
|
|
9 |
# Implement your logic to interact with LlamaV2 LLM here.
|
10 |
# Example response, replace with actual chat logic
|
11 |
chat_response = "Hello, how can I assist you today?"
|
12 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
9 |
# Implement your logic to interact with LlamaV2 LLM here.
|
10 |
# Example response, replace with actual chat logic
|
11 |
chat_response = "Hello, how can I assist you today?"
|
12 |
+
return {
|
13 |
+
"response": chat_response,
|
14 |
+
"user_id": current_user["user_id"],
|
15 |
+
"name": current_user["name"],
|
16 |
+
"role": current_user["role"]
|
17 |
+
}
|
app/api/userlogin.py
CHANGED
@@ -51,6 +51,14 @@ async def user_login(file: UploadFile = File(...)):
|
|
51 |
# Store the token in TinyDB
|
52 |
tinydb_helper.insert_token(user_id, access_token, expires_at)
|
53 |
|
54 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
else:
|
56 |
raise HTTPException(status_code=400, detail="Face not recognized")
|
|
|
|
|
|
51 |
# Store the token in TinyDB
|
52 |
tinydb_helper.insert_token(user_id, access_token, expires_at)
|
53 |
|
54 |
+
return {
|
55 |
+
"access_token": access_token,
|
56 |
+
"token_type": "bearer",
|
57 |
+
"user_id": user_id,
|
58 |
+
"name": metadata["name"],
|
59 |
+
"role": metadata["role"]
|
60 |
+
}
|
61 |
else:
|
62 |
raise HTTPException(status_code=400, detail="Face not recognized")
|
63 |
+
|
64 |
+
os.remove(file_path)
|
app/api/userupload.py
CHANGED
@@ -1,11 +1,23 @@
|
|
1 |
-
from
|
|
|
|
|
|
|
2 |
|
3 |
router = APIRouter()
|
4 |
|
5 |
@router.post("/user/upload")
|
6 |
-
async def upload_file(file: UploadFile = File(...)):
|
7 |
-
|
|
|
|
|
|
|
|
|
8 |
with open(file_location, "wb") as buffer:
|
9 |
contents = await file.read()
|
10 |
buffer.write(contents)
|
11 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any
|
2 |
+
from fastapi import APIRouter, Depends, UploadFile, File
|
3 |
+
import os
|
4 |
+
from app.dependencies import get_current_user
|
5 |
|
6 |
router = APIRouter()
|
7 |
|
8 |
@router.post("/user/upload")
|
9 |
+
async def upload_file(file: UploadFile = File(...), current_user: Any = Depends(get_current_user)):
|
10 |
+
upload_dir = "/home/user/data/uploads"
|
11 |
+
# Ensure the upload directory exists
|
12 |
+
os.makedirs(upload_dir, exist_ok=True) # This creates the directory if it doesn't exist, does nothing otherwise
|
13 |
+
|
14 |
+
file_location = f"{upload_dir}/{file.filename}"
|
15 |
with open(file_location, "wb") as buffer:
|
16 |
contents = await file.read()
|
17 |
buffer.write(contents)
|
18 |
+
return {
|
19 |
+
"status": "File uploaded successfully.",
|
20 |
+
"user_id": current_user["user_id"],
|
21 |
+
"name": current_user["name"],
|
22 |
+
"role": current_user["role"]
|
23 |
+
}
|
app/dependencies.py
CHANGED
@@ -6,20 +6,23 @@ from .utils.jwt_utils import SECRET_KEY, ALGORITHM # Ensure these are defined i
|
|
6 |
|
7 |
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
8 |
|
9 |
-
|
10 |
-
credentials_exception = HTTPException(
|
11 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
12 |
-
detail="Could not validate credentials",
|
13 |
-
headers={"WWW-Authenticate": "Bearer"},
|
14 |
-
)
|
15 |
try:
|
16 |
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
17 |
user_id: str = payload.get("sub")
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
if not token_data:
|
22 |
raise credentials_exception
|
23 |
-
return
|
24 |
-
except
|
25 |
raise credentials_exception
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
8 |
|
9 |
+
def decode_access_token(token: str, credentials_exception) -> dict:
|
|
|
|
|
|
|
|
|
|
|
10 |
try:
|
11 |
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
12 |
user_id: str = payload.get("sub")
|
13 |
+
name: str = payload.get("name")
|
14 |
+
role: str = payload.get("role")
|
15 |
+
if user_id is None or name is None or role is None:
|
|
|
16 |
raise credentials_exception
|
17 |
+
return {"user_id": user_id, "name": name, "role": role}
|
18 |
+
except jwt.PyJWTError:
|
19 |
raise credentials_exception
|
20 |
+
|
21 |
+
async def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
|
22 |
+
credentials_exception = HTTPException(
|
23 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
24 |
+
detail="Could not validate credentials",
|
25 |
+
headers={"WWW-Authenticate": "Bearer"},
|
26 |
+
)
|
27 |
+
return decode_access_token(token, credentials_exception)
|
28 |
+
|
app/utils/jwt_utils.py
CHANGED
@@ -1,8 +1,8 @@
|
|
1 |
from datetime import datetime, timedelta
|
2 |
from jose import JWTError, jwt
|
3 |
from typing import Any, Union
|
4 |
-
from tinydb import TinyDB, Query
|
5 |
-
from tinydb.storages import MemoryStorage
|
6 |
|
7 |
|
8 |
# Secret key to encode JWT tokens. In production, use a more secure key and keep it secret!
|
@@ -10,23 +10,23 @@ SECRET_KEY = "a_very_secret_key"
|
|
10 |
ALGORITHM = "HS256"
|
11 |
ACCESS_TOKEN_EXPIRE_MINUTES = 30 # The expiration time for the access token
|
12 |
|
13 |
-
db = TinyDB(storage=MemoryStorage)
|
14 |
-
tokens_table = db.table('tokens')
|
15 |
-
|
16 |
-
def insert_token(user_id: str, token: str, expires_in: timedelta):
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
def validate_token(user_id: str, token: str) -> bool:
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
|
31 |
def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None) -> str:
|
32 |
"""
|
|
|
1 |
from datetime import datetime, timedelta
|
2 |
from jose import JWTError, jwt
|
3 |
from typing import Any, Union
|
4 |
+
#from tinydb import TinyDB, Query
|
5 |
+
#from tinydb.storages import MemoryStorage
|
6 |
|
7 |
|
8 |
# Secret key to encode JWT tokens. In production, use a more secure key and keep it secret!
|
|
|
10 |
ALGORITHM = "HS256"
|
11 |
ACCESS_TOKEN_EXPIRE_MINUTES = 30 # The expiration time for the access token
|
12 |
|
13 |
+
# db = TinyDB(storage=MemoryStorage)
|
14 |
+
# tokens_table = db.table('tokens')
|
15 |
+
|
16 |
+
# def insert_token(user_id: str, token: str, expires_in: timedelta):
|
17 |
+
# expiration = datetime.utcnow() + expires_in
|
18 |
+
# tokens_table.insert({'user_id': user_id, 'token': token, 'expires_at': expiration.isoformat()})
|
19 |
+
|
20 |
+
# def validate_token(user_id: str, token: str) -> bool:
|
21 |
+
# User = Query()
|
22 |
+
# result = tokens_table.search((User.user_id == user_id) & (User.token == token))
|
23 |
+
# if not result:
|
24 |
+
# return False
|
25 |
+
# # Check token expiration
|
26 |
+
# expires_at = datetime.fromisoformat(result[0]['expires_at'])
|
27 |
+
# if datetime.utcnow() > expires_at:
|
28 |
+
# return False
|
29 |
+
# return True
|
30 |
|
31 |
def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None) -> str:
|
32 |
"""
|
docker-compose.yml
CHANGED
@@ -11,7 +11,6 @@ services:
|
|
11 |
- HOME=/home/user
|
12 |
- PATH=/home/user/.local/bin:$PATH
|
13 |
- NAME=EduConnect
|
14 |
-
- EC_ADMIN_PWD=$2b$12$zybxm7XMoGCVV3ovNDcXt.r2QJUhtj7miYfEfuBw9UGqViTIRFg72
|
15 |
user: "1000:1000"
|
16 |
working_dir: /home/user/app
|
17 |
env_file:
|
|
|
11 |
- HOME=/home/user
|
12 |
- PATH=/home/user/.local/bin:$PATH
|
13 |
- NAME=EduConnect
|
|
|
14 |
user: "1000:1000"
|
15 |
working_dir: /home/user/app
|
16 |
env_file:
|