Добавить not_sorted/register.go
This commit is contained in:
75
not_sorted/register.go
Normal file
75
not_sorted/register.go
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
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.Exec(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
|
||||||
Reference in New Issue
Block a user