optimize cfg

This commit is contained in:
Pasha 2025-01-02 13:44:52 +03:00 committed by skeris
parent 5f925951e9
commit fdc2c7f692
13 changed files with 136 additions and 155 deletions

46
.env

@ -1,27 +1,24 @@
# General application settings
APP_NAME=codeword
HTTP_HOST="localhost"
HTTP_PORT="8080"
CLIENT_HTTP_URL="localhost:3000"
ADMIN_HTTP_URL="localhost:3001"
GRPC_URL="localhost:9000"
# MongoDB settings
MONGO_HOST="127.0.0.1"
MONGO_PORT="27020"
MONGO_USER="test"
MONGO_PASSWORD="test"
MONGO_DB="admin"
MONGO_AUTH="admin"
MONGO_URL="mongodb://test:test@localhost:27020/?authSource=admin"
MONGO_DB_NAME="admin"
# Redis settings
REDIS_ADDR="10.6.0.23:6379"
REDIS_PASS="Redalert2"
REDIS_DB=3
REDIS_HOST="localhost:6379"
REDIS_PASS="admin"
REDIS_DB=2
# Keys
PUBLIC_CURVE_KEY="-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAEbnIvjIMle4rqVol6K2XUqOxHy1KJoNoZdKJrRUPKL4=\n-----END PUBLIC KEY-----"
ENCRYPT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAEbnIvjIMle4rqVol6K2XUqOxHy1KJoNoZdKJrRUPKL4=\n-----END PUBLIC KEY-----"
PRIVATE_CURVE_KEY="-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIKn0BKwF3vZvODgWAnUIwQhd8de5oZhY48gc23EWfrfs\n-----END PRIVATE KEY-----"
ENCRYPT_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIKn0BKwF3vZvODgWAnUIwQhd8de5oZhY48gc23EWfrfs\n-----END PRIVATE KEY-----"
SIGN_SECRET="pena-auth-microservice-group"
ENCRYPT_SIGN_SECRET="pena-auth-microservice-group"
JWT_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgHgnvr7O2tiApjJfid1orFnIGm6980fZp+Lpbjo+NC/0whMFga2B
iw5b1G2Q/B2u0tpO1Fs/E8z7Lv1nYfr5jx2S8x6BdA4TS2kB9Kf0wn0+7wSlyikH
@ -43,23 +40,18 @@ JWT_ISSUER="pena-auth-service"
JWT_AUDIENCE="pena"
SIGN_SECRET="secret"
# SMTP settings
SMTP_API_URL="https://api.smtp.bz/v1/smtp/send"
SMTP_HOST="connect.mailclient.bz"
SMTP_PORT="587"
SMTP_UNAME="kotilion.95@gmail.com"
SMTP_PASS="vWwbCSg4bf0p"
SMTP_API_KEY="P0YsjUB137upXrr1NiJefHmXVKW1hmBWlpev"
SMTP_SENDER="noreply@mailing.pena.digital"
API_URL="https://api.smtp.bz/v1/smtp/send"
MAIL_API_KEY="P0YsjUB137upXrr1NiJefHmXVKW1hmBWlpev"
MAIL_SENDER="noreply@mailing.pena.digital"
# URL settings
DEFAULT_REDIRECTION_URL = "https://shub.pena.digital/recover/"
AUTH_EXCHANGE_URL = "http://10.6.0.11:59300/auth/exchange"
RECOVER_URL = "https://shub.pena.digital/recover/"
DISCOUNT_ADDRESS = "http://10.6.0.11:9001"
AUTH_MICROSERVICE_URL = "http://10.6.0.11:59300"
MAIL_RECOVERY_URL = "https://shub.pena.digital/recover/"
DISCOUNT_MICROSERVICE_GRPC_URL = "http://10.6.0.11:9001"
TRASH_LOG_HOST = "localhost:7113"
# Kafka settings
KAFKA_BROKERS="10.6.0.11:9092"
KAFKA_BROKERS="localhost:9092"
KAFKA_TOPIC_TARIFF="tariffs"

@ -10,20 +10,20 @@ import (
type AuthClientDeps struct {
AuthUrl string
FiberClient *fiber.Client
Logger *zap.Logger
}
type AuthClient struct {
deps AuthClientDeps
authUrl string
fiberClient *fiber.Client
logger *zap.Logger
}
func NewAuthClient(deps AuthClientDeps) *AuthClient {
if deps.FiberClient == nil {
deps.FiberClient = fiber.AcquireClient()
}
return &AuthClient{
deps: deps,
authUrl: deps.AuthUrl,
fiberClient: fiber.AcquireClient(),
logger: deps.Logger,
}
}
@ -35,30 +35,30 @@ func (a *AuthClient) RefreshAuthToken(userID, signature string) (*models.Refresh
bodyBytes, err := json.Marshal(body)
if err != nil {
a.deps.Logger.Error("Failed to encode request body", zap.Error(err))
a.logger.Error("Failed to encode request body", zap.Error(err))
return nil, err
}
agent := a.deps.FiberClient.Post(a.deps.AuthUrl)
agent := a.fiberClient.Post(fmt.Sprintf("%s/auth/exchange", a.authUrl))
agent.Set("Content-Type", "application/json").Body(bodyBytes)
statusCode, resBody, errs := agent.Bytes()
if len(errs) > 0 {
for _, err := range errs {
a.deps.Logger.Error("Error in exchange auth token request", zap.Error(err))
a.logger.Error("Error in exchange auth token request", zap.Error(err))
}
return nil, fmt.Errorf("request failed: %v", errs)
}
if statusCode != fiber.StatusOK {
errorMessage := fmt.Sprintf("received an incorrect response from the authentication service: %d", statusCode)
a.deps.Logger.Error(errorMessage, zap.Int("status", statusCode), zap.String("respBody", string(resBody)), zap.String("UserID", userID), zap.String("sign", signature))
a.logger.Error(errorMessage, zap.Int("status", statusCode), zap.String("respBody", string(resBody)), zap.String("UserID", userID), zap.String("sign", signature))
return nil, fmt.Errorf(errorMessage)
}
var tokens models.RefreshResponse
if err := json.Unmarshal(resBody, &tokens); err != nil {
a.deps.Logger.Error("failed to unmarshal auth service response", zap.Error(err))
a.logger.Error("failed to unmarshal auth service response", zap.Error(err))
return nil, err
}

@ -9,46 +9,46 @@ import (
)
type RecoveryEmailSenderDeps struct {
SmtpApiUrl string
SmtpHost string
SmtpPort string
SmtpSender string
Username string
Password string
ApiUrl string
Sender string
ApiKey string
FiberClient *fiber.Client
Logger *zap.Logger
RecoveryUrl string
}
type RecoveryEmailSender struct {
deps RecoveryEmailSenderDeps
apiUrl string
sender string
apiKey string
fiberClient *fiber.Client
logger *zap.Logger
recoveryUrl string
}
func NewRecoveryEmailSender(deps RecoveryEmailSenderDeps) *RecoveryEmailSender {
if deps.FiberClient == nil {
deps.FiberClient = fiber.AcquireClient()
}
return &RecoveryEmailSender{
deps: deps,
apiUrl: deps.ApiUrl,
sender: deps.Sender,
apiKey: deps.ApiKey,
fiberClient: fiber.AcquireClient(),
logger: deps.Logger,
recoveryUrl: deps.RecoveryUrl,
}
}
func (r *RecoveryEmailSender) SendRecoveryEmail(email string, signature string) error {
url := r.deps.SmtpApiUrl
fmt.Println(email, signature)
message := fmt.Sprintf(`Здравствуйте, ваша <a href="%s">ссылка для восстановление пароля</a>(доступна всего 15 минут)
Если это были не вы, напишите пожалуйста в техническую поддержку.`, r.deps.RecoveryUrl + signature)
Если это были не вы, напишите пожалуйста в техническую поддержку.`, r.recoveryUrl+signature)
form := new(bytes.Buffer)
writer := multipart.NewWriter(form)
defer writer.Close()
fields := map[string]string{
"from": r.deps.SmtpSender,
"from": r.sender,
"to": email,
"subject": "Восстановление доступа",
"html": message,
@ -64,20 +64,20 @@ func (r *RecoveryEmailSender) SendRecoveryEmail(email string, signature string)
return err
}
req := r.deps.FiberClient.Post(url).Body(form.Bytes()).ContentType(writer.FormDataContentType())
if r.deps.ApiKey != "" {
req.Set("Authorization", r.deps.ApiKey)
req := r.fiberClient.Post(r.apiUrl).Body(form.Bytes()).ContentType(writer.FormDataContentType())
if r.apiKey != "" {
req.Set("Authorization", r.apiKey)
}
statusCode, body, errs := req.Bytes()
if errs != nil {
r.deps.Logger.Error("Error sending request", zap.Error(errs[0]))
r.logger.Error("Error sending request", zap.Error(errs[0]))
return errs[0]
}
if statusCode != fiber.StatusOK {
err := fmt.Errorf("the SMTP service returned an error: %s Response body: %s", statusCode, body)
r.deps.Logger.Error("Error sending email", zap.Error(err))
r.logger.Error("Error sending email", zap.Error(err))
return err
}

@ -53,7 +53,7 @@ func Run(ctx context.Context, cfg initialize.Config, logger *zap.Logger, build B
return zapcore.NewTee(core, clickHouseLogger)
}))
loggerHlog := hlog.New(loggerForHlog).Module(cfg.ModuleLogger)
loggerHlog := hlog.New(loggerForHlog).Module(initialize.ModuleLogger)
loggerHlog.With(models.AllFields{})
loggerHlog.Emit(app.InfoSvcStarted{})
@ -71,9 +71,9 @@ func Run(ctx context.Context, cfg initialize.Config, logger *zap.Logger, build B
}
kafkaTariffClient, err := kgo.NewClient(
kgo.SeedBrokers(cfg.KafkaBrokers),
kgo.SeedBrokers(cfg.KafkaBrokers...),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
kgo.DefaultProduceTopic(cfg.KafkaTopic),
kgo.DefaultProduceTopic(cfg.KafkaTopicTariff),
)
if err != nil {
return err
@ -84,7 +84,7 @@ func Run(ctx context.Context, cfg initialize.Config, logger *zap.Logger, build B
return err
}
discountRpcClient, err := initialize.DiscountGRPCClient(cfg.DiscountServiceAddress)
discountRpcClient, err := initialize.DiscountGRPCClient(cfg.DiscountMicroserviceGRPC)
if err != nil {
logger.Error("failed to connect to discount service", zap.Error(err))
return err
@ -93,7 +93,7 @@ func Run(ctx context.Context, cfg initialize.Config, logger *zap.Logger, build B
brokers := initialize.NewBrokers(initialize.BrokersDeps{
Logger: logger,
TariffClient: kafkaTariffClient,
Topic: cfg.KafkaTopic,
Topic: cfg.KafkaTopicTariff,
})
rdb, err := initialize.Redis(ctx, cfg)
@ -134,15 +134,13 @@ func Run(ctx context.Context, cfg initialize.Config, logger *zap.Logger, build B
Logger: logger,
Service: recoveryService,
DefaultURL: cfg.DefaultRedirectionURL,
RecoveryURL: cfg.RecoveryUrl,
RecoveryURL: cfg.MailRecoveryURL,
})
clientPromoCodeController := client_promocode.NewPromoCodeController(client_promocode.Deps{Logger: logger, PromoCodeService: promoService})
adminRecoveryController := admin_recovery.NewRecoveryController(admin_recovery.Deps{
Logger: logger,
Service: recoveryService,
DefaultURL: cfg.DefaultRedirectionURL,
RecoveryURL: cfg.RecoveryUrl,
})
adminPromoCodeController := admin_promocode.NewPromoCodeController(admin_promocode.Deps{Logger: logger, PromoCodeService: promoService})
controllerRpc := rpc_controllers.InitRpcControllers(promoService)
@ -184,23 +182,20 @@ func Run(ctx context.Context, cfg initialize.Config, logger *zap.Logger, build B
})
go func() {
if err := clientServer.Start(cfg.HTTPClientHost + ":" + cfg.HTTPClientPort); err != nil {
if err := clientServer.Start(cfg.ClientHttpURL); err != nil {
logger.Error("Client server startup error", zap.Error(err))
cancel()
}
}()
go func() {
if err := adminServer.Start(cfg.HTTPAdminHost + ":" + cfg.HTTPAdminPort); err != nil {
if err := adminServer.Start(cfg.AdminHttpURL); err != nil {
logger.Error("Admin server startup error", zap.Error(err))
cancel()
}
}()
go grpcServer.Run(grpc.DepsGrpcRun{
Host: cfg.GrpcHost,
Port: cfg.GrpcPort,
})
go grpcServer.Run(cfg.GrpcURL)
clientServer.ListRoutes()
adminServer.ListRoutes()

@ -11,23 +11,17 @@ import (
type Deps struct {
Logger *zap.Logger
Service *services.RecoveryService
DefaultURL string
RecoveryURL string
}
type RecoveryController struct {
logger *zap.Logger
service *services.RecoveryService
defaultURL string
recoveryURL string
}
func NewRecoveryController(deps Deps) *RecoveryController {
return &RecoveryController{
logger: deps.Logger,
service: deps.Service,
defaultURL: deps.DefaultURL,
recoveryURL: deps.RecoveryURL,
}
}

@ -2,29 +2,22 @@ package initialize
import (
"gitea.pena/PenaSide/codeword/internal/adapters/client"
"github.com/gofiber/fiber/v2"
"go.uber.org/zap"
)
func RecoveryEmailSender(cfg Config, logger *zap.Logger) *client.RecoveryEmailSender {
return client.NewRecoveryEmailSender(client.RecoveryEmailSenderDeps{
SmtpApiUrl: cfg.SmtpApiUrl,
SmtpHost: cfg.SmtpHost,
SmtpPort: cfg.SmtpPort,
SmtpSender: cfg.SmtpSender,
Username: cfg.SmtpUsername,
Password: cfg.SmtpPassword,
ApiKey: cfg.SmtpApiKey,
FiberClient: &fiber.Client{},
ApiUrl: cfg.ExternalCfg.MailClientCfg.ApiURL,
Sender: cfg.ExternalCfg.MailClientCfg.Sender,
ApiKey: cfg.ExternalCfg.MailClientCfg.ApiKey,
Logger: logger,
RecoveryUrl: cfg.RecoveryUrl,
RecoveryUrl: cfg.MailRecoveryURL,
})
}
func AuthClient(cfg Config, logger *zap.Logger) *client.AuthClient {
return client.NewAuthClient(client.AuthClientDeps{
AuthUrl: cfg.AuthURL,
AuthUrl: cfg.AuthMicroserviceURL,
Logger: logger,
FiberClient: &fiber.Client{},
})
}

@ -3,44 +3,50 @@ package initialize
import (
"gitea.pena/PenaSide/common/mongo"
"github.com/caarlos0/env/v8"
"github.com/gofiber/fiber/v2"
"github.com/joho/godotenv"
"log"
)
type Config struct {
AppName string `env:"APP_NAME" envDefault:"codeword"`
HTTPClientHost string `env:"HTTP_CLIENT_HOST" envDefault:"localhost"`
HTTPClientPort string `env:"HTTP_CLIENT_PORT" envDefault:"3000"`
HTTPAdminHost string `env:"HTTP_ADMIN_HOST" envDefault:"localhost"`
HTTPAdminPort string `env:"HTTP_ADMIN_PORT" envDefault:"3001"`
PublicCurveKey string `env:"PUBLIC_CURVE_KEY"`
PrivateCurveKey string `env:"PRIVATE_CURVE_KEY"`
SignSecret string `env:"SIGN_SECRET"`
RedisAddr string `env:"REDIS_ADDR" envDefault:"localhost:6379"`
RedisPassword string `env:"REDIS_PASS" envDefault:"admin"`
RedisDB int `env:"REDIS_DB" envDefault:"2"`
SmtpApiUrl string `env:"SMTP_API_URL"`
SmtpHost string `env:"SMTP_HOST"`
SmtpPort string `env:"SMTP_PORT"`
SmtpUsername string `env:"SMTP_UNAME"`
SmtpPassword string `env:"SMTP_PASS"`
SmtpApiKey string `env:"SMTP_API_KEY"`
SmtpSender string `env:"SMTP_SENDER"`
DefaultRedirectionURL string `env:"DEFAULT_REDIRECTION_URL"`
AuthURL string `env:"AUTH_EXCHANGE_URL"`
KafkaBrokers string `env:"KAFKA_BROKERS"`
KafkaTopic string `env:"KAFKA_TOPIC_TARIFF"`
DiscountServiceAddress string `env:"DISCOUNT_ADDRESS"`
RecoveryUrl string `env:"RECOVERY_URL"`
ClientHttpURL string `env:"CLIENT_HTTP_URL,required" envDefault:"localhost:3000"`
AdminHttpURL string `env:"ADMIN_HTTP_URL,required" envDefault:"localhost:3001"`
GrpcURL string `env:"GRPC_URL,required" envDefault:"localhost:9000"`
RedisHost string `env:"REDIS_HOST,required" envDefault:"localhost:6379"`
RedisPassword string `env:"REDIS_PASSWORD,required" envDefault:"admin"`
RedisDB int `env:"REDIS_DB,required" envDefault:"2"`
KafkaTopicTariff string `env:"KAFKA_TOPIC_TARIFF,required"`
KafkaBrokers []string `env:"KAFKA_BROKERS,required"`
AuthMicroserviceURL string `env:"AUTH_MICROSERVICE_URL,required"`
DiscountMicroserviceGRPC string `env:"DISCOUNT_MICROSERVICE_GRPC_URL,required"`
TrashLogHost string `env:"TRASH_LOG_HOST,required" envDefault:"localhost:7113"`
MailRecoveryURL string `env:"MAIL_RECOVERY_URL,required"`
EncryptPublicKey string `env:"ENCRYPT_PUBLIC_KEY,required"`
EncryptPrivateKey string `env:"ENCRYPT_PRIVATE_KEY,required"`
EncryptSignSecret string `env:"ENCRYPT_SIGN_SECRET,required"`
DefaultRedirectionURL string `env:"DEFAULT_REDIRECTION_URL,required"`
ExternalCfg ExternalCfg
}
type ExternalCfg struct {
MailClientCfg MailClientCfg
Database mongo.Configuration
JwtCfg JWTConfiguration
}
type MailClientCfg struct {
ApiURL string `env:"API_URL,required"`
Sender string `env:"MAIL_SENDER,required"`
ApiKey string `env:"MAIL_API_KEY,required"`
FiberClient *fiber.Client
}
type JWTConfiguration struct {
PrivateKey string `env:"JWT_PRIVATE_KEY"`
PublicKey string `env:"JWT_PUBLIC_KEY,required"`
Issuer string `env:"JWT_ISSUER,required"`
Audience string `env:"JWT_AUDIENCE,required"`
GrpcHost string `env:"GRPC_HOST" envDefault:"localhost"`
GrpcPort string `env:"GRPC_PORT" envDefault:"9000"`
TrashLogHost string `env:"TRASH_LOG_HOST" envDefault:"localhost:7113"`
ModuleLogger string `env:"MODULE_LOGGER" envDefault:"codeword-local"`
DataBase mongo.Configuration
}
func LoadConfig() (*Config, error) {
@ -53,3 +59,5 @@ func LoadConfig() (*Config, error) {
}
return &config, nil
}
const ModuleLogger = "codeword"

@ -6,8 +6,8 @@ import (
func Encrypt(cfg Config) *encrypt.Encrypt {
return encrypt.New(&encrypt.EncryptDeps{
PublicKey: cfg.PublicCurveKey,
PrivateKey: cfg.PrivateCurveKey,
SignSecret: cfg.SignSecret,
PublicKey: cfg.EncryptPublicKey,
PrivateKey: cfg.EncryptPrivateKey,
SignSecret: cfg.EncryptSignSecret,
})
}

@ -14,7 +14,7 @@ func MongoDB(ctx context.Context, cfg Config) (*mongo.Database, error) {
defer cancel()
mongoDeps := &mdb.ConnectDeps{
Configuration: &cfg.DataBase,
Configuration: &cfg.ExternalCfg.Database,
Timeout: 10 * time.Second,
}

@ -7,7 +7,7 @@ import (
func Redis(ctx context.Context, cfg Config) (*redis.Client, error) {
rdb := redis.NewClient(&redis.Options{
Addr: cfg.RedisAddr,
Addr: cfg.RedisHost,
Password: cfg.RedisPassword,
DB: cfg.RedisDB,
})

@ -36,13 +36,8 @@ func NewGRPC(logger *zap.Logger) (*GRPC, error) {
}, nil
}
type DepsGrpcRun struct {
Host string
Port string
}
func (g *GRPC) Run(config DepsGrpcRun) {
connectionString := fmt.Sprintf("%s:%s", config.Host, config.Port)
func (g *GRPC) Run(addr string) {
connectionString := fmt.Sprintf(addr)
g.logger.Info("Starting GRPC Server", zap.String("host", connectionString))

@ -19,10 +19,10 @@ type JWT struct {
func NewJWT(configuration *initialize.Config) *JWT {
return &JWT{
privateKey: []byte(configuration.PrivateKey),
publicKey: []byte(configuration.PublicKey),
issuer: configuration.Issuer,
audience: configuration.Audience,
privateKey: []byte(configuration.ExternalCfg.JwtCfg.PrivateKey),
publicKey: []byte(configuration.ExternalCfg.JwtCfg.PublicKey),
issuer: configuration.ExternalCfg.JwtCfg.Issuer,
audience: configuration.ExternalCfg.JwtCfg.Audience,
algorithm: jwt.SigningMethodRS256,
expiresIn: 15 * time.Minute,
}

@ -30,9 +30,13 @@ func InitializeJWT() *middleware.JWT {
-----END RSA PRIVATE KEY-----`, "\t", "", -1)
return middleware.NewJWT(&initialize.Config{
ExternalCfg: initialize.ExternalCfg{
JwtCfg: initialize.JWTConfiguration{
PrivateKey: privateKey,
PublicKey: publicKey,
Audience: "pena",
Issuer: "pena-auth-service",
},
},
})
}