JWT tokens 1.0

This commit is contained in:
2025-09-19 18:17:31 +03:00
parent 484fa0de23
commit 6b7a57dc6d
12 changed files with 139 additions and 11 deletions

27
server/backend/JWT.py Normal file
View File

@@ -0,0 +1,27 @@
from datetime import datetime, timedelta
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
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
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))
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
async def current_user(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
email: str = payload.get("sub")
if email is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
return email
except JWTError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")

View File

@@ -1,7 +1,10 @@
from fastapi import FastAPI, HTTPException
from fastapi import FastAPI, HTTPException, status, Depends
from fastapi.middleware.cors import CORSMiddleware
from . import pydentic
from . import pydentic, JWT
from datetime import datetime, timedelta
from pydantic import EmailStr
from server.database import db
import asyncio
api = FastAPI()
@@ -14,6 +17,10 @@ api.add_middleware(
allow_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():
for row in await db.get_all_rows():
@@ -21,8 +28,8 @@ async def get_all_rows():
return row
else:
raise HTTPException(status_code=404, detail="The user isn't found")
@api.get("/get_user/{id}", response_model=pydentic.IdofPersons)
async def get_user(id:int):
@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
@@ -63,4 +70,15 @@ async def update_user(id: int, updated_row: pydentic.UserUpdate):
await db.UpdateUser(user)
else:
pass
return user
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")
token = await JWT.create_access_token(
{"sub": user.email},
timedelta(minutes=JWT.ACCESS_TOKEN_EXPIRE_MINUTES)
)
return {"access_token": token, "token_type": "bearer"}

View File

@@ -34,4 +34,7 @@ class UserUpdate(BaseModel):
password:Optional[constr(min_length=8)] = Field(None, description="Password with min 8 chars, letters and digits")
@validator('password')
def password_validator(cls, password):
return check_password_complexity(cls, password)
return check_password_complexity(cls, password)
class UserLogin(BaseModel):
email:EmailStr = Field(..., min_length=6, max_length=254, description="user's email")
password:str = Field(..., description="Password")