From c73849ad7010ba1ed62bda342958b4dc08a0c85f Mon Sep 17 00:00:00 2001 From: Ernest Litvinenko Date: Sat, 28 Oct 2023 08:45:19 +0300 Subject: [PATCH] Init --- .gitignore | 8 ++++++ main.py | 77 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 .gitignore create mode 100644 main.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..17ebb69 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +venv/ +.idea/ +*.pyc +__pycache__ +*.egg-info/ +build/ +dist/ +*.egg \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..013ddb4 --- /dev/null +++ b/main.py @@ -0,0 +1,77 @@ +from datetime import datetime, timedelta +from pydantic import BaseModel + +import asyncpg +from fastapi import FastAPI, Depends, HTTPException +import jwt +from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm + +SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" +POSTGRES_URL = 'postgresql://amonic:amonic123@92.53.120.110:5432/amonic' +ALGORITHM = "HS256" +ACCESS_TOKEN_EXPIRE_MINUTES = 30 + +app = FastAPI(title="AMONIC API", version='0.0.1') +db: asyncpg.connection.Connection | None = None + + +class UserDB(BaseModel): + id: int | None + roleid: int | None + email: str | None + password: str | None + firstname: str | None + lastname: str | None + officeid: int | None + birthdate: datetime | None + active: bool | None + + +@app.on_event('startup') +async def startup(): + global db + db = await asyncpg.connect(POSTGRES_URL) + + +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/login") + + +async def get_current_user(token: str = Depends(oauth2_scheme)): + token = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + sql = """ + select * from users where email= $1 + """ + row = await db.fetchrow(sql, token['sub']) + if row is None: + raise HTTPException( + status_code=404, + detail="User not found" + ) + return UserDB.model_validate(dict(row)) + + +@app.post('/login') +async def login(user_data: OAuth2PasswordRequestForm = Depends()): + sql = """ + select * from users where email= $1 and password = md5($2) + """ + row = await db.fetchrow(sql, user_data.username, user_data.password) + if row is None: + raise HTTPException( + status_code=401, + detail="Incorrect username or password" + ) + payload = { + "sub": user_data.username, + "exp": datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) + } + token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) + return {"access_token": token, "token_type": "bearer"} + + +@app.get('/current-user') +async def profiles(user: UserDB = Depends(get_current_user)): + return user + +# @app.get('/profiles') +# async def ():