Files
sqlalchemy-fastapi-pydentic…/server/backend/endpoints.py
2025-09-21 17:49:55 +03:00

102 lines
3.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from fastapi import FastAPI, HTTPException, status, Depends
from fastapi.middleware.cors import CORSMiddleware
from . import pydentic, JWT
from datetime import datetime, timedelta
from pydantic import EmailStr
from server.database import db
import asyncio
api = FastAPI()
from dotenv import load_dotenv #Работа с env для CORS
import os
load_dotenv()
origins = os.getenv("ALLOW_ORIGINS").split(",")
credentials = os.getenv("ALLOW_CREDENTIALS").lower() == "true"
methods = os.getenv("ALLOW_METHODS").split(",")
headers = os.getenv("ALLOW_HEADERS").split(",")
api.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=credentials,
allow_methods=methods,
allow_headers=headers,
)
@api.get("/protected")
async def protected(current_user: str = Depends(JWT.current_user)):
return {"msg": f"Hello, {current_user}"}
@api.get("/", response_model=pydentic.IdofPersons)
async def get_all_rows(current_user: str = Depends(JWT.current_user)):
for row in await db.get_all_rows():
if row:
return row
else:
raise HTTPException(status_code=404, detail="The user isn't found")
@api.get("/get_user_by_id/{id}", response_model=pydentic.IdofPersons)
async def get_user(id: int, current_user: str = Depends(JWT.current_user)):
user = await db.GetUser(id)
if user:
return user
else:
raise HTTPException(status_code=404, detail="The user isn't found")
@api.post("/user_create", response_model=pydentic.IdofPersons)
async def create_user(row:pydentic.CreateUser):
rows = await db.get_all_rows()
if rows:
new_user_id = max(item.id for item in rows) + 1
else:
new_user_id = 1
new_row = pydentic.IdofPersons(id = new_user_id, email=row.email, description=row.description, activated = row.activated, password = row.password)
await db.CreateUser(new_row)
return new_row
@api.delete("/user_delete/{id}", response_model=pydentic.IdofPersons)
async def delete_user(id: int,current_user: str = Depends(JWT.current_user)):
user = await db.GetUser(id)
if not user:
raise HTTPException(status_code=404, detail="The user isn't found")
await db.DeleteUser(id)
return user
@api.put("/user_update/{id}", response_model=pydentic.IdofPersons)
async def update_user(id: int, updated_row: pydentic.UserUpdate, current_user: str = Depends(JWT.current_user)):
user = await db.GetUser(id)
if not user:
raise HTTPException(status_code=404, detail="The user isn't found")
changed = False
if updated_row.email is not None and updated_row.email != user.email:
user.email = updated_row.email
changed = True
if updated_row.description is not None and updated_row.description != user.description:
user.description = updated_row.description
changed = True
if updated_row.activated is not None and updated_row.activated != user.activated:
user.activated = updated_row.activated
changed = True
if updated_row.password is not None and updated_row.password != user.password:
user.password = updated_row.password
changed = True
if changed:
await db.UpdateUser(user)
else:
pass
return user
@api.post("/login")
async def login_user(row: pydentic.UserLogin):
user = await db.LoginUser(row)
if not user:
raise HTTPException(status_code=401, detail="The user isn't found")
access_token = await JWT.AccessToken.create(
{"sub": user.email},
timedelta(minutes=JWT.ACCESS_TOKEN_EXPIRE_MINUTES)
)
refresh_token = await JWT.RefreshToken.create(
{"sub": user.email},
timedelta(minutes=JWT.REFRESH_TOKEN_EXPIRE_MINUTES)
)
return {
"access_token": access_token,
"refresh_token": refresh_token,
"token_type": "bearer"
}