Backend finished
Co-authored-by: Álvaro <alvaro6gv@users.noreply.github.com>
This commit is contained in:
35
backend/app/core/security.py
Normal file
35
backend/app/core/security.py
Normal file
@@ -0,0 +1,35 @@
|
||||
from passlib.context import CryptContext
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from app.core.config import settings
|
||||
import jwt
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
def generate_jwt(data: dict, expires: timedelta | None = None):
|
||||
to_encode = data.copy()
|
||||
if expires:
|
||||
expire = datetime.now(timezone.utc) + expires
|
||||
else:
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=15)
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
||||
|
||||
def verify_jwt(token: str):
|
||||
try:
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
return payload
|
||||
except jwt.PyJWTError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token inválido o expirado",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
Reference in New Issue
Block a user