From 19e61e5ed9a3d2dd83fa74ce7b0f2c46ff2ab955 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=93=D0=B0=D0=BD=D0=B5=D0=B5=D0=B2=20=D0=90=D1=80=D1=82?= =?UTF-8?q?=D0=B5=D0=BC?= Date: Sat, 22 Nov 2025 15:27:23 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D1=8B=20=D0=BD=D0=B5=D0=B4=D0=BE=D1=81=D1=82=D0=B0=D1=8E?= =?UTF-8?q?=D1=89=D0=B8=D0=B5=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 18 ------------------ cmd/main.go | 4 ++-- internal/AuthServer.go | 7 +++---- internal/config/config.go | 14 +++++++------- internal/handler/middleware.go | 30 +----------------------------- 5 files changed, 13 insertions(+), 60 deletions(-) delete mode 100644 .env.example diff --git a/.env.example b/.env.example deleted file mode 100644 index 198b341..0000000 --- a/.env.example +++ /dev/null @@ -1,18 +0,0 @@ -# Database Configuration -DB_PASSWORD=postgres -DB_HOST=localhost -DB_PORT=5432 -DB_USER=postgres -DB_NAME=authorization - -# JWT Tokens (ВАЖНО: Сгенерируйте сложные случайные строки!) -# Можно использовать: openssl rand -base64 32 -ACCESS_TOKEN_SECRET=kdfmklsdlmk;asdmkl;ds -REFRESH_TOKEN_SECRET=asdflmkasdfklmsdafklm - -# Token TTL (optional, defaults from application.yaml) -# ACCESS_TOKEN_TTL_MINUTES=15 -# REFRESH_TOKEN_TTL_MINUTES=90 - -# Server (optional) -# SERVER_PORT=8081 diff --git a/cmd/main.go b/cmd/main.go index 29c705e..c745cf3 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -9,8 +9,8 @@ import ( "os" "github.com/golang-migrate/migrate/v4" - _ "github.com/golang-migrate/migrate/v4/database/postgres" // Импорт драйвера PostgreSQL - _ "github.com/golang-migrate/migrate/v4/source/file" // Импорт файлового драйвера + _ "github.com/golang-migrate/migrate/v4/database/postgres" + _ "github.com/golang-migrate/migrate/v4/source/file" "github.com/joho/godotenv" "github.com/sirupsen/logrus" ) diff --git a/internal/AuthServer.go b/internal/AuthServer.go index 7021a7d..cac366f 100644 --- a/internal/AuthServer.go +++ b/internal/AuthServer.go @@ -10,10 +10,10 @@ type Server struct { httpServer *http.Server } -func (s *Server) Run(port string,handler http.Handler) error { +func (s *Server) Run(port string, handler http.Handler) error { s.httpServer = &http.Server{ Addr: ":" + port, - Handler: handler, + Handler: handler, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, @@ -21,7 +21,6 @@ func (s *Server) Run(port string,handler http.Handler) error { return s.httpServer.ListenAndServe() } -func (s *Server) Shutdown(ctx context.Context) error{ +func (s *Server) Shutdown(ctx context.Context) error { return s.httpServer.Shutdown(ctx) } - diff --git a/internal/config/config.go b/internal/config/config.go index 1a3ab13..a87a36a 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -21,7 +21,7 @@ type ServerConfig struct { type DatabaseConfig struct { Username string `yaml:"username" json:"username"` - Password string // Из переменной окружения, не из YAML + Password string Host string `yaml:"host" json:"host"` Port string `yaml:"port" json:"port"` Sslmode string `yaml:"sslmode" json:"sslmode"` @@ -29,12 +29,12 @@ type DatabaseConfig struct { } func LoadConfig(absolutePath string) (*Config, error) { - // Загружаем .env файл (игнорируем ошибку, если файла нет) + _ = godotenv.Load() config := &Config{} - // Читаем базовую конфигурацию из YAML (без секретов) + file, err := os.Open(absolutePath) if err != nil { return nil, err @@ -56,28 +56,28 @@ func LoadConfig(absolutePath string) (*Config, error) { // loadFromEnv загружает секретные данные из переменных окружения func loadFromEnv(config *Config) error { - // Пароль БД (обязательный) + dbPassword := os.Getenv("DB_PASSWORD") if dbPassword == "" { return fmt.Errorf("DB_PASSWORD environment variable is required") } config.DB.Password = dbPassword - // Access Token Secret (обязательный) + accessTokenSecret := os.Getenv("ACCESS_TOKEN_SECRET") if accessTokenSecret == "" { return fmt.Errorf("ACCESS_TOKEN_SECRET environment variable is required") } config.Token.AccessToken.SecretWord = accessTokenSecret - // Refresh Token Secret (обязательный) + refreshTokenSecret := os.Getenv("REFRESH_TOKEN_SECRET") if refreshTokenSecret == "" { return fmt.Errorf("REFRESH_TOKEN_SECRET environment variable is required") } config.Token.RefreshToken.SecretWord = refreshTokenSecret - // Опциональные переопределения (если заданы в env) + if accessTTL := os.Getenv("ACCESS_TOKEN_TTL_MINUTES"); accessTTL != "" { ttl, err := strconv.Atoi(accessTTL) if err != nil { diff --git a/internal/handler/middleware.go b/internal/handler/middleware.go index 4079584..9f8dafa 100644 --- a/internal/handler/middleware.go +++ b/internal/handler/middleware.go @@ -42,7 +42,6 @@ func (h *Handler) userIdentity(c *gin.Context) { c.Next() } -// requireRole - middleware-фабрика, возвращает middleware для проверки конкретных ролей func (h *Handler) requireRole(allowedRoles ...internal.UserRole) gin.HandlerFunc { return func(c *gin.Context) { userRole, exists := c.Get(userRoleKey) @@ -86,31 +85,4 @@ func (h *Handler) requireTeacher() gin.HandlerFunc { func (h *Handler) requireStudent() gin.HandlerFunc { return h.requireRole(internal.Student, internal.Teacher, internal.Admin) -} - -func (h *Handler) checkAdminIdentity(c *gin.Context) { - header := c.GetHeader(authorizationHeader) - if header == "" { - newErrorResponse(c, http.StatusUnauthorized, "Пустой header авторизации") - return - } - - headerParts := strings.Split(header, " ") - if len(headerParts) != 2 { - newErrorResponse(c, http.StatusUnauthorized, "Невалидный токен JWT") - return - } - - userRole, err := h.services.ParseToken(headerParts[1]) - - if userRole != string(internal.Admin) { - newErrorResponse(c, http.StatusUnauthorized, "Недостаточно прав для выполнения запроса") - return - } - if err != nil { - newErrorResponse(c, http.StatusUnauthorized, "Ошибка при извлечении claims") - return - } - - c.Set(userRoleKey, userRole) -} +} \ No newline at end of file