Skip to content

Commit 89f67b3

Browse files
committed
Refactor: Changes code structure for schema and config
1 parent adf9ac4 commit 89f67b3

File tree

15 files changed

+230
-96
lines changed

15 files changed

+230
-96
lines changed

Dockerfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ ENV GOPROXY=direct
77
RUN apk add --no-cache make postgresql-client git curl
88

99
COPY go.mod go.sum ./
10+
RUN go mod tidy
1011
RUN go mod download
1112

1213
# Development Mode

docker-compose.dev.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
services:
22
app:
3-
build:
3+
build:
44
context: .
55
target: dev
66
ports:
@@ -31,4 +31,4 @@ services:
3131
restart: unless-stopped
3232

3333
volumes:
34-
postgres_data_dev:
34+
postgres_data_dev:

docker-compose.prod.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
services:
22
app:
3-
build:
3+
build:
44
context: .
55
target: prod
66
ports:

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ go 1.23.0
55
require (
66
github.com/gin-contrib/cors v1.7.5
77
github.com/gin-gonic/gin v1.10.1
8+
github.com/google/uuid v1.6.0
89
github.com/rs/zerolog v1.34.0
910
github.com/stretchr/testify v1.10.0
1011
gorm.io/gorm v1.30.0

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5x
3535
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
3636
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
3737
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
38+
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
39+
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
3840
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
3941
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
4042
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=

internal/api/main.go

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,53 +9,72 @@ import (
99
"github.com/gin-contrib/cors"
1010
"github.com/gin-gonic/gin"
1111

12+
"github.com/sdslabs/nymeria/internal/config"
1213
"github.com/sdslabs/nymeria/internal/database"
13-
"github.com/sdslabs/nymeria/internal/log"
14+
"github.com/sdslabs/nymeria/internal/logger"
15+
"github.com/sdslabs/nymeria/internal/middlewares"
1416
)
1517

1618
func Start() {
19+
// Initialize global configuration
20+
config.Init()
21+
1722
if err := database.Init(); err != nil {
1823
panic(err)
1924
}
2025

2126
r := gin.Default()
2227

2328
// Use custom logging middleware
24-
r.Use(log.LoggerMiddleware(log.Logger))
29+
r.Use(logger.Middleware(logger.Logger))
2530

2631
// CORS configuration
27-
config := cors.New(cors.Config{
32+
corsConfig := cors.New(cors.Config{
2833
AllowOrigins: []string{"http://localhost:3000"}, // TODO: change in prod
2934
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
30-
AllowHeaders: []string{"Authorization", "Content-Type"},
35+
AllowHeaders: []string{"Authorization", "Content-Type", "X-CSRF-Token", "X-User-ID"},
3136
ExposeHeaders: []string{"Content-Length"},
3237
AllowCredentials: true,
3338
MaxAge: 12 * 3600, // 12 hours in seconds
3439
})
3540

36-
r.Use(config)
41+
r.Use(corsConfig)
3742

3843
r.GET("/", func(c *gin.Context) {
39-
log.Logger.Info().Msg("welcome")
44+
logger.Info().Msg("welcome")
4045
c.JSON(http.StatusOK, gin.H{
4146
"status": "success",
4247
"message": "welcome",
4348
})
4449
})
4550

4651
r.GET("/ping", func(c *gin.Context) {
47-
log.Logger.Info().Msg("ping")
52+
logger.Info().Msg("ping")
53+
logger.Info().Msg(config.AppConfig.DBHost)
4854
c.JSON(http.StatusOK, gin.H{
4955
"status": "success",
5056
"message": "pong",
5157
})
5258
})
5359

5460
r.GET("/register", HandleGetRegistrationFlow)
55-
r.POST("/register", HandlePostRegistrationFlow)
61+
r.POST("/register", middlewares.CSRFMiddleware(), HandlePostRegistrationFlow)
5662

5763
r.GET("/login", HandleGetLoginFlow)
58-
r.POST("/login", HandlePostLoginFlow)
64+
r.POST("/login", middlewares.CSRFMiddleware(), HandlePostLoginFlow)
65+
66+
r.GET("/applications", HandleGetApplicationFlow)
67+
r.POST("/applications", HandleFetchAllApplicationsFlow)
68+
r.POST("/applications/:id", HandleFetchApplicationByIDFlow)
69+
70+
r.GET("/applications/create", HandleGetApplicationFlow)
71+
r.POST("/applications/create", middlewares.CSRFMiddleware(), HandleCreateApplicationFlow)
72+
73+
r.GET("/applications/update", HandleGetApplicationFlow)
74+
r.POST("/applications/update", middlewares.CSRFMiddleware(), HandleUpdateApplicationFlow)
75+
76+
r.GET("/applications/delete", HandleGetApplicationFlow)
77+
r.DELETE("/applications/delete/:id", middlewares.CSRFMiddleware(), HandleDeleteApplicationFlow)
5978

6079
r.Run(":9898")
6180
}

internal/api/register.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ import (
1010
"github.com/gin-gonic/gin"
1111

1212
"github.com/sdslabs/nymeria/internal/database"
13-
"github.com/sdslabs/nymeria/internal/log"
13+
"github.com/sdslabs/nymeria/internal/database/schema"
14+
"github.com/sdslabs/nymeria/internal/logger"
1415
)
1516

1617
// HandleGetRegistrationFlow handles the GET request for the registration flow.
@@ -26,7 +27,7 @@ func HandlePostRegistrationFlow(c *gin.Context) {
2627
var req RegistrationRequest
2728
err := c.ShouldBindJSON(&req)
2829
if err != nil {
29-
log.Logger.Err(err).Msg("invalid json")
30+
logger.Err(err).Msg("invalid json")
3031
c.JSON(http.StatusBadRequest, gin.H{
3132
"status": "error",
3233
"message": err.Error(),
@@ -63,7 +64,7 @@ func HandlePostRegistrationFlow(c *gin.Context) {
6364
return
6465
}
6566

66-
user := database.User{
67+
user := schema.User{
6768
Username: req.Username,
6869
Password: req.Password,
6970
Email: req.Email,
@@ -77,7 +78,7 @@ func HandlePostRegistrationFlow(c *gin.Context) {
7778
"message": "GitHub ID already exists",
7879
})
7980
} else {
80-
log.Logger.Err(result.Error).Msg("failed to insert user")
81+
logger.Err(result.Error).Msg("failed to insert user")
8182
}
8283
return
8384
}

internal/api/types.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,20 @@ type LoginRequest struct {
1111
Username string `json:"username"`
1212
Password string `json:"password"`
1313
}
14+
15+
type CreateApplicationRequest struct {
16+
Name string `json:"name" binding:"required"`
17+
ApplicationURL string `json:"application_url" binding:"required"`
18+
CSRFToken string `json:"csrf_token" binding:"required"`
19+
AllowedOrigins []string `json:"allowed_origins" binding:"required"`
20+
RedirectURIs []string `json:"redirect_uris" binding:"required"`
21+
}
22+
23+
type UpdateApplicationRequest struct {
24+
ApplicationID string `json:"application_id" binding:"required"`
25+
CSRFToken string `json:"csrf_token" binding:"required"`
26+
ApplicationURL string `json:"application_url" binding:"omitempty"`
27+
AllowedOrigins []string `json:"allowed_origins" binding:"omitempty"`
28+
RedirectURIs []string `json:"redirect_uris" binding:"omitempty"`
29+
NewKeyFlag bool `json:"new_key_flag" binding:"omitempty"`
30+
}

internal/config/config.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Copyright (c) 2025 SDSLabs
2+
// SPDX-License-Identifier: MIT
3+
4+
package config
5+
6+
import (
7+
"os"
8+
"strconv"
9+
)
10+
11+
// Global configuration instance
12+
var AppConfig *Config
13+
14+
// GetEnvOrDefault retrieves the value of the environment variable named by key.
15+
// If the environment variable is not set or is empty, it returns the default value.
16+
func GetEnvOrDefault(key, defaultValue string) string {
17+
if value := os.Getenv(key); value != "" {
18+
return value
19+
}
20+
return defaultValue
21+
}
22+
23+
func ParseIntGetEnvOrDefault(key, defaultValue string) int {
24+
value, err := strconv.Atoi(GetEnvOrDefault(key, defaultValue))
25+
if err != nil {
26+
value, _ = strconv.Atoi(defaultValue)
27+
}
28+
return value
29+
}
30+
31+
// LoadConfig loads configuration from environment variables
32+
func LoadConfig() *Config {
33+
return &Config{
34+
DBHost: GetEnvOrDefault("DB_HOST", "localhost"),
35+
DBUser: GetEnvOrDefault("DB_USER", "nymeria"),
36+
DBPassword: GetEnvOrDefault("DB_PASS", "password"),
37+
DBName: GetEnvOrDefault("DB_NAME", "nymeria"),
38+
DBPort: GetEnvOrDefault("DB_PORT", "5432"),
39+
40+
CSRFSecret: GetEnvOrDefault("CSRF_SECRET", "csrf-secret-key-32"),
41+
CSRFMaxAge: ParseIntGetEnvOrDefault("CSRF_MAX_AGE", "2"),
42+
JWTSecret: GetEnvOrDefault("JWT_SECRET", "jwt-secret-key-32"),
43+
JWTMaxAge: ParseIntGetEnvOrDefault("JWT_MAX_AGE", "2"),
44+
45+
EnvMode: GetEnvOrDefault("ENV_MODE", "development"),
46+
}
47+
}
48+
49+
// Init initializes the global configuration
50+
func Init() {
51+
AppConfig = LoadConfig()
52+
}

internal/config/types.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package config
2+
3+
// DatabaseConfig holds database configuration
4+
type Config struct {
5+
DBHost string `env:"DB_HOST"`
6+
DBUser string `env:"DB_USER"`
7+
DBPassword string `env:"DB_PASSWORD"`
8+
DBName string `env:"DB_NAME"`
9+
DBPort string `env:"DB_PORT"`
10+
11+
CSRFSecret string `env:"CSRF_SECRET"`
12+
CSRFMaxAge int `env:"CSRF_MAX_AGE"` // in minutes
13+
JWTSecret string `env:"JWT_SECRET"`
14+
JWTMaxAge int `env:"JWT_MAX_AGE"` // in days
15+
16+
EnvMode string `env:"ENV_MODE"`
17+
}

0 commit comments

Comments
 (0)