исправлено хеширование паролей
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
42
main.py
42
main.py
@@ -1,10 +1,8 @@
|
|||||||
|
|
||||||
from fastapi import FastAPI, HTTPException, Depends, Request
|
from fastapi import FastAPI, HTTPException, Depends, Request
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
import sqlite3
|
import sqlite3
|
||||||
from passlib.context import CryptContext
|
|
||||||
import uvicorn
|
import uvicorn
|
||||||
from werkzeug.security import generate_password_hash, check_password_hash
|
from werkzeug.security import generate_password_hash, check_password_hash
|
||||||
import jwt
|
import jwt
|
||||||
@@ -16,38 +14,39 @@ app = FastAPI(title="Work BD Auth API",
|
|||||||
|
|
||||||
app.add_middleware(
|
app.add_middleware(
|
||||||
CORSMiddleware,
|
CORSMiddleware,
|
||||||
allow_origins=["http://localhost:5173", "https://allowlgroup.ru"], # или список конкретных доменов
|
allow_origins=[
|
||||||
|
"http://localhost:5173",
|
||||||
|
"https://allowlgroup.ru",
|
||||||
|
],
|
||||||
allow_credentials=True,
|
allow_credentials=True,
|
||||||
allow_methods=["*"],
|
allow_methods=["*"],
|
||||||
allow_headers=["*"],
|
allow_headers=["*"],
|
||||||
)
|
)
|
||||||
|
|
||||||
DB_PATH = 'users.db'
|
DB_PATH = 'users.db'
|
||||||
|
|
||||||
# Инициализация базы данных
|
|
||||||
def init_db():
|
def init_db():
|
||||||
conn = sqlite3.connect(DB_PATH)
|
conn = sqlite3.connect(DB_PATH)
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
|
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
username TEXT UNIQUE NOT NULL,
|
username TEXT UNIQUE NOT NULL,
|
||||||
password TEXT NOT NULL)''')
|
password TEXT NOT NULL)''')
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
init_db()
|
init_db()
|
||||||
|
|
||||||
# Pydantic модель для входящих данных
|
|
||||||
class UserIn(BaseModel):
|
class UserIn(BaseModel):
|
||||||
username: str
|
username: str
|
||||||
password: str
|
password: str
|
||||||
|
|
||||||
|
|
||||||
@app.post('/register', status_code=201, tags=["User"])
|
@app.post('/register', status_code=201, tags=["User"])
|
||||||
async def register(user: UserIn):
|
async def register(user: UserIn):
|
||||||
if not user.username or not user.password:
|
if not user.username or not user.password:
|
||||||
raise HTTPException(status_code=400, detail="Username and password required")
|
raise HTTPException(status_code=400, detail="Username and password required")
|
||||||
|
|
||||||
hashed_password = generate_password_hash(user.password)
|
hashed_password = generate_password_hash(user.password)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
conn = sqlite3.connect(DB_PATH)
|
conn = sqlite3.connect(DB_PATH)
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
@@ -56,22 +55,21 @@ async def register(user: UserIn):
|
|||||||
conn.close()
|
conn.close()
|
||||||
except sqlite3.IntegrityError:
|
except sqlite3.IntegrityError:
|
||||||
raise HTTPException(status_code=400, detail="Username already exists")
|
raise HTTPException(status_code=400, detail="Username already exists")
|
||||||
|
|
||||||
return {"message": "User registered successfully"}
|
return {"message": "User registered successfully"}
|
||||||
|
|
||||||
@app.post('/login', tags=["User"])
|
@app.post('/login', tags=["User"])
|
||||||
async def login(user: UserIn):
|
async def login(user: UserIn):
|
||||||
if not user.username or not user.password:
|
if not user.username or not user.password:
|
||||||
raise HTTPException(status_code=400, detail="Username and password required")
|
raise HTTPException(status_code=400, detail="Username and password required")
|
||||||
|
|
||||||
conn = sqlite3.connect(DB_PATH)
|
conn = sqlite3.connect(DB_PATH)
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute('SELECT password FROM users WHERE username = ?', (user.username,))
|
cursor.execute('SELECT password FROM users WHERE username = ?', (user.username,))
|
||||||
row = cursor.fetchone()
|
row = cursor.fetchone()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
if row and check_password_hash(row[0], user.password):
|
if row and check_password_hash(row[0], user.password):
|
||||||
# Генерация JWT токена
|
|
||||||
token = jwt.encode({
|
token = jwt.encode({
|
||||||
"username": user.username,
|
"username": user.username,
|
||||||
"exp": datetime.datetime.utcnow() + datetime.timedelta(days=30)
|
"exp": datetime.datetime.utcnow() + datetime.timedelta(days=30)
|
||||||
@@ -81,8 +79,8 @@ async def login(user: UserIn):
|
|||||||
response.set_cookie(
|
response.set_cookie(
|
||||||
key="auth_token",
|
key="auth_token",
|
||||||
value=token,
|
value=token,
|
||||||
max_age=30*24*60*60, # 30 дней
|
max_age=30*24*60*60,
|
||||||
httponly=True, # Безопасность
|
httponly=True,
|
||||||
samesite="lax",
|
samesite="lax",
|
||||||
path="/"
|
path="/"
|
||||||
)
|
)
|
||||||
@@ -96,7 +94,7 @@ async def login(user: UserIn):
|
|||||||
return response
|
return response
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=401, detail="Invalid credentials")
|
raise HTTPException(status_code=401, detail="Invalid credentials")
|
||||||
|
|
||||||
@app.get('/users', tags=["User"])
|
@app.get('/users', tags=["User"])
|
||||||
async def get_users():
|
async def get_users():
|
||||||
conn = sqlite3.connect(DB_PATH)
|
conn = sqlite3.connect(DB_PATH)
|
||||||
@@ -104,10 +102,8 @@ async def get_users():
|
|||||||
cursor.execute('SELECT * FROM users')
|
cursor.execute('SELECT * FROM users')
|
||||||
rows = cursor.fetchall()
|
rows = cursor.fetchall()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
|
|
||||||
@app.get('/verify', tags=["User"])
|
@app.get('/verify', tags=["User"])
|
||||||
async def verify_token_endpoint(request: Request):
|
async def verify_token_endpoint(request: Request):
|
||||||
token = request.cookies.get('auth_token')
|
token = request.cookies.get('auth_token')
|
||||||
@@ -126,6 +122,6 @@ async def verify_token_endpoint(request: Request):
|
|||||||
raise HTTPException(status_code=401, detail="Token expired")
|
raise HTTPException(status_code=401, detail="Token expired")
|
||||||
except jwt.InvalidTokenError:
|
except jwt.InvalidTokenError:
|
||||||
raise HTTPException(status_code=401, detail="Invalid token")
|
raise HTTPException(status_code=401, detail="Invalid token")
|
||||||
# # Запуск сервера для теста
|
|
||||||
# if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# uvicorn.run("main:app", port=8004, reload=True)
|
uvicorn.run("main:app", host="0.0.0.0", port=8004, reload=True)
|
||||||
Reference in New Issue
Block a user