diff --git a/frontend/style/app/login/login.go b/frontend/style/app/login/login.go deleted file mode 100644 index c247770a..00000000 --- a/frontend/style/app/login/login.go +++ /dev/null @@ -1,100 +0,0 @@ -package main - -import ( - "database/sql" - "encoding/json" - "fmt" - "log" - "net/http" - "os" - - "github.com/gorilla/handlers" - _ "github.com/mattn/go-sqlite3" -) - -type User struct { - ID int `json:"id"` - Email string `json:"email"` - Password string `json:"password"` -} - -var db *sql.DB - -func initDB() { - var err error - dbFile := "users.db" - db, err = sql.Open("sqlite3", dbFile) - if err != nil { - log.Fatal("Ошибка подключения к базе данных:", err) - } - fmt.Println("База данных готова к работе.") -} - -func loginHandler(w http.ResponseWriter, r *http.Request) { - log.Printf("Received request with method: %s", r.Method) - if r.Method != http.MethodPost { - http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed) - return - } - - var user User - if err := json.NewDecoder(r.Body).Decode(&user); err != nil { - http.Error(w, "Ошибка обработки JSON", http.StatusBadRequest) - return - } - - // Check if the email and password are provided - if user.Email == "" || user.Password == "" { - http.Error(w, "Email и пароль обязательны", http.StatusBadRequest) - return - } - - // Query the database to check if the user exists - query := `SELECT id, email, password FROM users WHERE email = ?` - var dbUser User - err := db.QueryRow(query, user.Email).Scan(&dbUser.ID, &dbUser.Email, &dbUser.Password) - if err != nil { - if err == sql.ErrNoRows { - // Если пользователь не найден, просим зарегистрироваться - w.WriteHeader(http.StatusNotFound) - json.NewEncoder(w).Encode(map[string]string{"message": "Пользователь не найден. Пожалуйста, зарегистрируйтесь."}) - } else { - http.Error(w, "Ошибка при проверке учетных данных", http.StatusInternalServerError) - } - return - } - - // Если пользователь найден, проверяем пароль - if user.Password != dbUser.Password { - http.Error(w, "Неверный пароль", http.StatusUnauthorized) - return - } - - // Если пароль совпадает, вход успешен - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(map[string]string{"message": "Вход успешен", "email": dbUser.Email}) -} - -func main() { - initDB() - defer db.Close() - - // Setup CORS - cors := handlers.CORS( - handlers.AllowedOrigins([]string{"*"}), - handlers.AllowedMethods([]string{"GET", "POST"}), - handlers.AllowedHeaders([]string{"Content-Type"}), - ) - - // Register handlers - http.HandleFunc("/api/login", loginHandler) - - // Start server with CORS middleware - port := os.Getenv("PORT") - if port == "" { - port = "8080" - } - - fmt.Println("Go-сервер запущен на порту", port) - log.Fatal(http.ListenAndServe(":"+port, cors(http.DefaultServeMux))) -} diff --git a/frontend/style/app/login/page.tsx b/frontend/style/app/login/page.tsx deleted file mode 100644 index d0f6d098..00000000 --- a/frontend/style/app/login/page.tsx +++ /dev/null @@ -1,48 +0,0 @@ -"use client" - -import { useState } from "react" -import { useRouter } from "next/navigation" -import { Button } from "@/components/ui/button" -import { Input } from "@/components/ui/input" -import { Label } from "@/components/ui/label" -import { useAuth } from "@/contexts/auth-context" - -export default function LoginPage() { - const [email, setEmail] = useState("") - const [password, setPassword] = useState("") - const router = useRouter() - const { login } = useAuth() - - const handleSubmit = (e: React.FormEvent) => { - e.preventDefault() - // In a real application, you would validate credentials here - login() - router.push("/") - } - - return ( -
-

Войти

-
-
- - setEmail(e.target.value)} required /> -
-
- - setPassword(e.target.value)} - required - /> -
- -
-
- ) -} - diff --git a/frontend/style/app/login/users.db b/frontend/style/app/login/users.db deleted file mode 100644 index 22153776..00000000 Binary files a/frontend/style/app/login/users.db and /dev/null differ diff --git a/frontend/style/app/profile/register.go b/frontend/style/app/profile/auth.go similarity index 100% rename from frontend/style/app/profile/register.go rename to frontend/style/app/profile/auth.go diff --git a/frontend/style/app/profile/page.tsx b/frontend/style/app/profile/page.tsx index 4be0b0a8..9548445c 100644 --- a/frontend/style/app/profile/page.tsx +++ b/frontend/style/app/profile/page.tsx @@ -21,7 +21,7 @@ export default function AccountPage() { const handleLogin = async (e: React.FormEvent) => { e.preventDefault() try { - const response = await fetch("http://localhost:8080/api/login", { + const response = await fetch("http://localhost:8081/api/login", { method: "POST", headers: { "Content-Type": "application/json", @@ -50,7 +50,7 @@ export default function AccountPage() { return; } try { - const response = await fetch("http://localhost:8080/api/register", { + const response = await fetch("http://localhost:8081/api/register", { method: "POST", headers: { "Content-Type": "application/json", diff --git a/frontend/style/app/register/page.tsx b/frontend/style/app/register/page.tsx deleted file mode 100644 index 4c1bb4d8..00000000 --- a/frontend/style/app/register/page.tsx +++ /dev/null @@ -1,78 +0,0 @@ -"use client"; - -import { useState } from "react"; - -export default function RegisterPage() { - const [email, setEmail] = useState(""); - const [password, setPassword] = useState(""); - const [confirmPassword, setConfirmPassword] = useState(""); - const [message, setMessage] = useState(""); - - const handleSubmit = async (e: React.FormEvent) => { - e.preventDefault(); - - if (password !== confirmPassword) { - setMessage("Пароли не совпадают"); - return; - } - - try { - const response = await fetch("http://localhost:8080/api/register", { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ email, password }), - }); - - if (response.ok) { - setMessage("Регистрация прошла успешно!"); - } else { - const errorText = await response.text(); - setMessage(`Ошибка при регистрации: ${errorText}`); - } - } catch (error) { - console.error("Ошибка сети:", error); - setMessage("Ошибка сети"); - } - }; - - return ( -
-

Регистрация

-
-
- - setEmail(e.target.value)} - className="border rounded w-full p-2 mb-4" - /> -
-
- - setPassword(e.target.value)} - className="border rounded w-full p-2 mb-4" - /> -
-
- - setConfirmPassword(e.target.value)} - className="border rounded w-full p-2 mb-4" - /> -
- - {message &&

{message}

} -
-
- ); -} \ No newline at end of file diff --git a/frontend/style/app/register/register.go b/frontend/style/app/register/register.go deleted file mode 100644 index b63423f9..00000000 --- a/frontend/style/app/register/register.go +++ /dev/null @@ -1,127 +0,0 @@ -package main - -import ( - "database/sql" - "encoding/json" - "fmt" - "log" - "net/http" - "os" - - "github.com/gorilla/handlers" - _ "github.com/mattn/go-sqlite3" -) - -type User struct { - ID int `json:"id"` - Email string `json:"email"` - Password string `json:"password"` -} - -var db *sql.DB - -func initDB() { - var err error - - dbFile := "users.db" - db, err = sql.Open("sqlite3", dbFile) - if err != nil { - log.Fatal("Ошибка подключения к базе данных:", err) - } - - createTableQuery := ` - CREATE TABLE IF NOT EXISTS users ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - email TEXT NOT NULL UNIQUE, - password TEXT NOT NULL - );` - _, err = db.Exec(createTableQuery) - if err != nil { - log.Fatal("Ошибка при создании таблицы:", err) - } - - fmt.Println("База данных готова к работе.") -} - -func registerHandler(w http.ResponseWriter, r *http.Request) { - log.Printf("Received request with method: %s", r.Method) - if r.Method != http.MethodPost { - http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed) - return - } - - var user User - if err := json.NewDecoder(r.Body).Decode(&user); err != nil { - http.Error(w, "Ошибка обработки JSON", http.StatusBadRequest) - return - } - - if user.Email == "" || user.Password == "" { - http.Error(w, "Все поля обязательны для заполнения", http.StatusBadRequest) - return - } - - insertQuery := `INSERT INTO users (email, password) VALUES (?, ?)` - _, err := db.Exec(insertQuery, user.Email, user.Password) - if err != nil { - http.Error(w, "Ошибка записи в базу данных", http.StatusInternalServerError) - fmt.Println("Ошибка:", err) - return - } - - w.WriteHeader(http.StatusCreated) - w.Write([]byte("Пользователь успешно зарегистрирован")) -} - -func getUsersHandler(w http.ResponseWriter, r *http.Request) { - log.Printf("Received request with method: %s", r.Method) - if r.Method != http.MethodGet { - http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed) - return - } - - rows, err := db.Query(`SELECT id, email, password FROM users`) - if err != nil { - http.Error(w, "Ошибка чтения из базы данных", http.StatusInternalServerError) - return - } - defer rows.Close() - - var users []User - for rows.Next() { - var user User - if err := rows.Scan(&user.ID, &user.Email, &user.Password); err != nil { - http.Error(w, "Ошибка обработки данных", http.StatusInternalServerError) - return - } - users = append(users, user) - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(users) -} - -func main() { - initDB() - defer db.Close() - - // Setup CORS - cors := handlers.CORS( - handlers.AllowedOrigins([]string{"*"}), - handlers.AllowedMethods([]string{"GET", "POST"}), - handlers.AllowedHeaders([]string{"Content-Type"}), - ) - - // Register handlers - http.HandleFunc("/api/register", registerHandler) - http.HandleFunc("/api/users", getUsersHandler) - - // Start server with CORS middleware - port := os.Getenv("PORT") - if port == "" { - port = "8080" - } - - fmt.Println("Go-сервер запущен на порту", port) - log.Fatal(http.ListenAndServe(":"+port, cors(http.DefaultServeMux))) -} diff --git a/frontend/style/app/register/users.db b/frontend/style/app/register/users.db deleted file mode 100644 index 2dd32d08..00000000 Binary files a/frontend/style/app/register/users.db and /dev/null differ diff --git a/go.mod b/go.mod index 0264dfe5..1ac7f39b 100644 --- a/go.mod +++ b/go.mod @@ -23,7 +23,9 @@ 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.24 github.com/rivo/uniseg v0.2.0 // indirect + github.com/rs/cors v1.11.1 github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasthttp v1.51.0 // indirect github.com/valyala/tcplisten v1.0.0 // indirect diff --git a/internal/products/handler.go b/internal/products/handler.go deleted file mode 100644 index 1e0e2cff..00000000 --- a/internal/products/handler.go +++ /dev/null @@ -1 +0,0 @@ -package products diff --git a/internal/products/model.go b/internal/products/model.go deleted file mode 100644 index a9242a94..00000000 --- a/internal/products/model.go +++ /dev/null @@ -1,10 +0,0 @@ -package products - -type Product struct { - ID int `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Price float64 `json:"price"` - Stock int `json:"stock"` - Images []string `json:"images"` -} diff --git a/internal/products/repository.go b/internal/products/repository.go deleted file mode 100644 index 1e0e2cff..00000000 --- a/internal/products/repository.go +++ /dev/null @@ -1 +0,0 @@ -package products diff --git a/internal/products/service.go b/internal/products/service.go deleted file mode 100644 index f341fbc0..00000000 --- a/internal/products/service.go +++ /dev/null @@ -1,27 +0,0 @@ -package products - -// Product - структура для товара -type Product struct { - Name string - Price float64 -} - -// ProductService - сервис для работы с товарами -type ProductService struct { - products []Product -} - -// NewProductService - создание нового экземпляра ProductService -func NewProductService() *ProductService { - return &ProductService{} -} - -// AddProduct - добавление товара в сервис -func (s *ProductService) AddProduct(product Product) { - s.products = append(s.products, product) -} - -// GetAllProducts - получение списка всех товаров -func (s *ProductService) GetAllProducts() []Product { - return s.products -} diff --git a/not_sorted/register.go b/not_sorted/register.go deleted file mode 100644 index 23a48509..00000000 --- a/not_sorted/register.go +++ /dev/null @@ -1,75 +0,0 @@ -package main - -import ( - "fmt" - "log" - db "market/database" - "golang.org/x/crypto/bcrypt" - "github.com/gofiber/fiber/v2" -) - -// Data структура для входящих данных -type Data struct { - ID int `json:"ID"` - Count int `json:"Count"` -} - -type Account struct { - Login string `json:"Login"` - Password string `json:"Password"` -} - -func HashPassword(password string) (string) { - // Генерация хэша с заданным уровнем сложности (по умолчанию 10) - hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) - if err != nil { - return "" - } - return string(hash) -} - -// CheckPassword сравнивает хэшированный пароль с обычным -func CheckPassword(hashedPassword, plainPassword string) bool { - err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(plainPassword)) - return err == nil -} - -func main() { - // Инициализация Fiber - app := fiber.New() - - // Маршрут для обработки POST-запроса - app.Post("/register", func(c *fiber.Ctx) error { - // var input []Data - var input Account - // Парсинг входящих данных - if err := c.BodyParser(&input); err != nil { - return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ - "message": "err", - }) - } - - check_auth := fmt.Sprintf("SELECT ID, login WHERE login=%s", input.Login) - is_exist := db.Insert_Data(check_auth) - if is_exist{ - pswd := HashPassword(input.Password) - formatted := fmt.Sprintf("INSERT INTO users (login, hash_password) VALUES (%s, %s)", input.Login, pswd) - err := db.Insert_Data(formatted) - if err == false { - log.Printf("Ошибка при вставке данных") - return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ - "message": "err", - }) - } - } - - - return c.Status(fiber.StatusOK).JSON(fiber.Map{ - "message": "OK", - }) - }) - - // Запуск сервера - log.Fatal(app.Listen(":3000")) -} -18 diff --git a/not_sorted/url_for_pay_example b/not_sorted/url_for_pay_example deleted file mode 100755 index 179f01cf..00000000 Binary files a/not_sorted/url_for_pay_example and /dev/null differ diff --git a/not_sorted/url_for_pay_example.go b/not_sorted/url_for_pay_example.go deleted file mode 100644 index 0eba506f..00000000 --- a/not_sorted/url_for_pay_example.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "net/url" -) - -func Pay(sum float64) string{ - // Базовый URL - baseURL := "https://yoomoney.ru/quickpay/confirm.xml" - baseSum := fmt.Sprintf("%f", sum) - - // Параметры запроса - params := url.Values{} - params.Add("receiver", "410012845407838") - params.Add("quickpay-form", "shop") - params.Add("targets", "Тестовая покупка") - params.Add("paymentType", "SB") - params.Add("sum", baseSum) - params.Add("label", "cheche") - - // Формируем полный URL с параметрами - fullURL := fmt.Sprintf("%s?%s", baseURL, params.Encode()) - // fmt.Println("Request URL:", fullURL) - - // Создаем кастомный HTTP-клиент с отключенными редиректами - client := &http.Client{ - CheckRedirect: func(req *http.Request, via []*http.Request) error { - // Останавливаемся после первого редиректа - return http.ErrUseLastResponse - }, - } - - // Отправляем POST-запрос с пустым телом - resp, err := client.Post(fullURL, "application/x-www-form-urlencoded", nil) - if err != nil { - // fmt.Println("Error sending request:", err) - return "WHOOPS" - } - defer resp.Body.Close() - - location, err := resp.Location() - if err != nil { - // fmt.Println("Error getting location:", err) - return "WHOOPS" - } - // fmt.Println("Redirect URL:", location.String()) - return location.String() -} - -func main() { - pay := Pay(6.0) - fmt.Println(pay) -} \ No newline at end of file