This commit is contained in:
33
main.py
33
main.py
@@ -1,11 +1,14 @@
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Depends
|
||||
from fastapi.middleware.cors import CORSMiddleware # <-- добавлено
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from pydantic import BaseModel
|
||||
import sqlite3
|
||||
from passlib.context import CryptContext
|
||||
import uvicorn
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
import jwt
|
||||
import datetime
|
||||
|
||||
app = FastAPI(title="Work BD Auth API",
|
||||
description="API для авторизации и регистрации",
|
||||
@@ -58,7 +61,6 @@ async def register(user: UserIn):
|
||||
|
||||
@app.post('/login', tags=["User"])
|
||||
async def login(user: UserIn):
|
||||
print(user)
|
||||
if not user.username or not user.password:
|
||||
raise HTTPException(status_code=400, detail="Username and password required")
|
||||
|
||||
@@ -69,10 +71,31 @@ async def login(user: UserIn):
|
||||
conn.close()
|
||||
|
||||
if row and check_password_hash(row[0], user.password):
|
||||
return {"message": "Login successful"}
|
||||
# Генерация JWT токена
|
||||
token = jwt.encode({
|
||||
"username": user.username,
|
||||
"exp": datetime.datetime.utcnow() + datetime.timedelta(days=30)
|
||||
}, "95ad4fb1f2612c41ed299d5ca695945890c957fa", algorithm="HS256")
|
||||
|
||||
response = JSONResponse(content={"message": "Login successful", "token": token})
|
||||
response.set_cookie(
|
||||
key="auth_token",
|
||||
value=token,
|
||||
max_age=30*24*60*60, # 30 дней
|
||||
httponly=True, # Безопасность
|
||||
samesite="lax",
|
||||
path="/"
|
||||
)
|
||||
response.set_cookie(
|
||||
key="username",
|
||||
value=user.username,
|
||||
max_age=30*24*60*60,
|
||||
samesite="lax",
|
||||
path="/"
|
||||
)
|
||||
return response
|
||||
else:
|
||||
# raise HTTPException(status_code=401, detail="Invalid credentials")
|
||||
return {"message": "successful"}
|
||||
raise HTTPException(status_code=401, detail="Invalid credentials")
|
||||
|
||||
@app.get('/users', tags=["User"])
|
||||
async def get_users():
|
||||
|
||||
Reference in New Issue
Block a user