ruspet_portal_back/service/rest_admin_service/cmd/app.go

243 lines
8.4 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 main
import (
configcore "bitrix_balancer_api/core/config"
clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers"
_ "bitrix_balancer_api/rest_admin_service/docs"
adminhandler "bitrix_balancer_api/rest_admin_service/handlers/admin"
approvalstepshandler "bitrix_balancer_api/rest_admin_service/handlers/approval_steps"
approvalshandler "bitrix_balancer_api/rest_admin_service/handlers/approvals"
authhandler "bitrix_balancer_api/rest_admin_service/handlers/auth"
departmentshandler "bitrix_balancer_api/rest_admin_service/handlers/departments"
permissionshandler "bitrix_balancer_api/rest_admin_service/handlers/permission"
profilehandler "bitrix_balancer_api/rest_admin_service/handlers/profile"
roleshandler "bitrix_balancer_api/rest_admin_service/handlers/roles"
categorieshandler "bitrix_balancer_api/rest_admin_service/handlers/topic_categories"
topicexecutorshandler "bitrix_balancer_api/rest_admin_service/handlers/topic_executors"
topicshandler "bitrix_balancer_api/rest_admin_service/handlers/topics"
hierarchieshandler "bitrix_balancer_api/rest_admin_service/handlers/user_hierarchy"
userroleshandler "bitrix_balancer_api/rest_admin_service/handlers/user_roles"
usershandler "bitrix_balancer_api/rest_admin_service/handlers/users"
typesm "bitrix_balancer_api/rest_admin_service/types"
"errors"
"fmt"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/go-chi/httprate"
"github.com/sirupsen/logrus"
httpSwagger "github.com/swaggo/http-swagger"
"log"
"net/http"
"time"
)
const (
readTimeout = 15 * time.Minute // Таймаут чтения
writeTimeout = 15 * time.Minute // Таймаут записи
idleTimeout = 15 * time.Minute // Таймаут бездействия
rateLimit = 15 // Лимит запросов
rateWindow = 1 * time.Second // Окно времени для лимита запросов
)
// @title RusPet Admin API
// @version 0.1
// @description API админ-панели для системы согласований
// @description
// @description ## Возможности
// @description - Управление отделами, ролями и пользователями
// @description - Настройка тем и категорий согласований
// @description - Управление иерархией согласований
// @description - Назначение исполнителей и прав
// @description - Просмотр заявок и шагов согласования
// @description
// @description ## Аутентификация
// @description Все защищённые эндпоинты требуют:
// @description - `Authorization: Bearer <JWT_TOKEN>` — JWT токен администратора
// @description - `ApiKey: <HMAC_SIGNATURE>` — HMAC подпись для верификации клиента
// @description - `X-Timestamp: <UNIX_TIMESTAMP>` — Unix timestamp (не старше 3 минут)
// @description - `x-device-id: <DEVICE_ID>` — ID устройства
//
// @host localhost:8080
// @BasePath /
//
// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
//
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name ApiKey
//
// @securityDefinitions.apikey DeviceID
// @in header
// @name x-device-id
//
// @securityDefinitions.apikey Timestamp
// @in header
// @name X-Timestamp
//
// @contact.name Roman
// @contact.email romanzabolotskij0@gmail.com
func main() {
err := initService()
if err != nil {
logrus.Errorln("🔴 failed to init common: ", err)
}
select {}
}
func initService() error {
clientsExternal, err := getClientsExternal()
if err != nil {
logrus.Errorln("🔴 failed to load config: ", err)
return err
}
ipc, err := initInternalProvider(clientsExternal)
if err != nil {
logrus.Errorln("🔴 failed to init internal provider: ", err)
return err
}
router, err := initBaseApiRouter(ipc)
if err != nil {
logrus.Errorln("🔴 failed to init base api router: ", err)
return err
}
if err := startRestApiServer(ipc, router); err != nil {
logrus.Errorln("🔴 failed to start server: ", err)
return err
}
return nil
}
func getClientsExternal() (clientcontrollers.ClientsExternal, error) {
options := &configcore.ConfigLoadOptions{
Redis: true,
Database: true,
Secrets: configcore.SecretsOptions{
AuthJWT: configcore.AuthJWTOptions{
Admin: true,
},
AdminAccessCode: true,
},
Server: configcore.ExposedServiceOptions{
RESTAdminService: true,
},
}
return clientcontrollers.ReturnClientsExternal(options)
}
func initInternalProvider(clientsExternal clientcontrollers.ClientsExternal) (*typesm.InternalProviderControl, error) {
return &typesm.InternalProviderControl{
Config: clientsExternal.Config,
RedisClient: clientsExternal.Redis,
Database: clientsExternal.DB,
}, nil
}
func startRestApiServer(ipc *typesm.InternalProviderControl, router *chi.Mux) error {
serverPort := fmt.Sprintf("%d", ipc.Config.Server.RESTAdminService.PortRest)
serverAddr := ":" + serverPort
httpServer := &http.Server{
Addr: serverAddr,
Handler: router,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
IdleTimeout: idleTimeout,
}
log.Printf("✅ Starting server on %s", serverAddr)
return httpServer.ListenAndServe()
}
func initBaseApiRouter(ipc *typesm.InternalProviderControl) (*chi.Mux, error) {
router := chi.NewRouter()
corsOptions := cors.New(cors.Options{
AllowedOrigins: ipc.Config.Server.RESTAdminService.Cors.AllowedOrigins, // Список разрешенных origin
AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch, http.MethodOptions},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "ApiKey", "x-device-id"},
ExposedHeaders: []string{"Link", "Cache-Control"},
AllowCredentials: false,
MaxAge: 300, // Максимальное время жизни предварительных запросов в секундах
})
router.Use(corsOptions.Handler)
router.Use(middleware.RealIP)
// Добавляем ограничение по IP
router.Use(httprate.LimitByIP(rateLimit, rateWindow))
if ipc.Database == nil {
return nil, errors.New("failed_to_connect_db")
}
err := registerRoutes(router, ipc)
if err != nil {
return nil, err
}
return router, nil
}
// регистрирует маршруты
func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) error {
router.Get("/swagger/*", httpSwagger.Handler(
httpSwagger.URL("/swagger/doc.json"), // URL к сгенерированному JSON
httpSwagger.DeepLinking(true),
httpSwagger.DocExpansion("none"),
httpSwagger.DomID("swagger-ui"),
))
// Слайс обработчиков маршрутов
routeHandlers := []struct {
name string
handler func(chi.Router, *typesm.InternalProviderControl) error
}{
{"admin", adminhandler.RegisterAdminRoutes},
{"auth", authhandler.RegisterAuthRoutes},
{"profile", profilehandler.RegisterProfileRoutes},
{"users", usershandler.RegisterUserRoutes},
{"departments", departmentshandler.RegisterDepartmentRoutes},
{"roles", roleshandler.RegisterRoleRoutes},
{"categories", categorieshandler.RegisterCategoryRoutes},
{"topics", topicshandler.RegisterTopicRoutes},
{"user-roles", userroleshandler.RegisterUserRoleRoutes},
{"hierarchies", hierarchieshandler.RegisterHierarchyRoutes},
{"topic-executors", topicexecutorshandler.RegisterTopicExecutorRoutes},
{"approvals", approvalshandler.RegisterApprovalRoutes},
{"approval-steps", approvalstepshandler.RegisterApprovalStepRoutes},
{"permissions", permissionshandler.RegisterPermissionRoutes},
}
// Регистрация всех маршрутов
for _, rh := range routeHandlers {
if errObj := rh.handler(router, ipc); errObj != nil {
return errors.New(fmt.Sprintf("🔴 failed to register %s routes", rh.name))
}
}
// Вывод зарегистрированных маршрутов
if err := printRoutes(router, ipc); err != nil {
return errors.New(fmt.Sprintf("🔴 failed to print routes: %v", err))
}
return nil
}
func printRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error {
err := chi.Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
logrus.Info(fmt.Sprintf("🩵 [ %s ] %s\n", method, route))
return nil
})
if err != nil {
return err
}
return nil
}