91 lines
1.7 KiB
Python
91 lines
1.7 KiB
Python
from database import execute, fetch_one
|
|
import bcrypt
|
|
from jose import jwt, JWTError
|
|
from datetime import datetime, timedelta
|
|
from fastapi import Header, HTTPException
|
|
from dotenv import load_dotenv
|
|
import os
|
|
from fastapi import Depends, HTTPException
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
|
|
security = HTTPBearer()
|
|
load_dotenv()
|
|
|
|
SECRET_KEY = os.getenv("SECRET_KEY")
|
|
ALGORITHM = "HS256"
|
|
|
|
|
|
def create_token(user_id):
|
|
payload = {
|
|
"user_id": user_id,
|
|
"exp": datetime.utcnow() + timedelta(hours=24)
|
|
}
|
|
|
|
token = jwt.encode(
|
|
payload,
|
|
SECRET_KEY,
|
|
algorithm=ALGORITHM
|
|
)
|
|
|
|
return token
|
|
|
|
|
|
def create_user(username, password):
|
|
|
|
password_hash = bcrypt.hashpw(
|
|
password.encode(),
|
|
bcrypt.gensalt()
|
|
).decode()
|
|
|
|
user_id = execute(
|
|
"""
|
|
INSERT INTO users (username, password_hash)
|
|
VALUES (?, ?)
|
|
""",
|
|
(username, password_hash)
|
|
)
|
|
|
|
return user_id
|
|
|
|
|
|
def verify_user(username, password):
|
|
|
|
user = fetch_one(
|
|
"SELECT * FROM users WHERE username = ?",
|
|
(username,)
|
|
)
|
|
|
|
if not user:
|
|
return None
|
|
|
|
if bcrypt.checkpw(
|
|
password.encode(),
|
|
user["password_hash"].encode()
|
|
):
|
|
return user["id"]
|
|
|
|
return None
|
|
|
|
|
|
def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials = Depends(security)
|
|
):
|
|
token = credentials.credentials
|
|
|
|
payload = jwt.decode(
|
|
token,
|
|
SECRET_KEY,
|
|
algorithms=[ALGORITHM]
|
|
)
|
|
|
|
return payload["user_id"]
|
|
|
|
def get_user(user_id):
|
|
return fetch_one(
|
|
"""
|
|
SELECT id, username
|
|
FROM users
|
|
WHERE id = ?
|
|
""",
|
|
(user_id,)
|
|
) |