
Features: - User authentication with JWT tokens - Task and project CRUD operations - Task filtering and organization generated with BackendIM... (backend.im)
33 lines
1.1 KiB
Python
33 lines
1.1 KiB
Python
from datetime import datetime, timedelta
|
|
from jose import JWTError, jwt
|
|
from typing import Optional
|
|
|
|
from app.schemas.token import TokenData
|
|
|
|
# to generate a secure secret key: openssl rand -hex 32
|
|
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
|
|
ALGORITHM = "HS256"
|
|
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
|
|
|
|
|
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
|
|
to_encode = data.copy()
|
|
if expires_delta:
|
|
expire = datetime.utcnow() + expires_delta
|
|
else:
|
|
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
to_encode.update({"exp": expire})
|
|
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
|
return encoded_jwt
|
|
|
|
|
|
def verify_token(token: str, credentials_exception):
|
|
try:
|
|
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
|
username: str = payload.get("sub")
|
|
if username is None:
|
|
raise credentials_exception
|
|
token_data = TokenData(username=username)
|
|
return token_data
|
|
except JWTError:
|
|
raise credentials_exception |