Update auth.py
Browse files
auth.py
CHANGED
|
@@ -14,6 +14,7 @@ from jose import JWTError, jwt
|
|
| 14 |
from passlib.context import CryptContext
|
| 15 |
from pymongo import MongoClient
|
| 16 |
import gridfs
|
|
|
|
| 17 |
|
| 18 |
from models import User, UserUpdate, Token, LoginResponse
|
| 19 |
from config import CONNECTION_STRING, SECRET_KEY, ACCESS_TOKEN_EXPIRE_MINUTES, REFRESH_TOKEN_EXPIRE_DAYS
|
|
@@ -101,6 +102,7 @@ async def signup(
|
|
| 101 |
name: str = Form(...),
|
| 102 |
email: str = Form(...),
|
| 103 |
password: str = Form(...),
|
|
|
|
| 104 |
avatar: Optional[UploadFile] = File(None)
|
| 105 |
):
|
| 106 |
try:
|
|
@@ -111,18 +113,24 @@ async def signup(
|
|
| 111 |
if get_user(email):
|
| 112 |
logger.warning(f"Attempt to register already existing email: {email}")
|
| 113 |
raise HTTPException(status_code=400, detail="Email already registered")
|
|
|
|
| 114 |
hashed_password = get_password_hash(password)
|
|
|
|
| 115 |
user_data = {
|
| 116 |
"name": name,
|
| 117 |
"email": email,
|
| 118 |
"hashed_password": hashed_password,
|
|
|
|
| 119 |
"chat_histories": []
|
| 120 |
}
|
|
|
|
| 121 |
if avatar:
|
| 122 |
file_id = await save_avatar_file_to_gridfs(avatar)
|
| 123 |
user_data["avatar"] = file_id
|
|
|
|
| 124 |
users_collection.insert_one(user_data)
|
| 125 |
-
logger.info(f"New user registered: {email}")
|
|
|
|
| 126 |
return {
|
| 127 |
"access_token": create_access_token(email),
|
| 128 |
"refresh_token": create_refresh_token(email),
|
|
@@ -135,16 +143,20 @@ async def login(request: Request, form_data: OAuth2PasswordRequestForm = Depends
|
|
| 135 |
if not user:
|
| 136 |
logger.warning(f"Failed login attempt for: {form_data.username}")
|
| 137 |
raise HTTPException(status_code=401, detail="Incorrect username or password")
|
|
|
|
| 138 |
logger.info(f"User logged in: {user['email']}")
|
|
|
|
| 139 |
avatar_url = None
|
| 140 |
if "avatar" in user and user["avatar"]:
|
| 141 |
avatar_url = f"/auth/avatar/{user['avatar']}"
|
|
|
|
| 142 |
return {
|
| 143 |
"access_token": create_access_token(user["email"]),
|
| 144 |
"refresh_token": create_refresh_token(user["email"]),
|
| 145 |
"token_type": "bearer",
|
| 146 |
"name": user["name"],
|
| 147 |
-
"avatar": avatar_url
|
|
|
|
| 148 |
}
|
| 149 |
|
| 150 |
@router.get("/user/data")
|
|
@@ -152,10 +164,12 @@ async def get_user_data(request: Request, current_user: dict = Depends(get_curre
|
|
| 152 |
avatar_url = None
|
| 153 |
if "avatar" in current_user and current_user["avatar"]:
|
| 154 |
avatar_url = f"/auth/avatar/{current_user['avatar']}"
|
|
|
|
| 155 |
return {
|
| 156 |
"name": current_user["name"],
|
| 157 |
"email": current_user["email"],
|
| 158 |
"avatar": avatar_url,
|
|
|
|
| 159 |
"chat_histories": current_user.get("chat_histories", [])
|
| 160 |
}
|
| 161 |
|
|
@@ -180,14 +194,18 @@ async def update_user(
|
|
| 180 |
logger.error(f"Password validation error during update: {e}")
|
| 181 |
raise HTTPException(status_code=400, detail=str(e))
|
| 182 |
update_data["hashed_password"] = get_password_hash(password)
|
|
|
|
| 183 |
if avatar:
|
| 184 |
file_id = await save_avatar_file_to_gridfs(avatar)
|
| 185 |
update_data["avatar"] = file_id
|
|
|
|
| 186 |
if not update_data:
|
| 187 |
logger.info("No update parameters provided")
|
| 188 |
raise HTTPException(status_code=400, detail="No update parameters provided")
|
|
|
|
| 189 |
users_collection.update_one({"email": current_user["email"]}, {"$set": update_data})
|
| 190 |
logger.info(f"User updated: {current_user['email']}")
|
|
|
|
| 191 |
return {"message": "User updated successfully"}
|
| 192 |
|
| 193 |
@router.post("/logout")
|
|
@@ -195,8 +213,6 @@ async def logout(request: Request, current_user: dict = Depends(get_current_user
|
|
| 195 |
logger.info(f"User logged out: {current_user['email']}")
|
| 196 |
return {"message": "User logged out successfully"}
|
| 197 |
|
| 198 |
-
from bson import ObjectId
|
| 199 |
-
|
| 200 |
@router.get("/avatar/{file_id}")
|
| 201 |
async def get_avatar(file_id: str):
|
| 202 |
try:
|
|
@@ -205,4 +221,4 @@ async def get_avatar(file_id: str):
|
|
| 205 |
return StreamingResponse(file, media_type=file.content_type)
|
| 206 |
except Exception as e:
|
| 207 |
logger.error(f"Avatar not found for file_id {file_id}: {e}")
|
| 208 |
-
raise HTTPException(status_code=404, detail="Avatar not found")
|
|
|
|
| 14 |
from passlib.context import CryptContext
|
| 15 |
from pymongo import MongoClient
|
| 16 |
import gridfs
|
| 17 |
+
from bson import ObjectId # Ensure ObjectId is imported
|
| 18 |
|
| 19 |
from models import User, UserUpdate, Token, LoginResponse
|
| 20 |
from config import CONNECTION_STRING, SECRET_KEY, ACCESS_TOKEN_EXPIRE_MINUTES, REFRESH_TOKEN_EXPIRE_DAYS
|
|
|
|
| 102 |
name: str = Form(...),
|
| 103 |
email: str = Form(...),
|
| 104 |
password: str = Form(...),
|
| 105 |
+
role: str = Form(...), # <-- MODIFICATION: Added role
|
| 106 |
avatar: Optional[UploadFile] = File(None)
|
| 107 |
):
|
| 108 |
try:
|
|
|
|
| 113 |
if get_user(email):
|
| 114 |
logger.warning(f"Attempt to register already existing email: {email}")
|
| 115 |
raise HTTPException(status_code=400, detail="Email already registered")
|
| 116 |
+
|
| 117 |
hashed_password = get_password_hash(password)
|
| 118 |
+
|
| 119 |
user_data = {
|
| 120 |
"name": name,
|
| 121 |
"email": email,
|
| 122 |
"hashed_password": hashed_password,
|
| 123 |
+
"role": role, # <-- MODIFICATION: Added role to user data
|
| 124 |
"chat_histories": []
|
| 125 |
}
|
| 126 |
+
|
| 127 |
if avatar:
|
| 128 |
file_id = await save_avatar_file_to_gridfs(avatar)
|
| 129 |
user_data["avatar"] = file_id
|
| 130 |
+
|
| 131 |
users_collection.insert_one(user_data)
|
| 132 |
+
logger.info(f"New user registered: {email} with role: {role}")
|
| 133 |
+
|
| 134 |
return {
|
| 135 |
"access_token": create_access_token(email),
|
| 136 |
"refresh_token": create_refresh_token(email),
|
|
|
|
| 143 |
if not user:
|
| 144 |
logger.warning(f"Failed login attempt for: {form_data.username}")
|
| 145 |
raise HTTPException(status_code=401, detail="Incorrect username or password")
|
| 146 |
+
|
| 147 |
logger.info(f"User logged in: {user['email']}")
|
| 148 |
+
|
| 149 |
avatar_url = None
|
| 150 |
if "avatar" in user and user["avatar"]:
|
| 151 |
avatar_url = f"/auth/avatar/{user['avatar']}"
|
| 152 |
+
|
| 153 |
return {
|
| 154 |
"access_token": create_access_token(user["email"]),
|
| 155 |
"refresh_token": create_refresh_token(user["email"]),
|
| 156 |
"token_type": "bearer",
|
| 157 |
"name": user["name"],
|
| 158 |
+
"avatar": avatar_url,
|
| 159 |
+
"role": user.get("role", "user") # <-- MODIFICATION: Return role (default to "user")
|
| 160 |
}
|
| 161 |
|
| 162 |
@router.get("/user/data")
|
|
|
|
| 164 |
avatar_url = None
|
| 165 |
if "avatar" in current_user and current_user["avatar"]:
|
| 166 |
avatar_url = f"/auth/avatar/{current_user['avatar']}"
|
| 167 |
+
|
| 168 |
return {
|
| 169 |
"name": current_user["name"],
|
| 170 |
"email": current_user["email"],
|
| 171 |
"avatar": avatar_url,
|
| 172 |
+
"role": current_user.get("role", "user"), # <-- MODIFICATION: Return role (default to "user")
|
| 173 |
"chat_histories": current_user.get("chat_histories", [])
|
| 174 |
}
|
| 175 |
|
|
|
|
| 194 |
logger.error(f"Password validation error during update: {e}")
|
| 195 |
raise HTTPException(status_code=400, detail=str(e))
|
| 196 |
update_data["hashed_password"] = get_password_hash(password)
|
| 197 |
+
|
| 198 |
if avatar:
|
| 199 |
file_id = await save_avatar_file_to_gridfs(avatar)
|
| 200 |
update_data["avatar"] = file_id
|
| 201 |
+
|
| 202 |
if not update_data:
|
| 203 |
logger.info("No update parameters provided")
|
| 204 |
raise HTTPException(status_code=400, detail="No update parameters provided")
|
| 205 |
+
|
| 206 |
users_collection.update_one({"email": current_user["email"]}, {"$set": update_data})
|
| 207 |
logger.info(f"User updated: {current_user['email']}")
|
| 208 |
+
|
| 209 |
return {"message": "User updated successfully"}
|
| 210 |
|
| 211 |
@router.post("/logout")
|
|
|
|
| 213 |
logger.info(f"User logged out: {current_user['email']}")
|
| 214 |
return {"message": "User logged out successfully"}
|
| 215 |
|
|
|
|
|
|
|
| 216 |
@router.get("/avatar/{file_id}")
|
| 217 |
async def get_avatar(file_id: str):
|
| 218 |
try:
|
|
|
|
| 221 |
return StreamingResponse(file, media_type=file.content_type)
|
| 222 |
except Exception as e:
|
| 223 |
logger.error(f"Avatar not found for file_id {file_id}: {e}")
|
| 224 |
+
raise HTTPException(status_code=404, detail="Avatar not found")
|