users table endpoints. auth to fix
This commit is contained in:
88
src/api/utils.py
Normal file
88
src/api/utils.py
Normal file
@ -0,0 +1,88 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Annotated
|
||||
|
||||
import jwt
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from jwt.exceptions import InvalidTokenError
|
||||
from passlib.context import CryptContext
|
||||
from psycopg2._psycopg import connection
|
||||
|
||||
import db.users
|
||||
import settings.settings as settings
|
||||
from api.models import TokenData, User
|
||||
from db.internal import get_db_connection
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
||||
|
||||
|
||||
def decode_token(token):
|
||||
return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
|
||||
def encode_token(payload):
|
||||
return jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm)
|
||||
|
||||
def verify_password(plain_password, hashed_password):
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
|
||||
|
||||
def authenticate_user(
|
||||
conn: connection,
|
||||
username: str,
|
||||
password: str
|
||||
):
|
||||
user = User()
|
||||
userdata = db.users.get_user(conn, username)
|
||||
if not userdata:
|
||||
return False
|
||||
if not verify_password(password, user.password):
|
||||
return False
|
||||
user.fill(userdata)
|
||||
return user
|
||||
|
||||
def create_access_token(
|
||||
data: dict,
|
||||
expires_delta: timedelta
|
||||
):
|
||||
encode_payload = data.copy()
|
||||
expire_moment = datetime.now(timezone.utc) + expires_delta
|
||||
encode_payload.update({"exp": expire_moment})
|
||||
encoded_jwt = encode_token(encode_payload)
|
||||
return encoded_jwt
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
token: Annotated[str, Depends(oauth2_scheme)],
|
||||
conn: Annotated[connection, Depends(get_db_connection)]
|
||||
):
|
||||
credentials_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
try:
|
||||
payload = decode_token(token)
|
||||
print(payload)
|
||||
username = payload.get("sub")
|
||||
if username is None:
|
||||
raise credentials_exception
|
||||
token_data = TokenData(username=username)
|
||||
except InvalidTokenError:
|
||||
raise credentials_exception
|
||||
|
||||
user = User()
|
||||
user.fill(db.users.get_user(conn, username=token_data.username))
|
||||
if user is None:
|
||||
raise credentials_exception
|
||||
|
||||
if user.disabled:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Inactive user"
|
||||
)
|
||||
|
||||
return user
|
||||
Reference in New Issue
Block a user