Add JWT authentication
- Create register and login use cases - Implement JWT service for token generation and validation - Add authentication middleware to protect habit endpoints - Create auth HTTP handlers (register, login) - Update habit handlers to extract userID from JWT token - Register/login endpoints: POST /auth/register, POST /auth/login - Habit endpoints now require Bearer token in Authorization header - Tested: register -> create habit -> list habits works correctly
This commit is contained in:
+24
-1
@@ -4,9 +4,12 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"habit-tracker-api/internal/application/commands"
|
||||
"habit-tracker-api/internal/application/queries"
|
||||
"habit-tracker-api/internal/infrastructure/auth"
|
||||
"habit-tracker-api/internal/infrastructure/config"
|
||||
httpInfra "habit-tracker-api/internal/infrastructure/http"
|
||||
"habit-tracker-api/internal/infrastructure/persistence/sqlite"
|
||||
@@ -24,16 +27,27 @@ func main() {
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
jwtExpiryHours, err := parseJWTExpiry(cfg.JWTExpiry)
|
||||
if err != nil {
|
||||
log.Fatalf("Invalid JWT_EXPIRY: %v", err)
|
||||
}
|
||||
|
||||
jwtService := auth.NewJWTService(cfg.JWTSecret, jwtExpiryHours)
|
||||
|
||||
userRepo := sqlite.NewUserRepository(db.Conn())
|
||||
habitRepo := sqlite.NewHabitRepository(db.Conn())
|
||||
entryRepo := sqlite.NewHabitEntryRepository(db.Conn())
|
||||
|
||||
registerHandler := commands.NewRegisterUserHandler(userRepo)
|
||||
loginHandler := queries.NewLoginUserHandler(userRepo)
|
||||
createHandler := commands.NewCreateHabitHandler(habitRepo)
|
||||
getTodaysHandler := queries.NewGetTodaysHabitsHandler(habitRepo, entryRepo)
|
||||
markHandler := commands.NewMarkHabitHandler(entryRepo, habitRepo)
|
||||
|
||||
authHandlers := httpInfra.NewAuthHandlers(registerHandler, loginHandler, jwtService)
|
||||
habitHandlers := httpInfra.NewHabitHandlers(createHandler, getTodaysHandler, markHandler)
|
||||
|
||||
router := httpInfra.NewRouter(cfg.CORSOrigins, habitHandlers)
|
||||
router := httpInfra.NewRouter(cfg.CORSOrigins, habitHandlers, authHandlers, jwtService)
|
||||
|
||||
addr := fmt.Sprintf("%s:%s", cfg.Host, cfg.Port)
|
||||
log.Printf("Server starting on %s", addr)
|
||||
@@ -42,3 +56,12 @@ func main() {
|
||||
log.Fatalf("Server failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func parseJWTExpiry(expiry string) (int, error) {
|
||||
expiry = strings.TrimSpace(expiry)
|
||||
if strings.HasSuffix(expiry, "h") {
|
||||
hours := strings.TrimSuffix(expiry, "h")
|
||||
return strconv.Atoi(hours)
|
||||
}
|
||||
return 0, fmt.Errorf("invalid format, expected format like '24h'")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user