Spaces:
Sleeping
Sleeping
File size: 13,713 Bytes
0f75bc4 39df9c9 0f75bc4 c760cc8 0f75bc4 3c28e31 c760cc8 3c28e31 c760cc8 0f75bc4 de419dd 0f75bc4 3c28e31 0f75bc4 3c28e31 0f75bc4 3c28e31 0f75bc4 3c28e31 0f75bc4 3c28e31 c760cc8 3c28e31 c760cc8 3c28e31 0f75bc4 3c28e31 0f75bc4 3c28e31 0f75bc4 3a975c6 0f75bc4 3c28e31 0f75bc4 3c28e31 0f75bc4 3c28e31 0f75bc4 |
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
import os
import uuid
import logging
from datetime import datetime, timedelta
from urllib.parse import quote_plus
from typing import List, Optional, Any
from dotenv import load_dotenv
from fastapi import APIRouter, HTTPException, Depends, Request, UploadFile, File, Form, Body
from fastapi.responses import JSONResponse
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, EmailStr, Field, validator
from pymongo import MongoClient
import os.path
# ----- OTP and Email Imports -----
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
try:
import markdown
except ImportError:
markdown = None
import secrets
# ----------------------------------
load_dotenv()
# Setup logging
logger = logging.getLogger("uvicorn")
logger.setLevel(logging.INFO)
# MongoDB setup for user management
password = quote_plus(os.getenv("MONGO_PASSWORD"))
MONGO_URL = os.getenv("CONNECTION_STRING").replace("${PASSWORD}", password)
client = MongoClient(MONGO_URL)
db = client.users_database
users_collection = db.users
# New collection to store OTP records
otp_collection = db.otp_verifications
# OAuth2 setup
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# Create an APIRouter instance
router = APIRouter()
# Pydantic models
class User(BaseModel):
name: str = Field(..., min_length=3, max_length=50)
email: EmailStr
password: str
@validator("password")
def validate_password(cls, value):
if len(value) < 8:
raise ValueError("Password must be at least 8 characters long.")
if not any(char.isdigit() for char in value):
raise ValueError("Password must include at least one number.")
if not any(char.isupper() for char in value):
raise ValueError("Password must include at least one uppercase letter.")
if not any(char.islower() for char in value):
raise ValueError("Password must include at least one lowercase letter.")
if not any(char in "!@#$%^&*()-_+=<>?/" for char in value):
raise ValueError("Password must include at least one special character.")
return value
class UserUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=3, max_length=50)
email: Optional[EmailStr]
password: Optional[str]
@validator("password")
def validate_password(cls, value):
if value is not None:
if len(value) < 8:
raise ValueError("Password must be at least 8 characters long.")
if not any(char.isdigit() for char in value):
raise ValueError("Password must include at least one number.")
if not any(char.isupper() for char in value):
raise ValueError("Password must include at least one uppercase letter.")
if not any(char.islower() for char in value):
raise ValueError("Password must include at least one lowercase letter.")
if not any(char in "!@#$%^&*()-_+=<>?/" for char in value):
raise ValueError("Password must include at least one special character.")
return value
class Token(BaseModel):
access_token: str
refresh_token: str
token_type: str
class LoginResponse(Token):
name: str
avatar: Optional[str] = None
class TokenData(BaseModel):
email: Optional[str] = None
# Password hashing
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
def get_user(email: str) -> Optional[dict]:
return users_collection.find_one({"email": email})
def authenticate_user(email: str, password: str) -> Optional[dict]:
user = get_user(email)
if not user or not verify_password(password, user["hashed_password"]):
return None
return user
def create_token(data: dict, expires_delta: timedelta = None) -> str:
to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
to_encode.update({"exp": expire})
secret_key = os.getenv("SECRET_KEY")
algorithm = "HS256"
return jwt.encode(to_encode, secret_key, algorithm=algorithm)
def create_access_token(email: str) -> str:
return create_token({"sub": email}, timedelta(minutes=int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "90"))))
def create_refresh_token(email: str) -> str:
return create_token({"sub": email}, timedelta(days=int(os.getenv("REFRESH_TOKEN_EXPIRE_DAYS", "7"))))
def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
secret_key = os.getenv("SECRET_KEY")
try:
payload = jwt.decode(token, secret_key, algorithms=["HS256"])
email: str = payload.get("sub")
if not email:
raise HTTPException(status_code=401, detail="Invalid credentials")
user = get_user(email)
if not user:
raise HTTPException(status_code=401, detail="User not found")
return user
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")
# Setup for avatar file saving
AVATAR_DIR = "avatars"
if not os.path.exists(AVATAR_DIR):
os.makedirs(AVATAR_DIR)
def save_avatar_file(file: UploadFile) -> str:
allowed_types = ["image/jpeg", "image/png", "image/gif"]
if file.content_type not in allowed_types:
logger.error(f"Unsupported file type: {file.content_type}")
raise HTTPException(
status_code=400,
detail="Invalid image format. Only JPEG, PNG, and GIF are accepted."
)
file_extension = os.path.splitext(file.filename)[1]
unique_filename = f"{uuid.uuid4()}{file_extension}"
file_path = os.path.join(AVATAR_DIR, unique_filename)
try:
contents = file.file.read()
with open(file_path, "wb") as f:
f.write(contents)
logger.info(f"Avatar saved as {file_path}")
except Exception as e:
logger.exception("Failed to save avatar file")
raise HTTPException(status_code=500, detail="Could not save avatar file.")
finally:
file.file.close()
return file_path
# ----- OTP and Email Functions -----
def generate_otp(length=6):
"""Generate a numeric OTP of specified length."""
digits = "0123456789"
otp = ''.join(secrets.choice(digits) for _ in range(length))
return otp
def send_email_func(sender_email, sender_password, receiver_email, subject, body):
smtp_server = "smtp.gmail.com"
port = 587
message = MIMEMultipart("alternative")
message["Subject"] = subject
message["From"] = sender_email
message["To"] = receiver_email
part1 = MIMEText(body, "plain")
if markdown:
html_content = markdown.markdown(body)
else:
html_content = f"<pre>{body}</pre>"
html_template = f"""\
<html>
<head>
<style>
body {{
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 20px;
}}
h1, h2, h3 {{
color: #333;
}}
pre {{
background: #f4f4f4;
padding: 10px;
border: 1px solid #ddd;
}}
</style>
</head>
<body>
{html_content}
</body>
</html>
"""
part2 = MIMEText(html_template, "html")
message.attach(part1)
message.attach(part2)
try:
with smtplib.SMTP(smtp_server, port, timeout=10) as server:
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_email, message.as_string())
logger.info("Successfully sent email")
except Exception as e:
logger.error(f"Error sending email: {e}")
raise e
# ------------------------------------
# ----- Auth Endpoints -----
@router.post("/send_otp")
async def send_otp(receiver_email: EmailStr = Body(..., embed=True)):
"""
Generates an OTP and sends it via email to the provided receiver_email.
(For demonstration purposes, the OTP is returned. Remove it in production.)
"""
sender_email = os.getenv("SENDER_EMAIL")
sender_password = os.getenv("SENDER_PASSWORD")
if not sender_email or not sender_password:
raise HTTPException(status_code=500, detail="Email sender credentials are not configured.")
otp = generate_otp(6)
subject = "Your One-Time Password (OTP)"
body = f"""\
# Your OTP
Here is your one-time password (OTP):
`{otp}`
Please use the code above to verify your email and proceed with account creation.
"""
try:
send_email_func(sender_email, sender_password, receiver_email, subject, body)
# Store OTP record with a 10-minute expiration
otp_record = {
"email": receiver_email,
"otp": otp,
"expires_at": datetime.utcnow() + timedelta(minutes=1)
}
otp_collection.update_one({"email": receiver_email}, {"$set": otp_record}, upsert=True)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error sending OTP email: {str(e)}")
return {"message": "OTP sent successfully", "otp": otp} # Remove OTP from response in production
@router.post("/signup", response_model=Token)
async def signup(
request: Request,
name: str = Form(...),
email: EmailStr = Form(...),
password: str = Form(...),
otp: str = Form(...),
avatar: Optional[UploadFile] = File(None)
):
# Verify OTP for this email
otp_record = otp_collection.find_one({"email": email})
if not otp_record:
raise HTTPException(status_code=400, detail="No OTP sent to this email. Please request an OTP first.")
if otp_record["otp"] != otp:
raise HTTPException(status_code=400, detail="Invalid OTP provided.")
if datetime.utcnow() > otp_record["expires_at"]:
raise HTTPException(status_code=400, detail="OTP has expired. Please request a new one.")
# Remove the OTP record after successful verification
otp_collection.delete_one({"email": email})
try:
_ = User(name=name, email=email, password=password)
except Exception as e:
logger.error(f"Validation error during signup: {e}")
raise HTTPException(status_code=400, detail=str(e))
if get_user(email):
logger.warning(f"Attempt to register already existing email: {email}")
raise HTTPException(status_code=400, detail="Email already registered")
hashed_password = get_password_hash(password)
user_data = {
"name": name,
"email": email,
"hashed_password": hashed_password,
"chat_histories": []
}
if avatar:
avatar_path = save_avatar_file(avatar)
user_data["avatar"] = f"/avatars/{os.path.basename(avatar_path)}"
users_collection.insert_one(user_data)
logger.info(f"New user registered: {email}")
return {
"access_token": create_access_token(email),
"refresh_token": create_refresh_token(email),
"token_type": "bearer"
}
@router.post("/login", response_model=LoginResponse)
async def login(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(form_data.username, form_data.password)
if not user:
logger.warning(f"Failed login attempt for: {form_data.username}")
raise HTTPException(status_code=401, detail="Incorrect username or password")
logger.info(f"User logged in: {user['email']}")
return {
"access_token": create_access_token(user["email"]),
"refresh_token": create_refresh_token(user["email"]),
"token_type": "bearer",
"name": user["name"],
"avatar": user.get("avatar")
}
@router.get("/user/data")
async def get_user_data(request: Request, current_user: dict = Depends(get_current_user)):
return {
"name": current_user["name"],
"email": current_user["email"],
"avatar": current_user.get("avatar"),
"chat_histories": current_user.get("chat_histories", [])
}
@router.put("/user/update")
async def update_user(
request: Request,
name: Optional[str] = Form(None),
email: Optional[EmailStr] = Form(None),
password: Optional[str] = Form(None),
avatar: Optional[UploadFile] = File(None),
current_user: dict = Depends(get_current_user)
):
update_data = {}
if name is not None:
update_data["name"] = name
if email is not None:
update_data["email"] = email
if password is not None:
try:
_ = User(name=current_user["name"], email=current_user["email"], password=password)
except Exception as e:
logger.error(f"Password validation error during update: {e}")
raise HTTPException(status_code=400, detail=str(e))
update_data["hashed_password"] = get_password_hash(password)
if avatar:
avatar_path = save_avatar_file(avatar)
update_data["avatar"] = f"/avatars/{os.path.basename(avatar_path)}"
if not update_data:
logger.info("No update parameters provided")
raise HTTPException(status_code=400, detail="No update parameters provided")
users_collection.update_one({"email": current_user["email"]}, {"$set": update_data})
logger.info(f"User updated: {current_user['email']}")
return {"message": "User updated successfully"}
@router.post("/logout")
async def logout(request: Request, current_user: dict = Depends(get_current_user)):
logger.info(f"User logged out: {current_user['email']}")
return {"message": "User logged out successfully"}
|