Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ go.work.sum

# env file
.env
.env.dev

main
*.db
Expand Down
14 changes: 14 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch NovaMD Server",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/server/cmd/server/main.go",
"cwd": "${workspaceFolder}",
"envFile": "${workspaceFolder}/server/.env"
}
]
}
7 changes: 6 additions & 1 deletion server/cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"log"

"novamd/internal/app"
"novamd/internal/logging"
)

// @title NovaMD API
Expand All @@ -23,6 +24,10 @@ func main() {
log.Fatal("Failed to load configuration:", err)
}

// Setup logging
logging.Setup(cfg.LogLevel)
logging.Debug("Configuration loaded", "config", cfg.Redact())

// Initialize and start server
options, err := app.DefaultOptions(cfg)
if err != nil {
Expand All @@ -32,7 +37,7 @@ func main() {
server := app.NewServer(options)
defer func() {
if err := server.Close(); err != nil {
log.Println("Error closing server:", err)
logging.Error("Failed to close server:", err)
}
}()

Expand Down
28 changes: 26 additions & 2 deletions server/internal/app/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package app

import (
"fmt"
"novamd/internal/logging"
"novamd/internal/secrets"
"os"
"strconv"
Expand All @@ -25,6 +26,7 @@ type Config struct {
RateLimitRequests int
RateLimitWindow time.Duration
IsDevelopment bool
LogLevel logging.LogLevel
}

// DefaultConfig returns a new Config instance with default values
Expand Down Expand Up @@ -54,6 +56,16 @@ func (c *Config) validate() error {
return nil
}

// Redact redacts sensitive fields from a Config instance
func (c *Config) Redact() *Config {
redacted := *c
redacted.AdminPassword = "[REDACTED]"
redacted.AdminEmail = "[REDACTED]"
redacted.EncryptionKey = "[REDACTED]"
redacted.JWTSigningKey = "[REDACTED]"
return &redacted
}

// LoadConfig creates a new Config instance with values from environment variables
func LoadConfig() (*Config, error) {
config := DefaultConfig()
Expand Down Expand Up @@ -97,17 +109,29 @@ func LoadConfig() (*Config, error) {

// Configure rate limiting
if reqStr := os.Getenv("NOVAMD_RATE_LIMIT_REQUESTS"); reqStr != "" {
if parsed, err := strconv.Atoi(reqStr); err == nil {
parsed, err := strconv.Atoi(reqStr)
if err == nil {
config.RateLimitRequests = parsed
}
}

if windowStr := os.Getenv("NOVAMD_RATE_LIMIT_WINDOW"); windowStr != "" {
if parsed, err := time.ParseDuration(windowStr); err == nil {
parsed, err := time.ParseDuration(windowStr)
if err == nil {
config.RateLimitWindow = parsed
}
}

// Configure log level, if isDevelopment is set, default to debug
if logLevel := os.Getenv("NOVAMD_LOG_LEVEL"); logLevel != "" {
parsed := logging.ParseLogLevel(logLevel)
config.LogLevel = parsed
} else if config.IsDevelopment {
config.LogLevel = logging.DEBUG
} else {
config.LogLevel = logging.INFO
}

// Validate all settings
if err := config.validate(); err != nil {
return nil, err
Expand Down
2 changes: 2 additions & 0 deletions server/internal/app/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"os"
"testing"
"time"

_ "novamd/internal/testenv"
)

func TestDefaultConfig(t *testing.T) {
Expand Down
44 changes: 25 additions & 19 deletions server/internal/app/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,21 @@ package app
import (
"database/sql"
"fmt"
"log"
"time"

"golang.org/x/crypto/bcrypt"

"novamd/internal/auth"
"novamd/internal/db"
"novamd/internal/logging"
"novamd/internal/models"
"novamd/internal/secrets"
"novamd/internal/storage"
)

// initSecretsService initializes the secrets service
func initSecretsService(cfg *Config) (secrets.Service, error) {
logging.Debug("initializing secrets service")
secretsService, err := secrets.NewService(cfg.EncryptionKey)
if err != nil {
return nil, fmt.Errorf("failed to initialize secrets service: %w", err)
Expand All @@ -27,6 +28,8 @@ func initSecretsService(cfg *Config) (secrets.Service, error) {

// initDatabase initializes and migrates the database
func initDatabase(cfg *Config, secretsService secrets.Service) (db.Database, error) {
logging.Debug("initializing database", "path", cfg.DBPath)

database, err := db.Init(cfg.DBPath, secretsService)
if err != nil {
return nil, fmt.Errorf("failed to initialize database: %w", err)
Expand All @@ -41,57 +44,59 @@ func initDatabase(cfg *Config, secretsService secrets.Service) (db.Database, err

// initAuth initializes JWT and session services
func initAuth(cfg *Config, database db.Database) (auth.JWTManager, auth.SessionManager, auth.CookieManager, error) {
logging.Debug("initializing authentication services")

accessTokeExpiry := 15 * time.Minute
refreshTokenExpiry := 7 * 24 * time.Hour

// Get or generate JWT signing key
signingKey := cfg.JWTSigningKey
if signingKey == "" {
logging.Debug("no JWT signing key provided, generating new key")
var err error
signingKey, err = database.EnsureJWTSecret()
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to ensure JWT secret: %w", err)
}
}

// Initialize JWT service
jwtManager, err := auth.NewJWTService(auth.JWTConfig{
SigningKey: signingKey,
AccessTokenExpiry: 15 * time.Minute,
RefreshTokenExpiry: 7 * 24 * time.Hour,
AccessTokenExpiry: accessTokeExpiry,
RefreshTokenExpiry: refreshTokenExpiry,
})
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to initialize JWT service: %w", err)
}

// Initialize session service
sessionManager := auth.NewSessionService(database, jwtManager)

// Cookie service
cookieService := auth.NewCookieService(cfg.IsDevelopment, cfg.Domain)

return jwtManager, sessionManager, cookieService, nil
}

// setupAdminUser creates the admin user if it doesn't exist
func setupAdminUser(database db.Database, storageManager storage.Manager, cfg *Config) error {
adminEmail := cfg.AdminEmail
adminPassword := cfg.AdminPassword

// Check if admin user exists
adminUser, err := database.GetUserByEmail(adminEmail)
adminUser, err := database.GetUserByEmail(cfg.AdminEmail)
if err != nil && err != sql.ErrNoRows {
return fmt.Errorf("failed to check for existing admin user: %w", err)
}

if adminUser != nil {
return nil // Admin user already exists
} else if err != sql.ErrNoRows {
return err
logging.Debug("admin user already exists", "userId", adminUser.ID)
return nil
}

// Hash the password
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(adminPassword), bcrypt.DefaultCost)
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(cfg.AdminPassword), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("failed to hash password: %w", err)
return fmt.Errorf("failed to hash admin password: %w", err)
}

// Create admin user
adminUser = &models.User{
Email: adminEmail,
Email: cfg.AdminEmail,
DisplayName: "Admin",
PasswordHash: string(hashedPassword),
Role: models.RoleAdmin,
Expand All @@ -102,13 +107,14 @@ func setupAdminUser(database db.Database, storageManager storage.Manager, cfg *C
return fmt.Errorf("failed to create admin user: %w", err)
}

// Initialize workspace directory
err = storageManager.InitializeUserWorkspace(createdUser.ID, createdUser.LastWorkspaceID)
if err != nil {
return fmt.Errorf("failed to initialize admin workspace: %w", err)
}

log.Printf("Created admin user with ID: %d and default workspace with ID: %d", createdUser.ID, createdUser.LastWorkspaceID)
logging.Info("admin user setup completed",
"userId", createdUser.ID,
"workspaceId", createdUser.LastWorkspaceID)

return nil
}
4 changes: 4 additions & 0 deletions server/internal/app/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package app
import (
"novamd/internal/auth"
"novamd/internal/db"
"novamd/internal/logging"
"novamd/internal/storage"
)

Expand Down Expand Up @@ -33,6 +34,9 @@ func DefaultOptions(cfg *Config) (*Options, error) {
// Initialize storage
storageManager := storage.NewService(cfg.WorkDir)

// Initialize logger
logging.Setup(cfg.LogLevel)

// Initialize auth services
jwtManager, sessionService, cookieService, err := initAuth(cfg, database)
if err != nil {
Expand Down
2 changes: 2 additions & 0 deletions server/internal/app/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"novamd/internal/auth"
"novamd/internal/context"
"novamd/internal/handlers"
"novamd/internal/logging"
"time"

"github.com/go-chi/chi/v5"
Expand All @@ -19,6 +20,7 @@ import (

// setupRouter creates and configures the chi router with middleware and routes
func setupRouter(o Options) *chi.Mux {
logging.Debug("setting up router")
r := chi.NewRouter()

// Basic middleware
Expand Down
5 changes: 3 additions & 2 deletions server/internal/app/server.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package app

import (
"log"
"net/http"
"novamd/internal/logging"

"github.com/go-chi/chi/v5"
)
Expand All @@ -25,12 +25,13 @@ func NewServer(options *Options) *Server {
func (s *Server) Start() error {
// Start server
addr := ":" + s.options.Config.Port
log.Printf("Server starting on port %s", s.options.Config.Port)
logging.Info("starting server", "address", addr)
return http.ListenAndServe(addr, s.router)
}

// Close handles graceful shutdown of server dependencies
func (s *Server) Close() error {
logging.Info("shutting down server")
return s.options.Database.Close()
}

Expand Down
Loading
Loading