fixed auth, added more endpoints and config saving

This commit is contained in:
2025-07-28 18:52:53 +03:00
parent 08d2ebb1b7
commit 2ef27a9137
14 changed files with 409 additions and 115 deletions

View File

@ -1,47 +1,50 @@
from datetime import datetime, timedelta, timezone
from typing import Annotated
import bcrypt
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jwt.exceptions import InvalidTokenError
from passlib.context import CryptContext
# from passlib.context import CryptContext
from psycopg2._psycopg import connection
import db.users
import settings.settings as settings
import settings.startup_settings as startup_settings
from api.models import TokenData, User
from db.internal import get_db_connection
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def verify_password(plain_password: str, hashed_password: str):
return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8"))
def get_password_hash(password: str):
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
def decode_token(token):
return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
return jwt.decode(token, startup_settings.secret_key, algorithms=[startup_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)
return jwt.encode(payload, startup_settings.secret_key, algorithm=startup_settings.algorithm)
def authenticate_user(
conn: connection,
username: str,
password: str
user_password: str
):
user = User()
userdata = db.users.get_user(conn, username)
if not userdata:
db_user_password = db.users.get_user_password(conn, username)
if not user_password:
return False
if not verify_password(password, user.password):
if not verify_password(user_password, db_user_password):
return False
user.fill(userdata)
return user
return True
def create_access_token(
data: dict,
@ -66,7 +69,6 @@ async def get_current_user(
try:
payload = decode_token(token)
print(payload)
username = payload.get("sub")
if username is None:
raise credentials_exception
@ -75,14 +77,16 @@ async def get_current_user(
raise credentials_exception
user = User()
user.fill(db.users.get_user(conn, username=token_data.username))
if user is None:
user_data = db.users.get_user(conn, token_data.username)
if user_data is None:
raise credentials_exception
user.fill(user_data)
if user.disabled:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Inactive user"
detail="User is disabled"
)
return user