Files
knock-gui/back/cmd/serve.go
2025-08-17 00:43:58 +06:00

71 lines
1.9 KiB
Go
Raw Permalink 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 cmd
import (
"crypto/sha256"
"embed"
"fmt"
"os"
"strings"
"port-knocker/internal"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
)
//go:embed public/*
var embeddedFS embed.FS
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Запуск встроенного веб-сервера с GUI и REST API",
RunE: runServe,
}
func init() {
rootCmd.AddCommand(serveCmd)
}
func runServe(cmd *cobra.Command, args []string) error {
pass := os.Getenv("GO_KNOCKER_SERVE_PASS")
if strings.TrimSpace(pass) == "" {
return fmt.Errorf("GO_KNOCKER_SERVE_PASS не задан — задайте пароль для доступа к GUI/API")
}
// Хеш, который будем использовать как ключ шифрования (совместимо с internal)
passHash := sha256.Sum256([]byte(pass))
// Пробрасываем пароль; internal сам выполнит sha256 от значения env
os.Setenv(internal.EncryptionKeyEnvVar, pass)
port := os.Getenv("GO_KNOCKER_SERVE_PORT")
if strings.TrimSpace(port) == "" {
port = "8888"
}
r := gin.Default()
// CORS: разрешаем для локальной разработки
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:4200", "http://127.0.0.1:8888", "http://localhost:8888"},
AllowMethods: []string{"GET", "POST", "OPTIONS"},
AllowHeaders: []string{"Authorization", "Content-Type"},
AllowCredentials: true,
}))
// Применяем middleware для защиты HTML страниц
r.Use(staticAuthMiddleware(pass))
// API роуты с авторизацией
api := r.Group("/api/v1/knock-actions")
api.Use(authMiddleware(pass))
// Настраиваем роуты
setupKnockRoutes(api)
setupCryptoRoutes(api, passHash)
setupStaticRoutes(r, embeddedFS)
fmt.Printf("Serving on :%s\n", port)
return r.Run(":" + port)
}