Update main.go
This commit is contained in:
97
main.go
97
main.go
@@ -5,6 +5,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
@@ -13,7 +14,7 @@ const (
|
|||||||
nocoURL = "https://nocodb.shaiheprjct.ru/api/v2/tables/mqvqd88xe01rxap/records"
|
nocoURL = "https://nocodb.shaiheprjct.ru/api/v2/tables/mqvqd88xe01rxap/records"
|
||||||
apiToken = "eVqxLwbUQRLQHQ3g44js9vfLHvIdWhllLZwKfW25"
|
apiToken = "eVqxLwbUQRLQHQ3g44js9vfLHvIdWhllLZwKfW25"
|
||||||
)
|
)
|
||||||
// Простая структура пользователя
|
|
||||||
type User struct {
|
type User struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
@@ -24,29 +25,23 @@ func main() {
|
|||||||
http.HandleFunc("/register", registerHandler)
|
http.HandleFunc("/register", registerHandler)
|
||||||
http.HandleFunc("/login", loginHandler)
|
http.HandleFunc("/login", loginHandler)
|
||||||
|
|
||||||
fmt.Println("Сервер запущен на http://localhost:9000")
|
log.Println("✅ Сервер запускается на порту :9000")
|
||||||
// Меняем порт здесь:
|
if err := http.ListenAndServe(":9000", nil); err != nil {
|
||||||
err := http.ListenAndServe(":9000", nil)
|
log.Fatalf("❌ Ошибка запуска сервера: %v", err)
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Ошибка запуска сервера: %v\n", err)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Хэширование пароля
|
|
||||||
func hashPassword(password string) (string, error) {
|
|
||||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
|
|
||||||
return string(bytes), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Регистрация (отправка в NocoDB)
|
|
||||||
func registerHandler(w http.ResponseWriter, r *http.Request) {
|
func registerHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method == "POST" {
|
if r.Method == "POST" {
|
||||||
user := r.FormValue("username")
|
username := r.FormValue("username")
|
||||||
pass, _ := hashPassword(r.FormValue("password"))
|
password := r.FormValue("password")
|
||||||
|
|
||||||
|
log.Printf("--> Регистрация пользователя: %s", username)
|
||||||
|
|
||||||
|
hash, _ := bcrypt.GenerateFromPassword([]byte(password), 10)
|
||||||
jsonData, _ := json.Marshal(map[string]string{
|
jsonData, _ := json.Marshal(map[string]string{
|
||||||
"username": user,
|
"username": username,
|
||||||
"password": pass,
|
"password": string(hash),
|
||||||
})
|
})
|
||||||
|
|
||||||
req, _ := http.NewRequest("POST", nocoURL, bytes.NewBuffer(jsonData))
|
req, _ := http.NewRequest("POST", nocoURL, bytes.NewBuffer(jsonData))
|
||||||
@@ -54,73 +49,75 @@ func registerHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
client := &http.Client{}
|
client := &http.Client{}
|
||||||
resp, _ := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("❌ Ошибка запроса к NocoDB: %v", err)
|
||||||
|
http.Error(w, err.Error(), 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.StatusCode == 200 || resp.StatusCode == 201 {
|
body, _ := io.ReadAll(resp.Body)
|
||||||
fmt.Fprint(w, "Регистрация успешна! Теперь можно войти.")
|
log.Printf("<-- Ответ NocoDB (Статус %d): %s", resp.StatusCode, string(body))
|
||||||
|
|
||||||
|
if resp.StatusCode < 300 {
|
||||||
|
fmt.Fprint(w, "Регистрация успешна!")
|
||||||
} else {
|
} else {
|
||||||
fmt.Fprint(w, "Ошибка регистрации. Возможно, имя занято.")
|
http.Error(w, "NocoDB error: "+string(body), 500)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Вход (проверка через NocoDB)
|
|
||||||
func loginHandler(w http.ResponseWriter, r *http.Request) {
|
func loginHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method == "POST" {
|
if r.Method == "POST" {
|
||||||
user := r.FormValue("username")
|
user := r.FormValue("username")
|
||||||
pass := r.FormValue("password")
|
pass := r.FormValue("password")
|
||||||
|
|
||||||
// Поиск пользователя в NocoDB по username
|
log.Printf("--> Попытка входа: %s", user)
|
||||||
|
|
||||||
|
// Поиск в NocoDB
|
||||||
searchURL := fmt.Sprintf("%s?where=(username,eq,%s)", nocoURL, user)
|
searchURL := fmt.Sprintf("%s?where=(username,eq,%s)", nocoURL, user)
|
||||||
req, _ := http.NewRequest("GET", searchURL, nil)
|
req, _ := http.NewRequest("GET", searchURL, nil)
|
||||||
req.Header.Set("xc-token", apiToken)
|
req.Header.Set("xc-token", apiToken)
|
||||||
|
|
||||||
client := &http.Client{}
|
client := &http.Client{}
|
||||||
resp, _ := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("❌ Ошибка при поиске пользователя: %v", err)
|
||||||
|
http.Error(w, err.Error(), 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
body, _ := io.ReadAll(resp.Body)
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
log.Printf("<-- Ответ NocoDB (Логин): %s", string(body))
|
||||||
|
|
||||||
var result struct {
|
var result struct {
|
||||||
List []User `json:"list"`
|
List []User `json:"list"`
|
||||||
}
|
}
|
||||||
json.Unmarshal(body, &result)
|
if err := json.Unmarshal(body, &result); err != nil {
|
||||||
|
log.Printf("❌ Ошибка парсинга JSON: %v", err)
|
||||||
|
http.Error(w, "Ошибка данных", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if len(result.List) > 0 {
|
if len(result.List) > 0 {
|
||||||
err := bcrypt.CompareHashAndPassword([]byte(result.List[0].Password), []byte(pass))
|
err := bcrypt.CompareHashAndPassword([]byte(result.List[0].Password), []byte(pass))
|
||||||
if err == nil {
|
if err == nil {
|
||||||
fmt.Fprintf(w, "Добро пожаловать в личный кабинет, %s!", user)
|
log.Printf("✅ Пользователь %s успешно вошел", user)
|
||||||
|
fmt.Fprintf(w, "Добро пожаловать, %s!", user)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Fprint(w, "Неверный логин или пароль.")
|
log.Printf("⚠️ Неудачная попытка входа для: %s", user)
|
||||||
|
fmt.Fprint(w, "Ошибка авторизации")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func homePage(w http.ResponseWriter, r *http.Request) {
|
func homePage(w http.ResponseWriter, r *http.Request) {
|
||||||
// Эта строка заставит браузер отобразить форму, а не текст кода
|
|
||||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
fmt.Fprint(w, `<h2>Личный кабинет</h2>
|
||||||
fmt.Fprint(w, `
|
<form action="/register" method="POST"><input name="username" placeholder="Логин"><input name="password" type="password"><button>Регистрация</button></form>
|
||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head><title>Личный кабинет</title></head>
|
|
||||||
<body>
|
|
||||||
<h2>Регистрация</h2>
|
|
||||||
<form action="/register" method="POST">
|
|
||||||
<input name="username" placeholder="Логин" required>
|
|
||||||
<input name="password" type="password" placeholder="Пароль" required>
|
|
||||||
<button type="submit">Создать аккаунт</button>
|
|
||||||
</form>
|
|
||||||
<hr>
|
<hr>
|
||||||
<h2>Вход</h2>
|
<form action="/login" method="POST"><input name="username" placeholder="Логин"><input name="password" type="password"><button>Вход</button></form>`)
|
||||||
<form action="/login" method="POST">
|
|
||||||
<input name="username" placeholder="Логин" required>
|
|
||||||
<input name="password" type="password" placeholder="Пароль" required>
|
|
||||||
<button type="submit">Войти</button>
|
|
||||||
</form>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
`)
|
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user