From 58419b0e14710098264496ca6fb1fe0974d82f84 Mon Sep 17 00:00:00 2001 From: "MH.Dmitrii" Date: Sat, 20 Sep 2025 14:05:42 +0300 Subject: [PATCH] env python 1.0 --- .env | 14 ++++++++++++++ .gitignore | 4 ++-- server/backend/JWT.py | 15 +++++++++------ server/backend/endpoints.py | 22 ++++++++++++++-------- server/database/DB/example.db | Bin 16384 -> 0 bytes server/front/login/js.js | 4 ++++ 6 files changed, 43 insertions(+), 16 deletions(-) create mode 100644 .env delete mode 100644 server/database/DB/example.db diff --git a/.env b/.env new file mode 100644 index 0000000..819e2e1 --- /dev/null +++ b/.env @@ -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=* \ No newline at end of file diff --git a/.gitignore b/.gitignore index e266e38..774a804 100644 --- a/.gitignore +++ b/.gitignore @@ -20,5 +20,5 @@ Thumbs.db hint.py #env -*.env -example.db \ No newline at end of file +#*.env +*.db \ No newline at end of file diff --git a/server/backend/JWT.py b/server/backend/JWT.py index 88f2fa5..9d7f107 100644 --- a/server/backend/JWT.py +++ b/server/backend/JWT.py @@ -1,14 +1,17 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta #jwt from jose import JWTError, jwt from fastapi import HTTPException, Depends, status from fastapi.security import OAuth2PasswordBearer -SECRET_KEY = "super-secret-string" -ALGORITHM = "HS256" -ACCESS_TOKEN_EXPIRE_MINUTES = 30 +from dotenv import load_dotenv #Работа с env для jwt +import os +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): to_encode = data.copy() 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) return encoded_jwt -async def current_user(token: str = Depends(oauth2_scheme)): +async def current_user(token: str = Depends(oauth2_scheme)): #Проверка jwt try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) email: str = payload.get("sub") diff --git a/server/backend/endpoints.py b/server/backend/endpoints.py index 3a98b4c..9a4bbf4 100644 --- a/server/backend/endpoints.py +++ b/server/backend/endpoints.py @@ -4,17 +4,23 @@ 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=["*"], # "*" — разрешить всем; можно указать список конкретных доменов - allow_credentials=True, - allow_methods=["*"], # GET, POST, PUT, DELETE и т.д. - allow_headers=["*"], # Разрешить любые заголовки + allow_origins=origins, + allow_credentials=credentials, + allow_methods=methods, + allow_headers=headers, ) @api.get("/protected") @@ -22,7 +28,7 @@ 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(): +async def get_all_rows(current_user: str = Depends(JWT.current_user)): for row in await db.get_all_rows(): if row: return row @@ -42,14 +48,14 @@ async def create_user(row:pydentic.CreateUser): await db.CreateUser(new_row) return new_row @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) 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): +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") diff --git a/server/database/DB/example.db b/server/database/DB/example.db deleted file mode 100644 index 2a6781bd8bf57cde87cf647e112f52193fdef538..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16384 zcmeI&!E4h{7y$5>C0%WCiwY8k8$57_MI^OVt1yHnTUfhxjmg?|-DRdt+P$_}x+LAw zo*aS~{|EmA!L#RGh4p{%+VnyDNHC$FIxLhrj9^z!ev~<$L zJEFFh7qykl(jTe@t}nFG(aX{S^o3w*0(FRTQ@q{gHbEr5^5*Pk^a26SsWEgebpNcNr$9cn&M;| zwO!kntc@BIM|@cFz_y0nbS~T*5FC4|@OEmbj+%w`rr2*N-oajVy*TI&y0yko@V%Ph zKGG|aZXL^+jM??`{WYg4r8iy$Q(g@VpMM&^9={u(o_}<5rmtK5o+&hKYw8JttTa@K zw7hbL)XlctR(7rRfwq_0A_Z$u?e&Vbu8xYwTOC*SNxu86qh^Q6;H%Q?8Dh`aG5h7Z ze`1(F2!H?xfB*=900@8p2!H?xfB*>mrvi8B)J=Mcnrvpo?$A6ny$!+KqgSbaY#`7{ z_GhsE|BBde?C&5z0|5{K0T2KI5C8!X009sH0T2KI5V+O?F`A-cvG7QTfB!S#8N>Vm DJg)1t diff --git a/server/front/login/js.js b/server/front/login/js.js index 2044542..c5ef518 100644 --- a/server/front/login/js.js +++ b/server/front/login/js.js @@ -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) { e.preventDefault(); const email = document.getElementById('email').value;