pocketbase-signer/handlers/dashboard.go

150 lines
4.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package handlers
import (
"encoding/json"
"io"
"log"
"net/http"
"pocketbaseSigner/models"
)
func DashboardHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed)
return
}
// Получаем токен из cookie
cookie, err := r.Cookie("pb_auth")
if err != nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
// Получаем ID пользователя из cookie
userIdCookie, err := r.Cookie("user_id")
if err != nil {
log.Printf("Ошибка при получении ID пользователя: %v", err)
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
// Получаем данные пользователя
url := "http://localhost:8090/api/collections/users/records/" + userIdCookie.Value
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Printf("Ошибка при создании запроса: %v", err)
http.Error(w, "Внутренняя ошибка сервера", http.StatusInternalServerError)
return
}
req.Header.Set("Authorization", cookie.Value)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("Ошибка при получении данных пользователя: %v", err)
http.Error(w, "Ошибка при получении данных", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("Ошибка при чтении ответа: %v", err)
http.Error(w, "Ошибка при обработке данных", http.StatusInternalServerError)
return
}
// Проверяем статус ответа
if resp.StatusCode != http.StatusOK {
log.Printf("Ошибка при получении данных пользователя: %s", string(body))
http.Error(w, "Ошибка при получении данных пользователя", resp.StatusCode)
return
}
var userData models.UserData
if err := json.Unmarshal(body, &userData); err != nil {
log.Printf("Ошибка при разборе JSON: %v", err)
http.Error(w, "Ошибка при обработке данных", http.StatusInternalServerError)
return
}
// Отображаем dashboard
w.Header().Set("Content-Type", "text/html")
dashboardHTML := `
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Личный кабинет</title>
<style>
body {
font-family: Arial, sans-serif;
background: #f4f4f4;
margin: 0;
padding: 20px;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
.user-info {
margin-bottom: 20px;
}
.logout-btn {
background: #dc3545;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
}
.logout-btn:hover {
background: #c82333;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Личный кабинет</h1>
<form action="/logout" method="POST">
<button type="submit" class="logout-btn">Выйти</button>
</form>
</div>
<div class="user-info">
<h2>Информация о пользователе</h2>
<p><strong>Email:</strong> ` + userData.Email + `</p>
<p><strong>Имя:</strong> ` + userData.FirstName + `</p>
<p><strong>Фамилия:</strong> ` + userData.LastName + `</p>
<p><strong>Телефон:</strong> ` + userData.Phone + `</p>
<p><strong>Дата регистрации:</strong> ` + userData.Created + `</p>
<p><strong>Последнее обновление:</strong> ` + userData.Updated + `</p>
<p><strong>Статус верификации:</strong> ` + formatVerified(userData.Verified) + `</p>
</div>
</div>
</body>
</html>
`
w.Write([]byte(dashboardHTML))
}
func formatVerified(verified bool) string {
if verified {
return "Подтвержден"
}
return "Не подтвержден"
}