Rework app setup

This commit is contained in:
2024-12-02 21:23:47 +01:00
parent 7d74821f29
commit 08e76671d0
11 changed files with 1226 additions and 362 deletions

View File

@@ -1,97 +0,0 @@
// Package api contains the API routes for the application. It sets up the routes for the public and protected endpoints, as well as the admin-only routes.
package api
import (
"novamd/internal/auth"
"novamd/internal/context"
"novamd/internal/db"
"novamd/internal/handlers"
"novamd/internal/storage"
"github.com/go-chi/chi/v5"
)
// SetupRoutes configures the API routes
func SetupRoutes(r chi.Router, db db.Database, s storage.Manager, authMiddleware *auth.Middleware, sessionService *auth.SessionService) {
handler := &handlers.Handler{
DB: db,
Storage: s,
}
// Public routes (no authentication required)
r.Group(func(r chi.Router) {
r.Post("/auth/login", handler.Login(sessionService))
r.Post("/auth/refresh", handler.RefreshToken(sessionService))
})
// Protected routes (authentication required)
r.Group(func(r chi.Router) {
// Apply authentication middleware to all routes in this group
r.Use(authMiddleware.Authenticate)
r.Use(context.WithUserContextMiddleware)
// Auth routes
r.Post("/auth/logout", handler.Logout(sessionService))
r.Get("/auth/me", handler.GetCurrentUser())
// User profile routes
r.Put("/profile", handler.UpdateProfile())
r.Delete("/profile", handler.DeleteAccount())
// Admin-only routes
r.Route("/admin", func(r chi.Router) {
r.Use(authMiddleware.RequireRole("admin"))
// User management
r.Route("/users", func(r chi.Router) {
r.Get("/", handler.AdminListUsers())
r.Post("/", handler.AdminCreateUser())
r.Get("/{userId}", handler.AdminGetUser())
r.Put("/{userId}", handler.AdminUpdateUser())
r.Delete("/{userId}", handler.AdminDeleteUser())
})
// Workspace management
r.Route("/workspaces", func(r chi.Router) {
r.Get("/", handler.AdminListWorkspaces())
})
// System stats
r.Get("/stats", handler.AdminGetSystemStats())
})
// Workspace routes
r.Route("/workspaces", func(r chi.Router) {
r.Get("/", handler.ListWorkspaces())
r.Post("/", handler.CreateWorkspace())
r.Get("/last", handler.GetLastWorkspaceName())
r.Put("/last", handler.UpdateLastWorkspaceName())
// Single workspace routes
r.Route("/{workspaceName}", func(r chi.Router) {
r.Use(context.WithWorkspaceContextMiddleware(db))
r.Use(authMiddleware.RequireWorkspaceAccess)
r.Get("/", handler.GetWorkspace())
r.Put("/", handler.UpdateWorkspace())
r.Delete("/", handler.DeleteWorkspace())
// File routes
r.Route("/files", func(r chi.Router) {
r.Get("/", handler.ListFiles())
r.Get("/last", handler.GetLastOpenedFile())
r.Put("/last", handler.UpdateLastOpenedFile())
r.Get("/lookup", handler.LookupFileByName())
r.Post("/*", handler.SaveFile())
r.Get("/*", handler.GetFileContent())
r.Delete("/*", handler.DeleteFile())
})
// Git routes
r.Route("/git", func(r chi.Router) {
r.Post("/commit", handler.StageCommitAndPush())
r.Post("/pull", handler.PullChanges())
})
})
})
})
}

View File

@@ -1,223 +0,0 @@
// Package app provides application-level functionality for initializing and running the server
package app
import (
"database/sql"
"fmt"
"log"
"net/http"
"time"
"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/unrolled/secure"
"golang.org/x/crypto/bcrypt"
"novamd/internal/api"
"novamd/internal/auth"
"novamd/internal/config"
"novamd/internal/db"
"novamd/internal/handlers"
"novamd/internal/models"
"novamd/internal/secrets"
"novamd/internal/storage"
)
// Server represents the HTTP server and its dependencies
type Server struct {
router *chi.Mux
config *config.Config
db db.Database
storage storage.Manager
}
// NewServer initializes a new server instance with all dependencies
func NewServer(cfg *config.Config) (*Server, error) {
// Initialize secrets service
secretsService, err := secrets.NewService(cfg.EncryptionKey)
if err != nil {
return nil, fmt.Errorf("failed to initialize secrets service: %w", err)
}
// Initialize database
database, err := initDatabase(cfg, secretsService)
if err != nil {
return nil, fmt.Errorf("failed to initialize database: %w", err)
}
// Initialize filesystem
storageManager := storage.NewService(cfg.WorkDir)
// Setup admin user
err = setupAdminUser(database, storageManager, cfg)
if err != nil {
return nil, fmt.Errorf("failed to setup admin user: %w", err)
}
// Initialize router
router := initRouter(cfg)
return &Server{
router: router,
config: cfg,
db: database,
storage: storageManager,
}, nil
}
// Start configures and starts the HTTP server
func (s *Server) Start() error {
// Set up authentication
jwtManager, sessionService, err := s.setupAuth()
if err != nil {
return fmt.Errorf("failed to setup authentication: %w", err)
}
// Set up routes
s.setupRoutes(jwtManager, sessionService)
// Start server
addr := ":" + s.config.Port
log.Printf("Server starting on port %s", s.config.Port)
return http.ListenAndServe(addr, s.router)
}
// Close handles graceful shutdown of server dependencies
func (s *Server) Close() error {
return s.db.Close()
}
// initDatabase initializes and migrates the database
func initDatabase(cfg *config.Config, secretsService secrets.Service) (db.Database, error) {
database, err := db.Init(cfg.DBPath, secretsService)
if err != nil {
return nil, fmt.Errorf("failed to initialize database: %w", err)
}
if err := database.Migrate(); err != nil {
return nil, fmt.Errorf("failed to apply database migrations: %w", err)
}
return database, nil
}
// initRouter creates and configures the chi router with middleware
func initRouter(cfg *config.Config) *chi.Mux {
r := chi.NewRouter()
// Basic middleware
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Timeout(30 * time.Second))
// Security headers
r.Use(secure.New(secure.Options{
SSLRedirect: false, // Let proxy handle HTTPS
SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
IsDevelopment: cfg.IsDevelopment,
}).Handler)
// CORS if origins are configured
if len(cfg.CORSOrigins) > 0 {
r.Use(cors.Handler(cors.Options{
AllowedOrigins: cfg.CORSOrigins,
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Requested-With"},
AllowCredentials: true,
MaxAge: 300,
}))
}
return r
}
// setupAuth initializes JWT and session services
func (s *Server) setupAuth() (auth.JWTManager, *auth.SessionService, error) {
// Get or generate JWT signing key
signingKey := s.config.JWTSigningKey
if signingKey == "" {
var err error
signingKey, err = s.db.EnsureJWTSecret()
if err != nil {
return 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,
})
if err != nil {
return nil, nil, fmt.Errorf("failed to initialize JWT service: %w", err)
}
// Initialize session service
sessionService := auth.NewSessionService(s.db, jwtManager)
return jwtManager, sessionService, nil
}
// setupRoutes configures all application routes
func (s *Server) setupRoutes(jwtManager auth.JWTManager, sessionService *auth.SessionService) {
// Initialize auth middleware
authMiddleware := auth.NewMiddleware(jwtManager)
// Set up API routes
s.router.Route("/api/v1", func(r chi.Router) {
r.Use(httprate.LimitByIP(s.config.RateLimitRequests, s.config.RateLimitWindow))
api.SetupRoutes(r, s.db, s.storage, authMiddleware, sessionService)
})
// Handle all other routes with static file server
s.router.Get("/*", handlers.NewStaticHandler(s.config.StaticPath).ServeHTTP)
}
func setupAdminUser(db db.Database, w storage.WorkspaceManager, cfg *config.Config) error {
adminEmail := cfg.AdminEmail
adminPassword := cfg.AdminPassword
// Check if admin user exists
adminUser, err := db.GetUserByEmail(adminEmail)
if adminUser != nil {
return nil // Admin user already exists
} else if err != sql.ErrNoRows {
return err
}
// Hash the password
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(adminPassword), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("failed to hash password: %w", err)
}
// Create admin user
adminUser = &models.User{
Email: adminEmail,
DisplayName: "Admin",
PasswordHash: string(hashedPassword),
Role: models.RoleAdmin,
}
createdUser, err := db.CreateUser(adminUser)
if err != nil {
return fmt.Errorf("failed to create admin user: %w", err)
}
// Initialize workspace directory
err = w.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)
return nil
}

View File

@@ -1,5 +1,4 @@
// Package config provides the configuration for the application
package config
package app
import (
"fmt"
@@ -40,8 +39,8 @@ func DefaultConfig() *Config {
}
}
// Validate checks if the configuration is valid
func (c *Config) Validate() error {
// validate checks if the configuration is valid
func (c *Config) validate() error {
if c.AdminEmail == "" || c.AdminPassword == "" {
return fmt.Errorf("NOVAMD_ADMIN_EMAIL and NOVAMD_ADMIN_PASSWORD must be set")
}
@@ -54,8 +53,8 @@ func (c *Config) Validate() error {
return nil
}
// Load creates a new Config instance with values from environment variables
func Load() (*Config, error) {
// LoadConfig creates a new Config instance with values from environment variables
func LoadConfig() (*Config, error) {
config := DefaultConfig()
if env := os.Getenv("NOVAMD_ENV"); env != "" {
@@ -105,7 +104,7 @@ func Load() (*Config, error) {
}
// Validate all settings
if err := config.Validate(); err != nil {
if err := config.validate(); err != nil {
return nil, err
}

View File

@@ -1,15 +1,14 @@
package config_test
package app_test
import (
"novamd/internal/app"
"os"
"testing"
"time"
"novamd/internal/config"
)
func TestDefaultConfig(t *testing.T) {
cfg := config.DefaultConfig()
cfg := app.DefaultConfig()
tests := []struct {
name string
@@ -75,7 +74,7 @@ func TestLoad(t *testing.T) {
setEnv(t, "NOVAMD_ADMIN_PASSWORD", "password123")
setEnv(t, "NOVAMD_ENCRYPTION_KEY", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoxMjM0NTY=") // 32 bytes base64 encoded
cfg, err := config.Load()
cfg, err := app.LoadConfig()
if err != nil {
t.Fatalf("Load() error = %v", err)
}
@@ -110,7 +109,7 @@ func TestLoad(t *testing.T) {
setEnv(t, k, v)
}
cfg, err := config.Load()
cfg, err := app.LoadConfig()
if err != nil {
t.Fatalf("Load() error = %v", err)
}
@@ -201,7 +200,7 @@ func TestLoad(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
tc.setupEnv(t)
_, err := config.Load()
_, err := app.LoadConfig()
if err == nil {
t.Error("expected error, got nil")
return

111
server/internal/app/init.go Normal file
View File

@@ -0,0 +1,111 @@
// Package app provides application-level functionality for initializing and running the server
package app
import (
"database/sql"
"fmt"
"log"
"time"
"golang.org/x/crypto/bcrypt"
"novamd/internal/auth"
"novamd/internal/db"
"novamd/internal/models"
"novamd/internal/secrets"
"novamd/internal/storage"
)
// initSecretsService initializes the secrets service
func initSecretsService(cfg *Config) (secrets.Service, error) {
secretsService, err := secrets.NewService(cfg.EncryptionKey)
if err != nil {
return nil, fmt.Errorf("failed to initialize secrets service: %w", err)
}
return secretsService, nil
}
// initDatabase initializes and migrates the database
func initDatabase(cfg *Config, secretsService secrets.Service) (db.Database, error) {
database, err := db.Init(cfg.DBPath, secretsService)
if err != nil {
return nil, fmt.Errorf("failed to initialize database: %w", err)
}
if err := database.Migrate(); err != nil {
return nil, fmt.Errorf("failed to apply database migrations: %w", err)
}
return database, nil
}
// initAuth initializes JWT and session services
func initAuth(cfg *Config, database db.Database) (auth.JWTManager, *auth.SessionService, error) {
// Get or generate JWT signing key
signingKey := cfg.JWTSigningKey
if signingKey == "" {
var err error
signingKey, err = database.EnsureJWTSecret()
if err != nil {
return 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,
})
if err != nil {
return nil, nil, fmt.Errorf("failed to initialize JWT service: %w", err)
}
// Initialize session service
sessionService := auth.NewSessionService(database, jwtManager)
return jwtManager, sessionService, 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)
if adminUser != nil {
return nil // Admin user already exists
} else if err != sql.ErrNoRows {
return err
}
// Hash the password
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(adminPassword), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("failed to hash password: %w", err)
}
// Create admin user
adminUser = &models.User{
Email: adminEmail,
DisplayName: "Admin",
PasswordHash: string(hashedPassword),
Role: models.RoleAdmin,
}
createdUser, err := database.CreateUser(adminUser)
if err != nil {
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)
return nil
}

View File

@@ -0,0 +1,53 @@
package app
import (
"novamd/internal/auth"
"novamd/internal/db"
"novamd/internal/storage"
)
// Options holds all dependencies and configuration for the server
type Options struct {
Config *Config
Database db.Database
Storage storage.Manager
JWTManager auth.JWTManager
SessionService *auth.SessionService
}
// DefaultOptions creates server options with default configuration
func DefaultOptions(cfg *Config) (*Options, error) {
// Initialize secrets service
secretsService, err := initSecretsService(cfg)
if err != nil {
return nil, err
}
// Initialize database
database, err := initDatabase(cfg, secretsService)
if err != nil {
return nil, err
}
// Initialize storage
storageManager := storage.NewService(cfg.WorkDir)
// Initialize auth services
jwtManager, sessionService, err := initAuth(cfg, database)
if err != nil {
return nil, err
}
// Setup admin user
if err := setupAdminUser(database, storageManager, cfg); err != nil {
return nil, err
}
return &Options{
Config: cfg,
Database: database,
Storage: storageManager,
JWTManager: jwtManager,
SessionService: sessionService,
}, nil
}

View File

@@ -0,0 +1,142 @@
package app
import (
"novamd/internal/auth"
"novamd/internal/context"
"novamd/internal/handlers"
"time"
"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/unrolled/secure"
)
// setupRouter creates and configures the chi router with middleware and routes
func setupRouter(o Options) *chi.Mux {
r := chi.NewRouter()
// Basic middleware
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Timeout(30 * time.Second))
// Security headers
r.Use(secure.New(secure.Options{
SSLRedirect: false,
SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
IsDevelopment: o.Config.IsDevelopment,
}).Handler)
// CORS if origins are configured
if len(o.Config.CORSOrigins) > 0 {
r.Use(cors.Handler(cors.Options{
AllowedOrigins: o.Config.CORSOrigins,
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Requested-With"},
AllowCredentials: true,
MaxAge: 300,
}))
}
// Initialize auth middleware and handler
authMiddleware := auth.NewMiddleware(o.JWTManager)
handler := &handlers.Handler{
DB: o.Database,
Storage: o.Storage,
}
// API routes
r.Route("/api/v1", func(r chi.Router) {
// Rate limiting for API routes
if o.Config.RateLimitRequests > 0 {
r.Use(httprate.LimitByIP(
o.Config.RateLimitRequests,
o.Config.RateLimitWindow,
))
}
// Public routes (no authentication required)
r.Group(func(r chi.Router) {
r.Post("/auth/login", handler.Login(o.SessionService))
r.Post("/auth/refresh", handler.RefreshToken(o.SessionService))
})
// Protected routes (authentication required)
r.Group(func(r chi.Router) {
r.Use(authMiddleware.Authenticate)
r.Use(context.WithUserContextMiddleware)
// Auth routes
r.Post("/auth/logout", handler.Logout(o.SessionService))
r.Get("/auth/me", handler.GetCurrentUser())
// User profile routes
r.Put("/profile", handler.UpdateProfile())
r.Delete("/profile", handler.DeleteAccount())
// Admin-only routes
r.Route("/admin", func(r chi.Router) {
r.Use(authMiddleware.RequireRole("admin"))
// User management
r.Route("/users", func(r chi.Router) {
r.Get("/", handler.AdminListUsers())
r.Post("/", handler.AdminCreateUser())
r.Get("/{userId}", handler.AdminGetUser())
r.Put("/{userId}", handler.AdminUpdateUser())
r.Delete("/{userId}", handler.AdminDeleteUser())
})
// Workspace management
r.Route("/workspaces", func(r chi.Router) {
r.Get("/", handler.AdminListWorkspaces())
})
// System stats
r.Get("/stats", handler.AdminGetSystemStats())
})
// Workspace routes
r.Route("/workspaces", func(r chi.Router) {
r.Get("/", handler.ListWorkspaces())
r.Post("/", handler.CreateWorkspace())
r.Get("/last", handler.GetLastWorkspaceName())
r.Put("/last", handler.UpdateLastWorkspaceName())
// Single workspace routes
r.Route("/{workspaceName}", func(r chi.Router) {
r.Use(context.WithWorkspaceContextMiddleware(o.Database))
r.Use(authMiddleware.RequireWorkspaceAccess)
r.Get("/", handler.GetWorkspace())
r.Put("/", handler.UpdateWorkspace())
r.Delete("/", handler.DeleteWorkspace())
// File routes
r.Route("/files", func(r chi.Router) {
r.Get("/", handler.ListFiles())
r.Get("/last", handler.GetLastOpenedFile())
r.Put("/last", handler.UpdateLastOpenedFile())
r.Get("/lookup", handler.LookupFileByName())
r.Post("/*", handler.SaveFile())
r.Get("/*", handler.GetFileContent())
r.Delete("/*", handler.DeleteFile())
})
// Git routes
r.Route("/git", func(r chi.Router) {
r.Post("/commit", handler.StageCommitAndPush())
r.Post("/pull", handler.PullChanges())
})
})
})
})
})
// Handle all other routes with static file server
r.Get("/*", handlers.NewStaticHandler(o.Config.StaticPath).ServeHTTP)
return r
}

View File

@@ -0,0 +1,40 @@
package app
import (
"log"
"net/http"
"github.com/go-chi/chi/v5"
)
// Server represents the HTTP server and its dependencies
type Server struct {
router *chi.Mux
options *Options
}
// NewServer creates a new server instance with the given options
func NewServer(options *Options) *Server {
return &Server{
router: setupRouter(*options),
options: options,
}
}
// Start configures and starts the HTTP server
func (s *Server) Start() error {
// Start server
addr := ":" + s.options.Config.Port
log.Printf("Server starting on port %s", s.options.Config.Port)
return http.ListenAndServe(addr, s.router)
}
// Close handles graceful shutdown of server dependencies
func (s *Server) Close() error {
return s.options.Database.Close()
}
// Router returns the chi router for testing
func (s *Server) Router() chi.Router {
return s.router
}

View File

@@ -11,14 +11,12 @@ import (
"testing"
"time"
"github.com/go-chi/chi/v5"
"golang.org/x/crypto/bcrypt"
"novamd/internal/api"
"novamd/internal/app"
"novamd/internal/auth"
"novamd/internal/db"
"novamd/internal/git"
"novamd/internal/handlers"
"novamd/internal/models"
"novamd/internal/secrets"
"novamd/internal/storage"
@@ -26,10 +24,9 @@ import (
// testHarness encapsulates all the dependencies needed for testing
type testHarness struct {
Server *app.Server
DB db.TestDatabase
Storage storage.Manager
Router *chi.Mux
Handler *handlers.Handler
JWTManager auth.JWTManager
SessionSvc *auth.SessionService
AdminUser *models.User
@@ -89,24 +86,34 @@ func setupTestHarness(t *testing.T) *testHarness {
// Initialize session service
sessionSvc := auth.NewSessionService(database, jwtSvc)
// Create handler
handler := &handlers.Handler{
DB: database,
Storage: storageSvc,
// Create test config
testConfig := &app.Config{
DBPath: ":memory:",
WorkDir: tempDir,
StaticPath: "../testdata",
Port: "8081",
AdminEmail: "admin@test.com",
AdminPassword: "admin123",
EncryptionKey: "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoxMjM0NTY=",
IsDevelopment: true,
}
// Set up router with middlewares
router := chi.NewRouter()
authMiddleware := auth.NewMiddleware(jwtSvc)
router.Route("/api/v1", func(r chi.Router) {
api.SetupRoutes(r, database, storageSvc, authMiddleware, sessionSvc)
})
// Create server options
serverOpts := &app.Options{
Config: testConfig,
Database: database,
Storage: storageSvc,
JWTManager: jwtSvc,
SessionService: sessionSvc,
}
// Create server
srv := app.NewServer(serverOpts)
h := &testHarness{
Server: srv,
DB: database,
Storage: storageSvc,
Router: router,
Handler: handler,
JWTManager: jwtSvc,
SessionSvc: sessionSvc,
TempDirectory: tempDir,
@@ -114,8 +121,8 @@ func setupTestHarness(t *testing.T) *testHarness {
}
// Create test users
adminUser, adminToken := h.createTestUser(t, database, sessionSvc, "admin@test.com", "admin123", models.RoleAdmin)
regularUser, regularToken := h.createTestUser(t, database, sessionSvc, "user@test.com", "user123", models.RoleEditor)
adminUser, adminToken := h.createTestUser(t, "admin@test.com", "admin123", models.RoleAdmin)
regularUser, regularToken := h.createTestUser(t, "user@test.com", "user123", models.RoleEditor)
h.AdminUser = adminUser
h.AdminToken = adminToken
@@ -139,7 +146,7 @@ func (h *testHarness) teardown(t *testing.T) {
}
// createTestUser creates a test user and returns the user and access token
func (h *testHarness) createTestUser(t *testing.T, db db.Database, sessionSvc *auth.SessionService, email, password string, role models.UserRole) (*models.User, string) {
func (h *testHarness) createTestUser(t *testing.T, email, password string, role models.UserRole) (*models.User, string) {
t.Helper()
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
@@ -154,7 +161,7 @@ func (h *testHarness) createTestUser(t *testing.T, db db.Database, sessionSvc *a
Role: role,
}
user, err = db.CreateUser(user)
user, err = h.DB.CreateUser(user)
if err != nil {
t.Fatalf("Failed to create user: %v", err)
}
@@ -165,7 +172,7 @@ func (h *testHarness) createTestUser(t *testing.T, db db.Database, sessionSvc *a
t.Fatalf("Failed to initialize user workspace: %v", err)
}
session, accessToken, err := sessionSvc.CreateSession(user.ID, string(user.Role))
session, accessToken, err := h.SessionSvc.CreateSession(user.ID, string(user.Role))
if err != nil {
t.Fatalf("Failed to create session: %v", err)
}
@@ -203,7 +210,7 @@ func (h *testHarness) makeRequest(t *testing.T, method, path string, body interf
}
rr := httptest.NewRecorder()
h.Router.ServeHTTP(rr, req)
h.Server.Router().ServeHTTP(rr, req)
return rr
}
@@ -223,7 +230,7 @@ func (h *testHarness) makeRequestRaw(t *testing.T, method, path string, body io.
}
rr := httptest.NewRecorder()
h.Router.ServeHTTP(rr, req)
h.Server.Router().ServeHTTP(rr, req)
return rr
}