95 lines
1.8 KiB
Python
95 lines
1.8 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
|
|
|
|
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(authorization: str = Header(None)):
|
|
|
|
if authorization is None:
|
|
raise HTTPException(
|
|
status_code=401,
|
|
detail="Missing token"
|
|
)
|
|
|
|
try:
|
|
scheme, token = authorization.split(" ")
|
|
|
|
if scheme.lower() != "bearer":
|
|
raise Exception()
|
|
|
|
payload = jwt.decode(
|
|
token,
|
|
SECRET_KEY,
|
|
algorithms=[ALGORITHM]
|
|
)
|
|
|
|
user_id = payload["user_id"]
|
|
|
|
return user_id
|
|
|
|
except JWTError:
|
|
raise HTTPException(
|
|
status_code=401,
|
|
detail="Invalid token"
|
|
) |