72 lines
2.0 KiB
Go
72 lines
2.0 KiB
Go
package httpserver
|
|
|
|
import (
|
|
"Rezina-Backend/internal/domain"
|
|
"errors"
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/jackc/pgx/v5"
|
|
"strings"
|
|
)
|
|
|
|
// RequireCoursePurchase protects consumption. Collection metadata is redacted by handlers.
|
|
func (a *App) RequireCoursePurchase() fiber.Handler {
|
|
return func(c *fiber.Ctx) error {
|
|
role, userID, err := subscriptionScopedUser(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if bypassSubscriptionForRole(role) {
|
|
return c.Next()
|
|
}
|
|
kind := ""
|
|
id := int64(0)
|
|
path := c.Route().Path
|
|
if strings.Contains(path, "/videos/engagement/heartbeat") {
|
|
var req domain.VideoEngagementHeartbeatInput
|
|
if err := c.BodyParser(&req); err != nil || req.ContentID <= 0 {
|
|
return fiber.NewError(400, "Invalid video heartbeat")
|
|
}
|
|
kind = "lesson"
|
|
id = req.ContentID
|
|
} else if strings.Contains(path, "/lessons/:id") {
|
|
kind = "lesson"
|
|
id, _, err = parseRouteInt64(c, "id")
|
|
} else if strings.Contains(path, "/quizzes/") || strings.Contains(path, "/practices/") {
|
|
for _, param := range []string{"practiceId", "id"} {
|
|
if c.Params(param) != "" {
|
|
kind = "practice"
|
|
id, _, err = parseRouteInt64(c, param)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if kind == "" {
|
|
return c.Next()
|
|
}
|
|
access, err := a.examPrepSvc.CourseContentAccess(c.Context(), kind, id)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return fiber.NewError(404, "Content not found")
|
|
}
|
|
if err != nil {
|
|
return fiber.NewError(500, "Failed to verify course access")
|
|
}
|
|
if !access.Published {
|
|
return fiber.NewError(404, "Content not found")
|
|
}
|
|
if access.Tier == domain.ContentAccessFree {
|
|
return c.Next()
|
|
}
|
|
owned, err := a.examPrepSvc.HasCoursePurchase(c.Context(), userID, access.CourseID)
|
|
if err != nil {
|
|
return fiber.NewError(500, "Failed to verify course purchase")
|
|
}
|
|
if !owned {
|
|
return c.Status(403).JSON(fiber.Map{"message": "Purchase this course to access premium content", "course_id": access.CourseID, "code": "COURSE_PURCHASE_REQUIRED"})
|
|
}
|
|
return c.Next()
|
|
}
|
|
}
|