Skip to content

Commit

Permalink
Update config file and remove todo reminders
Browse files Browse the repository at this point in the history
Also, update test and docker related files
  • Loading branch information
jessicatarra committed Dec 17, 2023
1 parent 1107e9a commit 3ae10ba
Show file tree
Hide file tree
Showing 7 changed files with 87 additions and 58 deletions.
4 changes: 1 addition & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ WORKDIR /bin
COPY . .
RUN go mod download && go mod verify && go mod vendor
ARG API_VERSION="v0.0.0+unknown"
ARG API_PORT="unknown"
ARG API_ENV="unknown"
RUN go build -ldflags "-X 'main.version=$API_VERSION' -X 'main.port=$API_PORT' -X 'main.env=$API_ENV'" -o api ./cmd/api
RUN go build -ldflags "-X 'main.version=$API_VERSION'" -o api ./cmd/api

# Run stage
FROM golang:${GO_VERSION}-alpine3.17 AS build-release-stage
Expand Down
4 changes: 2 additions & 2 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ func run(logger *slog.Logger) error {
defer db.Close()

initMetrics(db)
//TODO: add config variable
grpcConn, err := grpc.Dial("localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))

grpcConn, err := grpc.Dial(cfg.Auth.GrpcBaseURL, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
logger.Error("did not connect:", err)
return err
Expand Down
32 changes: 16 additions & 16 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,22 @@ services:
POSTGRES_DB: "greenlight"
restart: always

greenlight:
build:
context: .
args:
API_VERSION: "v1.0.0"
API_PORT: "8080"
API_ENV: "staging"
dockerfile: Dockerfile
container_name: greenlight-api
hostname: greenlight-api
env_file: .env
ports:
- "8080:8080"
depends_on:
- database
command: [ "/bin/api"]
#TODO: update docker compose for greenlight app
# greenlight:
# build:
# context: .
# args:
# API_VERSION: "v1.0.0"
# dockerfile: Dockerfile
# container_name: greenlight-api
# hostname: greenlight-api
# env_file: .env
# ports:
# - "8080:8080"
# - "8080:8082"
# depends_on:
# - database
# command: [ "/bin/api"]



Expand Down
48 changes: 25 additions & 23 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,17 @@ package config
import (
"flag"
"fmt"
"os"
"strconv"
"strings"
)

var (
Version string
port string
env string
)

type Config struct {
BaseURL string
Port int
Env string
DB struct {
Port int
Env string
DB struct {
Dsn string
MaxOpenConns int
MaxIdleConns int
Expand All @@ -37,34 +32,41 @@ type Config struct {
Jwt struct {
Secret string
}
Auth struct {
HttpBaseURL string
GrpcBaseURL string
GrpcServerPort int
HttpPort int
}
}

func Init() (cfg Config, err error) {
intPort, _ := strconv.Atoi(port)

flag.StringVar(&cfg.BaseURL, "base-url", os.Getenv("BASE_URL"), "base URL for the application")
flag.IntVar(&cfg.Port, "port", intPort, "API server port")
flag.StringVar(&cfg.Env, "env", env, "Environment (development|staging|production)")
flag.StringVar(&cfg.DB.Dsn, "db-dsn", os.Getenv(
"DATABASE_URL"), "PostgreSQL DSN")
flag.IntVar(&cfg.Port, "port", 8080, "API server port")
flag.StringVar(&cfg.Env, "env", "development", "Environment (development|staging|production)")
flag.StringVar(&cfg.DB.Dsn, "db-dsn", "postgres://greenlight:pa55word@localhost/greenlight?sslmode=disable", "PostgreSQL DSN")
flag.IntVar(&cfg.DB.MaxOpenConns, "db-max-open-conns", 25, "PostgreSQL max open connections")
flag.IntVar(&cfg.DB.MaxIdleConns, "db-max-idle-conns", 25, "PostgreSQL max idle connections")
flag.StringVar(&cfg.DB.MaxIdleTime, "db-max-idle-time", "15m", "PostgreSQL max connection idle time")

smtpPort, _ := strconv.Atoi(os.Getenv("SMTP_PORT"))

flag.StringVar(&cfg.Smtp.Host, "smtp-host", os.Getenv("SMTP_HOST"), "SMTP host")
flag.IntVar(&cfg.Smtp.Port, "smtp-port", smtpPort, "SMTP port")
flag.StringVar(&cfg.Smtp.Username, "smtp-username", os.Getenv("SMTP_USERNAME"), "SMTP username")
flag.StringVar(&cfg.Smtp.Password, "smtp-password", os.Getenv("SMTP_PASSWORD"), "SMTP password")
flag.StringVar(&cfg.Smtp.From, "smtp-sender", os.Getenv("SMTP_SENDER"), "SMTP sender")
flag.StringVar(&cfg.Smtp.Host, "smtp-host", "example.smtp.host", "SMTP host")
flag.IntVar(&cfg.Smtp.Port, "smtp-port", 25, "SMTP port")
flag.StringVar(&cfg.Smtp.Username, "smtp-username", "example_username", "SMTP username")
flag.StringVar(&cfg.Smtp.Password, "smtp-password", "example_password", "SMTP password")
flag.StringVar(&cfg.Smtp.From, "smtp-sender", "Example Name <no-reply@example.org>", "SMTP sender")

flag.Func("cors-trusted-origins", "Trusted CORS origins (space separated)", func(val string) error {
cfg.Cors.TrustedOrigins = strings.Fields(val)
return nil
})

flag.StringVar(&cfg.Jwt.Secret, "jwt-secret", os.Getenv("JWT_SECRET"), "JWT secret")
flag.StringVar(&cfg.Jwt.Secret, "jwt-secret", "56vphh6sheco5sbtfkxwesy3wx7fpiip", "JWT secret")

flag.StringVar(&cfg.Auth.HttpBaseURL, "base-url", "http://localhost:8080", "base URL for the application")
flag.StringVar(&cfg.Auth.GrpcBaseURL, "auth-grpc-client-base-url", "localhost:50051", "GRPC client")

flag.IntVar(&cfg.Auth.HttpPort, "auth-http-port", 8082, "port to listen on for HTTP requests for auth module")

flag.IntVar(&cfg.Auth.GrpcServerPort, "auth-grpc-port", 50051, "port to listen on for GRPC methods for auth module")

displayVersion := flag.Bool("version", false, "Display version and exit")

Expand Down
8 changes: 4 additions & 4 deletions ms/auth/internal/application/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@ func (a *appl) CreateAuthTokenUseCase(userID int64) ([]byte, error) {
claims.Issued = jwt.NewNumericTime(time.Now())
claims.NotBefore = jwt.NewNumericTime(time.Now())
claims.Expires = jwt.NewNumericTime(time.Now().Add(24 * time.Hour))
claims.Issuer = a.cfg.BaseURL
claims.Audiences = []string{a.cfg.BaseURL}
claims.Issuer = a.cfg.Auth.HttpBaseURL
claims.Audiences = []string{a.cfg.Auth.HttpBaseURL}

jwtBytes, err := claims.HMACSign(jwt.HS256, []byte(a.cfg.Jwt.Secret))
if err != nil {
Expand All @@ -127,12 +127,12 @@ func (a *appl) ValidateAuthTokenUseCase(token string) (*domain.User, error) {
return nil, err
}

if claims.Issuer != a.cfg.BaseURL {
if claims.Issuer != a.cfg.Auth.HttpBaseURL {
return nil, err

}

if !claims.AcceptAudience(a.cfg.BaseURL) {
if !claims.AcceptAudience(a.cfg.Auth.HttpBaseURL) {
return nil, err

}
Expand Down
40 changes: 35 additions & 5 deletions ms/auth/internal/application/application_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ func Init() (mocks.UserRepository, mocks.TokenRepository, mocks.PermissionReposi
permissionRepo := mocks.PermissionRepository{}
wg := sync.WaitGroup{}
cfg := config.Config{
BaseURL: "localhost:8082",
Jwt: struct {
Secret string
}{
Expand All @@ -43,6 +42,17 @@ func Init() (mocks.UserRepository, mocks.TokenRepository, mocks.PermissionReposi
Password: "password",
From: "Greenlight <no-reply@tarralva.com>",
},
Auth: struct {
HttpBaseURL string
GrpcBaseURL string
GrpcServerPort int
HttpPort int
}{
HttpBaseURL: "localhost:8082",
GrpcBaseURL: "localhost:50051",
GrpcServerPort: 50051,
HttpPort: 8082,
},
}
return userRepo, tokenRepo, permissionRepo, cfg, wg
}
Expand Down Expand Up @@ -282,8 +292,8 @@ func TestAppl_CreateAuthTokenUseCase(t *testing.T) {

expectedUserID := int64(1)
expectedSubject := strconv.FormatInt(expectedUserID, 10)
expectedIssuer := cfg.BaseURL
expectedAudience := []string{cfg.BaseURL}
expectedIssuer := cfg.Auth.HttpBaseURL
expectedAudience := []string{cfg.Auth.HttpBaseURL}

// Act
tokenBytes, err := appl.CreateAuthTokenUseCase(expectedUserID)
Expand All @@ -299,7 +309,17 @@ func TestAppl_CreateAuthTokenUseCase(t *testing.T) {
t.Run("Error", func(t *testing.T) {
// Arrange
cfg := config.Config{
BaseURL: "localhost:8082",
Auth: struct {
HttpBaseURL string
GrpcBaseURL string
GrpcServerPort int
HttpPort int
}{
HttpBaseURL: "localhost:8082",
GrpcBaseURL: "localhost:50051",
GrpcServerPort: 50051,
HttpPort: 8082,
},
}
userRepo, tokenRepo, permissionRepo, _, wg := Init()
appl := NewAppl(&userRepo, &tokenRepo, &permissionRepo, &wg, cfg)
Expand Down Expand Up @@ -341,7 +361,17 @@ func TestAppl_ValidateAuthTokenUseCase(t *testing.T) {
// Arrange
userRepo, tokenRepo, permissionRepo, _, wg := Init()
cfg := config.Config{
BaseURL: "localhost:8082",
Auth: struct {
HttpBaseURL string
GrpcBaseURL string
GrpcServerPort int
HttpPort int
}{
HttpBaseURL: "localhost:8082",
GrpcBaseURL: "localhost:50051",
GrpcServerPort: 50051,
HttpPort: 8082,
},
}
appl := NewAppl(&userRepo, &tokenRepo, &permissionRepo, &wg, cfg)
expectedUserID := int64(1)
Expand Down
9 changes: 4 additions & 5 deletions ms/auth/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type module struct {
grpc *grpc.Server
server *http.Server
logger *slog.Logger
cfg *config.Config
}

func (m module) Start(wg *sync.WaitGroup) {
Expand All @@ -51,8 +52,7 @@ func (m module) Start(wg *sync.WaitGroup) {

go func() {
defer wg.Done()
//TODO: add config variable
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", 50051))
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", m.cfg.Auth.GrpcServerPort))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
Expand Down Expand Up @@ -88,14 +88,13 @@ func NewModule(db *sql.DB, cfg config.Config, wg *sync.WaitGroup, logger *slog.L
pb.RegisterAuthGRPCServiceServer(grpcServer, _grpc.NewGRPCServer(appl))

srv := &http.Server{
//TODO: add config variable
Addr: fmt.Sprintf(":%d", 8082),
Addr: fmt.Sprintf(":%d", cfg.Auth.HttpPort),
Handler: api.Routes(),
ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelWarn),
IdleTimeout: defaultIdleTimeout,
ReadTimeout: defaultReadTimeout,
WriteTimeout: defaultWriteTimeout,
}

return &module{grpc: grpcServer, server: srv, logger: logger}
return &module{grpc: grpcServer, server: srv, logger: logger, cfg: &cfg}
}

0 comments on commit 3ae10ba

Please sign in to comment.