env python 1.0

This commit is contained in:
2025-09-20 14:05:42 +03:00
parent a26a0bf10b
commit 58419b0e14
6 changed files with 43 additions and 16 deletions

14
.env Normal file
View File

@@ -0,0 +1,14 @@
# JWT configuration
SECRET_KEY=SUPER_SECRET_KEY
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
# CORS-middleware
# ALLOW_ORIGINS=*, # "*" — разрешить всем; можно указать список конкретных доменов
# ALLOW_CREDENTIALS=True,
# ALLOW_METHODS=*, # GET, POST, PUT, DELETE и т.д.
# ALLOW_HEADERS=*, # Разрешить любые заголовки вот он есть, но находится в другой папке просто
ALLOW_ORIGINS=*
ALLOW_CREDENTIALS=True
ALLOW_METHODS=*
ALLOW_HEADERS=*

4
.gitignore vendored
View File

@@ -20,5 +20,5 @@ Thumbs.db
hint.py hint.py
#env #env
*.env #*.env
example.db *.db

View File

@@ -1,14 +1,17 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta #jwt
from jose import JWTError, jwt from jose import JWTError, jwt
from fastapi import HTTPException, Depends, status from fastapi import HTTPException, Depends, status
from fastapi.security import OAuth2PasswordBearer from fastapi.security import OAuth2PasswordBearer
SECRET_KEY = "super-secret-string" from dotenv import load_dotenv #Работа с env для jwt
ALGORITHM = "HS256" import os
ACCESS_TOKEN_EXPIRE_MINUTES = 30 load_dotenv()
SECRET_KEY = os.getenv('SECRET_KEY')
ALGORITHM = os.getenv('ALGORITHM')
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv('ACCESS_TOKEN_EXPIRE_MINUTES'))
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login") #Создание jwt
async def create_access_token(data: dict, expires_delta: timedelta | None = None): async def create_access_token(data: dict, expires_delta: timedelta | None = None):
to_encode = data.copy() to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15)) expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
@@ -16,7 +19,7 @@ async def create_access_token(data: dict, expires_delta: timedelta | None = None
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt return encoded_jwt
async def current_user(token: str = Depends(oauth2_scheme)): async def current_user(token: str = Depends(oauth2_scheme)): #Проверка jwt
try: try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
email: str = payload.get("sub") email: str = payload.get("sub")

View File

@@ -4,17 +4,23 @@ from . import pydentic, JWT
from datetime import datetime, timedelta from datetime import datetime, timedelta
from pydantic import EmailStr from pydantic import EmailStr
from server.database import db from server.database import db
import asyncio import asyncio
api = FastAPI() 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( api.add_middleware(
CORSMiddleware, CORSMiddleware,
allow_origins=["*"], # "*" — разрешить всем; можно указать список конкретных доменов allow_origins=origins,
allow_credentials=True, allow_credentials=credentials,
allow_methods=["*"], # GET, POST, PUT, DELETE и т.д. allow_methods=methods,
allow_headers=["*"], # Разрешить любые заголовки allow_headers=headers,
) )
@api.get("/protected") @api.get("/protected")
@@ -22,7 +28,7 @@ async def protected(current_user: str = Depends(JWT.current_user)):
return {"msg": f"Hello, {current_user}"} return {"msg": f"Hello, {current_user}"}
@api.get("/", response_model=pydentic.IdofPersons) @api.get("/", response_model=pydentic.IdofPersons)
async def get_all_rows(): async def get_all_rows(current_user: str = Depends(JWT.current_user)):
for row in await db.get_all_rows(): for row in await db.get_all_rows():
if row: if row:
return row return row
@@ -42,14 +48,14 @@ async def create_user(row:pydentic.CreateUser):
await db.CreateUser(new_row) await db.CreateUser(new_row)
return new_row return new_row
@api.delete("/user_delete/{id}", response_model=pydentic.IdofPersons) @api.delete("/user_delete/{id}", response_model=pydentic.IdofPersons)
async def delete_user(id: int): async def delete_user(id: int,current_user: str = Depends(JWT.current_user)):
user = await db.GetUser(id) user = await db.GetUser(id)
if not user: if not user:
raise HTTPException(status_code=404, detail="The user isn't found") raise HTTPException(status_code=404, detail="The user isn't found")
await db.DeleteUser(id) await db.DeleteUser(id)
return user return user
@api.put("/user_update/{id}", response_model=pydentic.IdofPersons) @api.put("/user_update/{id}", response_model=pydentic.IdofPersons)
async def update_user(id: int, updated_row: pydentic.UserUpdate): async def update_user(id: int, updated_row: pydentic.UserUpdate, current_user: str = Depends(JWT.current_user)):
user = await db.GetUser(id) user = await db.GetUser(id)
if not user: if not user:
raise HTTPException(status_code=404, detail="The user isn't found") raise HTTPException(status_code=404, detail="The user isn't found")

Binary file not shown.

View File

@@ -1,3 +1,7 @@
const token = localStorage.getItem("token");
if (token) {
window.location.href = "./../main/index.html";
}
document.getElementById('loginForm').addEventListener('submit', async function (e) { document.getElementById('loginForm').addEventListener('submit', async function (e) {
e.preventDefault(); e.preventDefault();
const email = document.getElementById('email').value; const email = document.getElementById('email').value;