subscription.middleware.ts63 lines, 2.1 KB
| 1 | import { Request, Response, NextFunction } from "express"; |
| 2 | import { StatusCodes } from "http-status-codes"; |
| 3 | import { SubscriptionService } from "../services/subscription.service"; |
| 4 | import { errorResponse } from "../utils/response"; |
| 5 | |
| 6 | export const requiresSubscription = (tier: "basic" | "premium" | "pro") => { |
| 7 | return async (req: Request, res: Response, next: NextFunction) => { |
| 8 | try { |
| 9 | const userId = (req as any).user.id; |
| 10 | |
| 11 | // Get user's active subscription |
| 12 | const subscription = await SubscriptionService.getUserSubscription( |
| 13 | userId |
| 14 | ); |
| 15 | |
| 16 | // If no subscription and tier is required |
| 17 | if (!subscription) { |
| 18 | return res |
| 19 | .status(StatusCodes.PAYMENT_REQUIRED) |
| 20 | .json( |
| 21 | errorResponse( |
| 22 | `This feature requires a ${tier} subscription. Please upgrade to access it.` |
| 23 | ) |
| 24 | ); |
| 25 | } |
| 26 | |
| 27 | // Check subscription tier (you need to adapt this logic according to your plans structure) |
| 28 | const planName = subscription.plan.name.toLowerCase(); |
| 29 | |
| 30 | // Example tier hierarchy: free -> basic -> premium -> pro |
| 31 | if (tier === "basic" && !["basic", "premium", "pro"].includes(planName)) { |
| 32 | return res |
| 33 | .status(StatusCodes.PAYMENT_REQUIRED) |
| 34 | .json( |
| 35 | errorResponse( |
| 36 | `This feature requires at least a basic subscription. Please upgrade.` |
| 37 | ) |
| 38 | ); |
| 39 | } else if (tier === "premium" && !["premium", "pro"].includes(planName)) { |
| 40 | return res |
| 41 | .status(StatusCodes.PAYMENT_REQUIRED) |
| 42 | .json( |
| 43 | errorResponse( |
| 44 | `This feature requires at least a premium subscription. Please upgrade.` |
| 45 | ) |
| 46 | ); |
| 47 | } else if (tier === "pro" && planName !== "pro") { |
| 48 | return res |
| 49 | .status(StatusCodes.PAYMENT_REQUIRED) |
| 50 | .json( |
| 51 | errorResponse( |
| 52 | `This feature requires a pro subscription. Please upgrade.` |
| 53 | ) |
| 54 | ); |
| 55 | } |
| 56 | |
| 57 | // All checks passed, proceed to the route handler |
| 58 | next(); |
| 59 | } catch (error) { |
| 60 | next(error); |
| 61 | } |
| 62 | }; |
| 63 | }; |