feat(admin): added admin panel

This commit is contained in:
2025-06-18 17:29:01 +03:00
parent a157fc1cc3
commit 2c682c5123
5 changed files with 119 additions and 16 deletions

View File

@@ -27,14 +27,15 @@ func main() {
modpackHandler := &api.ModpackHandler{ModpackRepo: modpackRepo}
launcherHandler := &api.LauncherHandler{ModpackRepo: modpackRepo}
adminUserHandler := &api.AdminUserHandler{UserRepo: userRepo}
// Запускаем поллер в фоновой горутине
go serverPoller.Start(context.Background())
// Сервисы
userService := &core.UserService{Repo: userRepo}
authService := &core.AuthService{UserRepo: userRepo} // Новый сервис
// Инициализируем сервис профилей, читая путь к ключу и домен из переменных окружения
authService := &core.AuthService{UserRepo: userRepo}
keyPath := os.Getenv("RSA_PRIVATE_KEY_PATH")
if keyPath == "" {
log.Fatal("RSA_PRIVATE_KEY_PATH environment variable is not set")
@@ -81,8 +82,15 @@ func main() {
r.Route("/api/user", func(r chi.Router) {
r.Post("/skin", profileHandler.UploadSkin)
})
r.Route("/api/admin/modpacks", func(r chi.Router) {
r.Post("/import", modpackHandler.ImportModpack)
r.Route("/api/admin", func(r chi.Router) {
r.Use(api.AdminMiddleware)
r.Route("/modpacks", func(r chi.Router) {
r.Post("/import", modpackHandler.ImportModpack)
})
r.Route("/users", func(r chi.Router) {
r.Get("/", adminUserHandler.GetAllUsers)
r.Patch("/{id}/role", adminUserHandler.UpdateUserRole)
})
})
})

View File

@@ -0,0 +1,40 @@
package api
import (
"encoding/json"
"net/http"
"strconv"
"gitea.mrixs.me/minecraft-platform/backend/internal/database"
"github.com/go-chi/chi/v5"
)
type AdminUserHandler struct {
UserRepo *database.UserRepository
}
func (h *AdminUserHandler) GetAllUsers(w http.ResponseWriter, r *http.Request) {
users, err := h.UserRepo.GetAllUsers(r.Context())
if err != nil {
http.Error(w, "Failed to get users", http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(users)
}
func (h *AdminUserHandler) UpdateUserRole(w http.ResponseWriter, r *http.Request) {
userID, _ := strconv.Atoi(chi.URLParam(r, "id"))
var payload struct {
Role string `json:"role"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// TODO: Валидация роли
if err := h.UserRepo.UpdateUserRole(r.Context(), userID, payload.Role); err != nil {
http.Error(w, "Failed to update role", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}

View File

@@ -11,9 +11,9 @@ import (
type contextKey string
const UserIDContextKey = contextKey("userID")
const ClaimsContextKey = contextKey("claims")
// AuthMiddleware проверяет JWT токен и добавляет user_id в контекст запроса.
// AuthMiddleware проверяет JWT токен и добавляет claims в контекст запроса.
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
@@ -52,14 +52,28 @@ func AuthMiddleware(next http.Handler) http.Handler {
return
}
userIDFloat, ok := claims["user_id"].(float64)
if !ok {
http.Error(w, "Invalid user_id in token", http.StatusUnauthorized)
return
}
userID := int(userIDFloat)
ctx := context.WithValue(r.Context(), UserIDContextKey, userID)
// Добавляем claims в контекст
ctx := context.WithValue(r.Context(), ClaimsContextKey, claims)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// AdminMiddleware проверяет, что пользователь аутентифицирован и имеет роль 'admin'.
func AdminMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Получаем claims из контекста
claims, ok := r.Context().Value(ClaimsContextKey).(jwt.MapClaims)
if !ok {
http.Error(w, "Could not get claims from context", http.StatusInternalServerError)
return
}
role, ok := claims["role"].(string)
if !ok || role != "admin" {
http.Error(w, "Forbidden: insufficient permissions", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}

View File

@@ -8,6 +8,7 @@ import (
"gitea.mrixs.me/minecraft-platform/backend/internal/core"
"gitea.mrixs.me/minecraft-platform/backend/internal/database"
"github.com/go-chi/chi/v5"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
@@ -39,11 +40,18 @@ func (h *ProfileHandler) GetProfile(w http.ResponseWriter, r *http.Request) {
}
func (h *ProfileHandler) UploadSkin(w http.ResponseWriter, r *http.Request) {
userID, ok := r.Context().Value(UserIDContextKey).(int)
// Получаем claims из контекста
claims, ok := r.Context().Value(ClaimsContextKey).(jwt.MapClaims)
if !ok {
http.Error(w, "Could not get user ID from context", http.StatusInternalServerError)
http.Error(w, "Could not get claims from context", http.StatusInternalServerError)
return
}
userIDFloat, ok := claims["user_id"].(float64)
if !ok {
http.Error(w, "Invalid user_id in token", http.StatusInternalServerError)
return
}
userID := int(userIDFloat)
r.ParseMultipartForm(256 << 10) // 256KB

View File

@@ -181,3 +181,36 @@ func (r *UserRepository) GetUserByLogin(ctx context.Context, login string) (*mod
user.UUID, _ = uuid.Parse(userUUID)
return user, nil
}
// GetAllUsers возвращает список всех пользователей.
func (r *UserRepository) GetAllUsers(ctx context.Context) ([]models.User, error) {
rows, err := r.DB.Query(ctx, "SELECT id, uuid, username, email, role, created_at, updated_at FROM users ORDER BY id")
if err != nil {
return nil, err
}
defer rows.Close()
var users []models.User
for rows.Next() {
var u models.User
var userUUID string
if err := rows.Scan(&u.ID, &userUUID, &u.Username, &u.Email, &u.Role, &u.CreatedAt, &u.UpdatedAt); err != nil {
return nil, err
}
u.UUID, _ = uuid.Parse(userUUID)
users = append(users, u)
}
return users, nil
}
// UpdateUserRole обновляет роль пользователя по его ID.
func (r *UserRepository) UpdateUserRole(ctx context.Context, userID int, newRole string) error {
res, err := r.DB.Exec(ctx, "UPDATE users SET role = $1 WHERE id = $2", newRole, userID)
if err != nil {
return err
}
if res.RowsAffected() == 0 {
return ErrUserNotFound
}
return nil
}