Кучу всякого, но основная цель сейчас, это сделать выгрузку и загрузку файлов номральную
This commit is contained in:
parent
5b42813934
commit
ee7c78e1c8
0
fastapi-app-upload/database/models/csv_file.py
Normal file
0
fastapi-app-upload/database/models/csv_file.py
Normal file
0
fastapi-app-upload/database/models/h5_model.py
Normal file
0
fastapi-app-upload/database/models/h5_model.py
Normal file
0
fastapi-app-upload/database/models/user.py
Normal file
0
fastapi-app-upload/database/models/user.py
Normal file
9
fastapi-app-upload/repositories/csv_file_repository.py
Normal file
9
fastapi-app-upload/repositories/csv_file_repository.py
Normal file
@ -0,0 +1,9 @@
|
||||
from database.database import new_session, CSVFile
|
||||
|
||||
class CSVFileRepository:
|
||||
@staticmethod
|
||||
async def upload_file(user_id: int, file_path: str):
|
||||
async with new_session() as session:
|
||||
csv_file = CSVFile(user_id=user_id, file_path=file_path)
|
||||
session.add(csv_file)
|
||||
await session.commit()
|
8
fastapi-app-upload/repositories/h5_model_repository.py
Normal file
8
fastapi-app-upload/repositories/h5_model_repository.py
Normal file
@ -0,0 +1,8 @@
|
||||
from database.database import new_session, H5Model
|
||||
class H5ModelRepository:
|
||||
@staticmethod
|
||||
async def add_model(user_id: int, model_path: str):
|
||||
async with new_session() as session:
|
||||
model = H5Model(user_id=user_id, model_path=model_path)
|
||||
session.add(model)
|
||||
await session.commit()
|
@ -0,0 +1,11 @@
|
||||
from database.database import new_session, ModelStatistics
|
||||
from schemas.model_statistics_create import ModelStatisticsCreate
|
||||
|
||||
|
||||
class ModelStatisticsRepository:
|
||||
@staticmethod
|
||||
async def add_statistics(data: ModelStatisticsCreate):
|
||||
async with new_session() as session:
|
||||
stats = ModelStatistics(**data.model_dump())
|
||||
session.add(stats)
|
||||
await session.commit()
|
12
fastapi-app-upload/repositories/user_repository.py
Normal file
12
fastapi-app-upload/repositories/user_repository.py
Normal file
@ -0,0 +1,12 @@
|
||||
from database.database import new_session, User
|
||||
from schemas.user_create import UserCreate
|
||||
|
||||
|
||||
class UserRepository:
|
||||
@staticmethod
|
||||
async def create_user(data: UserCreate):
|
||||
async with new_session() as session:
|
||||
user = User(username=data.username, password_hash=data.password)
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
return user.id
|
7
fastapi-app-upload/schemas/csv_file_upload.py
Normal file
7
fastapi-app-upload/schemas/csv_file_upload.py
Normal file
@ -0,0 +1,7 @@
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
# CSVFileUpload: для загрузки CSV файла
|
||||
class CSVFileUpload(BaseModel):
|
||||
file_path: str
|
7
fastapi-app-upload/schemas/h5_model_create.py
Normal file
7
fastapi-app-upload/schemas/h5_model_create.py
Normal file
@ -0,0 +1,7 @@
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
# H5ModelCreate: для добавления модели
|
||||
class H5ModelCreate(BaseModel):
|
||||
path_model: str
|
10
fastapi-app-upload/schemas/model_statistics_create.py
Normal file
10
fastapi-app-upload/schemas/model_statistics_create.py
Normal file
@ -0,0 +1,10 @@
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
# ModelStatisticsCreate: для сохранения статистики модели
|
||||
class ModelStatisticsCreate(BaseModel):
|
||||
id_model: int
|
||||
accuracy: float
|
||||
loss: float
|
||||
created_at: Optional[datetime] = None
|
8
fastapi-app-upload/schemas/user_create.py
Normal file
8
fastapi-app-upload/schemas/user_create.py
Normal file
@ -0,0 +1,8 @@
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
# UserCreate: для создания пользователя
|
||||
class UserCreate(BaseModel):
|
||||
username: str
|
||||
password: str
|
Binary file not shown.
0
file-upload/.env
Normal file
0
file-upload/.env
Normal file
0
file-upload/Dockerfile
Normal file
0
file-upload/Dockerfile
Normal file
BIN
file-upload/README.md
Normal file
BIN
file-upload/README.md
Normal file
Binary file not shown.
0
file-upload/app/api/endpoints/auth.py
Normal file
0
file-upload/app/api/endpoints/auth.py
Normal file
0
file-upload/app/api/endpoints/edit.py
Normal file
0
file-upload/app/api/endpoints/edit.py
Normal file
35
file-upload/app/api/endpoints/upload.py
Normal file
35
file-upload/app/api/endpoints/upload.py
Normal file
@ -0,0 +1,35 @@
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from fastapi import APIRouter, UploadFile, File, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.db.database import get_db
|
||||
from app.db.models import File as FileModel
|
||||
from app.db.crud import save_file_metadata
|
||||
|
||||
router = APIRouter()
|
||||
STORAGE_PATH = Path("storage")
|
||||
STORAGE_PATH.mkdir(exist_ok=True) # Создаем папку, если её нет
|
||||
|
||||
|
||||
@router.post("/upload/")
|
||||
async def upload_file(file: UploadFile = File(...), db: AsyncSession = Depends(get_db)):
|
||||
file_path = STORAGE_PATH / file.filename
|
||||
|
||||
# Проверяем, существует ли файл
|
||||
if file_path.exists():
|
||||
raise HTTPException(status_code=400, detail="Файл с таким именем уже существует")
|
||||
|
||||
# Сохраняем файл на диск
|
||||
with file_path.open("wb") as buffer:
|
||||
shutil.copyfileobj(file.file, buffer)
|
||||
|
||||
# Сохраняем метаданные файла в БД
|
||||
file_metadata = await save_file_metadata(
|
||||
db=db,
|
||||
filename=file.filename,
|
||||
filepath=str(file_path),
|
||||
content_type=file.content_type,
|
||||
size=file_path.stat().st_size
|
||||
)
|
||||
|
||||
return {"message": "Файл успешно загружен", "file_id": file_metadata.id}
|
0
file-upload/app/api/endpoints/view.py
Normal file
0
file-upload/app/api/endpoints/view.py
Normal file
0
file-upload/app/core/config.py
Normal file
0
file-upload/app/core/config.py
Normal file
0
file-upload/app/core/security.py
Normal file
0
file-upload/app/core/security.py
Normal file
11
file-upload/app/db/crud.py
Normal file
11
file-upload/app/db/crud.py
Normal file
@ -0,0 +1,11 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from app.db.models import File
|
||||
|
||||
|
||||
async def save_file_metadata(db: AsyncSession, filename: str, filepath: str, content_type: str, size: int):
|
||||
new_file = File(filename=filename, filepath=filepath, content_type=content_type, size=size)
|
||||
db.add(new_file)
|
||||
await db.commit()
|
||||
await db.refresh(new_file)
|
||||
return new_file
|
0
file-upload/app/db/database.py
Normal file
0
file-upload/app/db/database.py
Normal file
15
file-upload/app/db/models.py
Normal file
15
file-upload/app/db/models.py
Normal file
@ -0,0 +1,15 @@
|
||||
from sqlalchemy import Column, Integer, String, DateTime, func
|
||||
from sqlalchemy.orm import declarative_base
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class File(Base):
|
||||
__tablename__ = "files"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
filename = Column(String, nullable=False)
|
||||
filepath = Column(String, unique=True, nullable=False) # Путь к файлу на диске
|
||||
content_type = Column(String, nullable=False) # MIME-тип файла
|
||||
size = Column(Integer, nullable=False) # Размер файла в байтах
|
||||
uploaded_at = Column(DateTime, server_default=func.now()) # Дата загрузки
|
12
file-upload/app/main.py
Normal file
12
file-upload/app/main.py
Normal file
@ -0,0 +1,12 @@
|
||||
from fastapi import FastAPI
|
||||
from app.api.endpoints import upload
|
||||
|
||||
app = FastAPI(title="File Manager API")
|
||||
|
||||
# Подключаем роутер для загрузки файлов
|
||||
app.include_router(upload.router, prefix="/files", tags=["Files"])
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def read_root():
|
||||
return {"message": "File Manager API is running"}
|
0
file-upload/app/schemas/file.py
Normal file
0
file-upload/app/schemas/file.py
Normal file
0
file-upload/app/services/file_service.py
Normal file
0
file-upload/app/services/file_service.py
Normal file
0
file-upload/docker-compose.yml
Normal file
0
file-upload/docker-compose.yml
Normal file
1
file-upload/hello.py
Normal file
1
file-upload/hello.py
Normal file
@ -0,0 +1 @@
|
||||
print(123)
|
7
file-upload/requirements.txt
Normal file
7
file-upload/requirements.txt
Normal file
@ -0,0 +1,7 @@
|
||||
fastapi==0.110.0 # FastAPI с поддержкой всех зависимостей
|
||||
uvicorn==0.29.0 # ASGI-сервер для FastAPI
|
||||
SQLAlchemy==2.0.29 # ORM для работы с PostgreSQL
|
||||
asyncpg==0.29.0 # Асинхронный драйвер PostgreSQL
|
||||
alembic==1.13.1 # Миграции базы данных
|
||||
pydantic==2.6.3 # Валидация данных
|
||||
python-multipart==0.0.9 # Поддержка загрузки файлов через multipart/form-data
|
0
file-upload/tests/test_edit.py
Normal file
0
file-upload/tests/test_edit.py
Normal file
0
file-upload/tests/test_upload.py
Normal file
0
file-upload/tests/test_upload.py
Normal file
0
file-upload/tests/test_view.py
Normal file
0
file-upload/tests/test_view.py
Normal file
@ -1,114 +1,134 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"log"
|
||||
"main/database"
|
||||
"main/models"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
// Глобальная переменная для хранения ключа
|
||||
var SecretKey string
|
||||
var (
|
||||
SecretKey string
|
||||
blockedTokens = make(map[string]struct{})
|
||||
blockedTokensMu sync.Mutex
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Загружаем .env файл
|
||||
err := godotenv.Load()
|
||||
if err != nil {
|
||||
if err := godotenv.Load(); err != nil {
|
||||
log.Fatal("Ошибка загрузки .env файла")
|
||||
}
|
||||
|
||||
// Читаем ключ из переменной окружения
|
||||
SecretKey = os.Getenv("JWT_SECRET_KEY")
|
||||
if SecretKey == "" {
|
||||
log.Fatal("JWT_SECRET_KEY не задан в .env")
|
||||
}
|
||||
}
|
||||
|
||||
// Регистрируем пользователя
|
||||
func Register(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
return err
|
||||
log.Println("Ошибка парсинга тела запроса:", err)
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "Invalid request body"})
|
||||
}
|
||||
|
||||
if data["password"] == "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "Password is required"})
|
||||
}
|
||||
|
||||
// Проверка на существующего пользователя
|
||||
var existingUser models.User
|
||||
if err := database.DB.Where("email = ?", data["email"]).First(&existingUser).Error; err == nil {
|
||||
return c.Status(fiber.StatusConflict).JSON(fiber.Map{"message": "Email already taken"})
|
||||
}
|
||||
|
||||
password, _ := bcrypt.GenerateFromPassword([]byte(data["password"]), bcrypt.DefaultCost)
|
||||
passwordHash, err := bcrypt.GenerateFromPassword([]byte(data["password"]), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
log.Println("Ошибка хеширования пароля:", err)
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Could not process password"})
|
||||
}
|
||||
|
||||
user := models.User{
|
||||
Name: data["name"],
|
||||
Email: data["email"],
|
||||
Password: password,
|
||||
Password: passwordHash,
|
||||
}
|
||||
|
||||
database.DB.Create(&user)
|
||||
|
||||
log.Println("Пользователь зарегистрирован:", user.Email)
|
||||
return c.JSON(user)
|
||||
}
|
||||
|
||||
// Генерация JWT-токена
|
||||
func generateToken(user models.User) (string, error) {
|
||||
claims := jwt.MapClaims{
|
||||
"user_id": user.Id,
|
||||
"exp": time.Now().Add(time.Hour * 24).Unix(), // Токен на 24 часа
|
||||
"exp": time.Now().Add(time.Hour * 24).Unix(),
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(SecretKey))
|
||||
}
|
||||
|
||||
func isTokenBlocked(token string) bool {
|
||||
blockedTokensMu.Lock()
|
||||
defer blockedTokensMu.Unlock()
|
||||
_, exists := blockedTokens[token]
|
||||
return exists
|
||||
}
|
||||
|
||||
func blockToken(token string) {
|
||||
blockedTokensMu.Lock()
|
||||
defer blockedTokensMu.Unlock()
|
||||
blockedTokens[token] = struct{}{}
|
||||
}
|
||||
|
||||
func Login(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
return err
|
||||
log.Println("Ошибка парсинга тела запроса:", err)
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "Invalid request body"})
|
||||
}
|
||||
|
||||
// Найти пользователя по email
|
||||
var user models.User
|
||||
database.DB.Where("email = ?", data["email"]).First(&user)
|
||||
if user.Id == 0 {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Invalid email or password"})
|
||||
}
|
||||
|
||||
// Проверяем пароль
|
||||
if err := bcrypt.CompareHashAndPassword(user.Password, []byte(data["password"])); err != nil {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Invalid email or password"})
|
||||
}
|
||||
|
||||
// Генерируем токен
|
||||
token, err := generateToken(user)
|
||||
if err != nil {
|
||||
log.Println("Ошибка генерации JWT токена:", err)
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Could not generate token"})
|
||||
}
|
||||
|
||||
// Сохраняем токен в cookie
|
||||
c.Cookie(&fiber.Cookie{
|
||||
Name: "jwt",
|
||||
Value: token,
|
||||
Expires: time.Now().Add(time.Hour * 24),
|
||||
HTTPOnly: true,
|
||||
Secure: true,
|
||||
SameSite: "Strict",
|
||||
})
|
||||
|
||||
log.Println("Пользователь вошел в систему:", user.Email)
|
||||
return c.JSON(fiber.Map{"message": "Login successful"})
|
||||
}
|
||||
|
||||
// Получаем пользователя по токену
|
||||
func User(c *fiber.Ctx) error {
|
||||
cookie := c.Cookies("jwt")
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
if isTokenBlocked(cookie) {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Token is blocked"})
|
||||
}
|
||||
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(SecretKey), nil
|
||||
})
|
||||
|
||||
@ -116,28 +136,33 @@ func User(c *fiber.Ctx) error {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
|
||||
}
|
||||
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
if claims.ExpiresAt < time.Now().Unix() {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Token expired"})
|
||||
claims, ok := token.Claims.(*jwt.MapClaims)
|
||||
if !ok || !token.Valid {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Invalid token"})
|
||||
}
|
||||
|
||||
var user models.User
|
||||
database.DB.Where("id = ?", claims.Issuer).First(&user)
|
||||
database.DB.Where("id = ?", (*claims)["user_id"]).First(&user)
|
||||
if user.Id == 0 {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "User not found"})
|
||||
}
|
||||
|
||||
return c.JSON(user)
|
||||
}
|
||||
|
||||
// Логаут
|
||||
func Logout(c *fiber.Ctx) error {
|
||||
cookie := fiber.Cookie{
|
||||
cookie := c.Cookies("jwt")
|
||||
blockToken(cookie)
|
||||
|
||||
c.Cookie(&fiber.Cookie{
|
||||
Name: "jwt",
|
||||
Value: "",
|
||||
Expires: time.Now().Add(-time.Hour),
|
||||
HTTPOnly: true,
|
||||
Secure: true,
|
||||
SameSite: "Strict",
|
||||
}
|
||||
})
|
||||
|
||||
c.Cookie(&cookie)
|
||||
|
||||
return c.JSON(fiber.Map{"message": "Logout success"})
|
||||
log.Println("Пользователь вышел из системы")
|
||||
return c.JSON(fiber.Map{"message": "Logout successful"})
|
||||
}
|
||||
|
@ -4,10 +4,11 @@ go 1.24.0
|
||||
|
||||
require (
|
||||
github.com/gofiber/fiber/v2 v2.52.6
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1
|
||||
github.com/joho/godotenv v1.5.1
|
||||
golang.org/x/crypto v0.34.0
|
||||
golang.org/x/crypto v0.36.0
|
||||
gorm.io/driver/postgres v1.5.11
|
||||
gorm.io/driver/sqlite v1.5.7
|
||||
gorm.io/gorm v1.25.12
|
||||
)
|
||||
|
||||
@ -24,11 +25,12 @@ require (
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||
github.com/rivo/uniseg v0.2.0 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.51.0 // indirect
|
||||
github.com/valyala/tcplisten v1.0.0 // indirect
|
||||
golang.org/x/sync v0.11.0 // indirect
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
golang.org/x/text v0.22.0 // indirect
|
||||
golang.org/x/sync v0.12.0 // indirect
|
||||
golang.org/x/sys v0.31.0 // indirect
|
||||
golang.org/x/text v0.23.0 // indirect
|
||||
)
|
||||
|
@ -5,8 +5,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gofiber/fiber/v2 v2.52.6 h1:Rfp+ILPiYSvvVuIPvxrBns+HJp8qGLDnLJawAu27XVI=
|
||||
github.com/gofiber/fiber/v2 v2.52.6/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1 h1:JdqV9zKUdtaa9gdPlywC3aeoEsR681PlKC+4F5gQgeo=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
@ -32,6 +32,8 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
@ -47,21 +49,23 @@ github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1S
|
||||
github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
|
||||
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
|
||||
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
||||
golang.org/x/crypto v0.34.0 h1:+/C6tk6rf/+t5DhUketUbD1aNGqiSX3j15Z6xuIDlBA=
|
||||
golang.org/x/crypto v0.34.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ=
|
||||
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
|
||||
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
|
||||
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
|
||||
golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
|
||||
golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
|
||||
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
|
||||
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/postgres v1.5.11 h1:ubBVAfbKEUld/twyKZ0IYn9rSQh448EdelLYk9Mv314=
|
||||
gorm.io/driver/postgres v1.5.11/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
|
||||
gorm.io/driver/sqlite v1.5.7 h1:8NvsrhP0ifM7LX9G4zPB97NwovUakUxc+2V2uuf3Z1I=
|
||||
gorm.io/driver/sqlite v1.5.7/go.mod h1:U+J8craQU6Fzkcvu8oLeAQmi50TkwPEhHDEjQZXDah4=
|
||||
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
|
||||
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
|
||||
|
211
go-auth/main.go
211
go-auth/main.go
@ -1,32 +1,207 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||
"github.com/joho/godotenv"
|
||||
"log"
|
||||
"main/database"
|
||||
"main/routes"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Модель пользователя
|
||||
type User struct {
|
||||
Id uint `json:"id" gorm:"primaryKey"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email" gorm:"unique"`
|
||||
Password []byte `json:"-"`
|
||||
}
|
||||
|
||||
// Загружаем .env
|
||||
err := godotenv.Load()
|
||||
if err != nil {
|
||||
log.Fatal("Ошибка загрузки .env")
|
||||
// Глобальные переменные
|
||||
var (
|
||||
DB *gorm.DB
|
||||
SecretKey string
|
||||
blockedTokens = make(map[string]struct{})
|
||||
blockedTokensMu sync.Mutex
|
||||
)
|
||||
|
||||
// Инициализация базы данных и загрузка переменных окружения
|
||||
func init() {
|
||||
if err := godotenv.Load(); err != nil {
|
||||
log.Fatal("Ошибка загрузки .env файла")
|
||||
}
|
||||
|
||||
database.Connect()
|
||||
SecretKey = os.Getenv("JWT_SECRET_KEY")
|
||||
if SecretKey == "" {
|
||||
log.Fatal("JWT_SECRET_KEY не задан в .env")
|
||||
}
|
||||
|
||||
var err error
|
||||
DB, err = gorm.Open(sqlite.Open("users.db"), &gorm.Config{})
|
||||
if err != nil {
|
||||
log.Fatal("Ошибка подключения к базе данных:", err)
|
||||
}
|
||||
DB.AutoMigrate(&User{})
|
||||
}
|
||||
|
||||
// Генерация JWT-токена
|
||||
func generateToken(user User) (string, error) {
|
||||
claims := jwt.MapClaims{
|
||||
"user_id": user.Id,
|
||||
"exp": time.Now().Add(time.Hour * 24).Unix(),
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(SecretKey))
|
||||
}
|
||||
|
||||
// Проверка заблокированного токена
|
||||
func isTokenBlocked(token string) bool {
|
||||
blockedTokensMu.Lock()
|
||||
defer blockedTokensMu.Unlock()
|
||||
_, exists := blockedTokens[token]
|
||||
return exists
|
||||
}
|
||||
|
||||
// Блокировка токена при выходе
|
||||
func blockToken(token string) {
|
||||
blockedTokensMu.Lock()
|
||||
defer blockedTokensMu.Unlock()
|
||||
blockedTokens[token] = struct{}{}
|
||||
}
|
||||
|
||||
// Регистрация пользователя
|
||||
func Register(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
log.Println("Ошибка парсинга запроса:", err)
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "Invalid request body"})
|
||||
}
|
||||
|
||||
if data["password"] == "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "Password is required"})
|
||||
}
|
||||
|
||||
var existingUser User
|
||||
if err := DB.Where("email = ?", data["email"]).First(&existingUser).Error; err == nil {
|
||||
return c.Status(fiber.StatusConflict).JSON(fiber.Map{"message": "Email already taken"})
|
||||
}
|
||||
|
||||
passwordHash, err := bcrypt.GenerateFromPassword([]byte(data["password"]), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
log.Println("Ошибка хеширования пароля:", err)
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Could not process password"})
|
||||
}
|
||||
|
||||
user := User{
|
||||
Name: data["name"],
|
||||
Email: data["email"],
|
||||
Password: passwordHash,
|
||||
}
|
||||
DB.Create(&user)
|
||||
|
||||
log.Println("Пользователь зарегистрирован:", user.Email)
|
||||
return c.JSON(user)
|
||||
}
|
||||
|
||||
// Логин пользователя
|
||||
func Login(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
log.Println("Ошибка парсинга запроса:", err)
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "Invalid request body"})
|
||||
}
|
||||
|
||||
var user User
|
||||
DB.Where("email = ?", data["email"]).First(&user)
|
||||
if user.Id == 0 {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Invalid email or password"})
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword(user.Password, []byte(data["password"])); err != nil {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Invalid email or password"})
|
||||
}
|
||||
|
||||
token, err := generateToken(user)
|
||||
if err != nil {
|
||||
log.Println("Ошибка генерации JWT токена:", err)
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Could not generate token"})
|
||||
}
|
||||
|
||||
c.Cookie(&fiber.Cookie{
|
||||
Name: "jwt",
|
||||
Value: token,
|
||||
Expires: time.Now().Add(time.Hour * 24),
|
||||
HTTPOnly: true,
|
||||
Secure: true,
|
||||
SameSite: "Strict",
|
||||
})
|
||||
|
||||
log.Println("Пользователь вошел в систему:", user.Email)
|
||||
return c.JSON(fiber.Map{"message": "Login successful"})
|
||||
}
|
||||
|
||||
// Получение информации о пользователе
|
||||
func UserInfo(c *fiber.Ctx) error {
|
||||
cookie := c.Cookies("jwt")
|
||||
if isTokenBlocked(cookie) {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Token is blocked"})
|
||||
}
|
||||
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(SecretKey), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*jwt.MapClaims)
|
||||
if !ok || !token.Valid {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Invalid token"})
|
||||
}
|
||||
|
||||
var user User
|
||||
DB.Where("id = ?", (*claims)["user_id"]).First(&user)
|
||||
if user.Id == 0 {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "User not found"})
|
||||
}
|
||||
|
||||
return c.JSON(user)
|
||||
}
|
||||
|
||||
// Выход пользователя
|
||||
func Logout(c *fiber.Ctx) error {
|
||||
cookie := c.Cookies("jwt")
|
||||
blockToken(cookie)
|
||||
|
||||
c.Cookie(&fiber.Cookie{
|
||||
Name: "jwt",
|
||||
Value: "",
|
||||
Expires: time.Now().Add(-time.Hour),
|
||||
HTTPOnly: true,
|
||||
Secure: true,
|
||||
SameSite: "Strict",
|
||||
})
|
||||
|
||||
log.Println("Пользователь вышел из системы")
|
||||
return c.JSON(fiber.Map{"message": "Logout successful"})
|
||||
}
|
||||
|
||||
// Запуск приложения и маршрутизация
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Use(cors.New(cors.Config{
|
||||
AllowCredentials: true,
|
||||
AllowOrigins: "http://localhost:5173/",
|
||||
}))
|
||||
app.Post("/register", Register)
|
||||
app.Post("/login", Login)
|
||||
app.Get("/user", UserInfo)
|
||||
app.Post("/logout", Logout)
|
||||
|
||||
routes.Setup(app)
|
||||
|
||||
app.Listen(":8000")
|
||||
log.Println("Сервер запущен на порту 3000")
|
||||
log.Fatal(app.Listen(":3000"))
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user