add auth module

This commit is contained in:
Egor Pozharov
2026-04-15 19:17:10 +06:00
parent e50f81f7f3
commit be0b13acbf
12 changed files with 410 additions and 8 deletions

View File

@@ -7,6 +7,7 @@ import (
"os"
"time"
"github.com/chedius/delivery-tracker/internal/auth"
db "github.com/chedius/delivery-tracker/internal/db/sqlc"
"github.com/chedius/delivery-tracker/internal/delivery"
"github.com/gin-contrib/cors"
@@ -15,6 +16,19 @@ import (
"github.com/joho/godotenv"
)
func initAuth(queries *db.Queries) (*auth.Service, *auth.Handler) {
secret := []byte(os.Getenv("JWT_SECRET"))
expiry := 24 * time.Minute
if len(secret) == 0 {
log.Fatal("JWT_SECRET not set")
}
service := auth.New(queries, secret, expiry)
handler := auth.NewHandler(service)
return service, handler
}
func main() {
ctx := context.Background()
godotenv.Load()
@@ -27,6 +41,7 @@ func main() {
defer pool.Close()
queries := db.New(pool)
_, authHandler := initAuth(queries)
h := delivery.NewHandler(queries)
r := gin.Default()
@@ -44,13 +59,20 @@ func main() {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
r.GET("/api/deliveries", h.GetDeliveries)
r.GET("/api/deliveries/:id", h.GetDeliveryByID)
r.GET("/api/deliveries/count", h.GetDeliveryCount)
r.POST("/api/deliveries", h.CreateDelivery)
r.PATCH("/api/deliveries/:id", h.UpdateDelivery)
r.PATCH("/api/deliveries/:id/status", h.UpdateDeliveryStatus)
r.DELETE("/api/deliveries/:id", h.DeleteDelivery)
r.POST("/api/auth/register", authHandler.Register)
r.POST("/api/auth/login", authHandler.Login)
authorized := r.Group("/api")
authorized.Use(auth.AuthMiddleware([]byte(os.Getenv("JWT_SECRET"))))
{
authorized.GET("/deliveries", h.GetDeliveries)
authorized.GET("/deliveries/:id", h.GetDeliveryByID)
authorized.GET("/deliveries/count", h.GetDeliveryCount)
authorized.POST("/deliveries", h.CreateDelivery)
authorized.PATCH("/deliveries/:id", h.UpdateDelivery)
authorized.PATCH("/deliveries/:id/status", h.UpdateDeliveryStatus)
authorized.DELETE("/deliveries/:id", h.DeleteDelivery)
}
r.Run(":8080")
}