added authorization
This commit is contained in:
36
database.py
36
database.py
@@ -1,6 +1,7 @@
|
|||||||
from models import User
|
from models import User
|
||||||
from passlib.context import CryptContext
|
from passlib.context import CryptContext
|
||||||
from settings import settings
|
from settings import settings
|
||||||
|
from fastapi import HTTPException, status, Request
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import jwt
|
import jwt
|
||||||
import datetime
|
import datetime
|
||||||
@@ -30,14 +31,45 @@ def register(user: User) -> None:
|
|||||||
cursor.execute("INSERT INTO users (name, password) VALUES (?, ?)", (user.name, password))
|
cursor.execute("INSERT INTO users (name, password) VALUES (?, ?)", (user.name, password))
|
||||||
connection.commit()
|
connection.commit()
|
||||||
|
|
||||||
|
def get_user_by_token(request: Request) -> User:
|
||||||
|
token = request.headers.get("Authorization")
|
||||||
|
if not token or not token.startswith("Bearer "):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Not authenticated"
|
||||||
|
)
|
||||||
|
token = token.split(" ")[1]
|
||||||
|
payload = jwt.decode(token, key=settings.jwt_secret, algorithms=[settings.jwt_algorithm])
|
||||||
|
|
||||||
|
connection = sqlite3.connect('database.db')
|
||||||
|
connection.row_factory = sqlite3.Row
|
||||||
|
cursor = connection.cursor()
|
||||||
|
cursor.execute("SELECT id, name, password FROM users WHERE id = ?", (payload["id"],))
|
||||||
|
row = cursor.fetchone()
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Not authenticated"
|
||||||
|
)
|
||||||
|
|
||||||
|
return User(**row)
|
||||||
|
|
||||||
def login(user: User) -> str:
|
def login(user: User) -> str:
|
||||||
cursor.execute("SELECT id, name, password FROM users WHERE name = ?", (user.name,))
|
cursor.execute("SELECT id, name, password FROM users WHERE name = ?", (user.name,))
|
||||||
row = cursor.fetchone()
|
row = cursor.fetchone()
|
||||||
|
|
||||||
if not row:
|
if not row:
|
||||||
raise Exception('User not found')
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid credentials"
|
||||||
|
)
|
||||||
if not password_context.verify(user.password, row["password"]):
|
if not password_context.verify(user.password, row["password"]):
|
||||||
raise Exception('Invalid password')
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid credentials"
|
||||||
|
)
|
||||||
|
|
||||||
exp = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1)
|
exp = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1)
|
||||||
payload = {
|
payload = {
|
||||||
|
|||||||
6
main.py
6
main.py
@@ -1,4 +1,4 @@
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI, Depends
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
import database
|
import database
|
||||||
import models
|
import models
|
||||||
@@ -16,6 +16,10 @@ app = FastAPI(lifespan=lifespan)
|
|||||||
async def root():
|
async def root():
|
||||||
return {"message": "Hello World"}
|
return {"message": "Hello World"}
|
||||||
|
|
||||||
|
@app.get("/me")
|
||||||
|
async def me(user: models.User = Depends(database.get_user_by_token)):
|
||||||
|
return user
|
||||||
|
|
||||||
@app.post("/users")
|
@app.post("/users")
|
||||||
async def register(user: models.User):
|
async def register(user: models.User):
|
||||||
database.register(user)
|
database.register(user)
|
||||||
|
|||||||
Reference in New Issue
Block a user