Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { diMiddleware, useScopedContainer } from '@bonadocs/di';
import { rootLoggerMiddleware } from '@bonadocs/logger';

import {
AdminMiddleware,
AppErrorHandler,
AuthMiddleware,
healthcheckMiddleware,
Expand Down Expand Up @@ -100,7 +101,7 @@ useExpressServer(app, {
BillingController,
CouponController,
],
middlewares: [AppErrorHandler, AuthMiddleware],
middlewares: [AppErrorHandler, AuthMiddleware, AdminMiddleware],
});

// register cron jobs
Expand Down
38 changes: 38 additions & 0 deletions src/middleware/admin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Request, Response } from 'express';
import { ExpressMiddlewareInterface, Middleware } from 'routing-controllers';
import { Inject, Service } from 'typedi';

import { diConstants } from '@bonadocs/di';
import { BonadocsLogger } from '@bonadocs/logger';

@Service()
@Middleware({ type: 'before' })
export class AdminMiddleware implements ExpressMiddlewareInterface {
constructor(@Inject(diConstants.logger) private readonly logger: BonadocsLogger) {}

async use(request: Request, response: Response, next: (err?: any) => any): Promise<any> {
// todo : find a better fix for this
const adminPaths = ['/coupons'];
const isAdminPath = adminPaths.some((path) => request.path.startsWith(path));
if (!isAdminPath) {
return next();
}
const token = request.headers.authorization?.split(' ')[1];
if (!token) {
this.logger.error('Admin token is missing');
return response.status(401).json({
message: 'Admin token is missing',
status: 'error',
});
}
if (token !== process.env.ADMIN_TOKEN) {
this.logger.error('Invalid admin token');
return response.status(403).json({
message: 'Invalid admin token',
status: 'error',
});
}
return next();
}
}
8 changes: 7 additions & 1 deletion src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@ export class AuthMiddleware implements ExpressMiddlewareInterface {

async use(request: Request, response: Response, next: (err?: any) => any): Promise<any> {
// todo : find a better fix for this
const exemptPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/billing/webhook'];
const exemptPaths = [
'/auth/login',
'/auth/register',
'/auth/refresh',
'/billing/webhook',
'/coupons',
];
const isExemptPath = exemptPaths.some((path) => request.path.startsWith(path));
if (isExemptPath) {
return next();
Expand Down
1 change: 1 addition & 0 deletions src/middleware/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export { default as AppErrorHandler } from './errors';
export { default as healthcheckMiddleware } from './healthcheck';
export { useCors } from './cors';
export { AuthMiddleware } from './auth';
export { AdminMiddleware } from './admin';
export { default as webhookMiddleware } from './webhook';
11 changes: 3 additions & 8 deletions src/modules/coupon/coupon.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Request } from 'express';
import { Body, Get, JsonController, Param, Patch, Post, Req } from 'routing-controllers';
import { Body, Get, JsonController, Param, Patch, Post } from 'routing-controllers';
import { Inject, Service } from 'typedi';

import { JsonResponse } from '../shared';
Expand All @@ -14,12 +13,8 @@ export class CouponController {
constructor(@Inject() private readonly couponService: CouponService) {}

@Post('/')
async create(
@Body({ validate: true }) payload: CreateCouponDto,
@Req() request: Request,
): Promise<JsonResponse<string>> {
const authData = request.auth;
const response = await this.couponService.create(payload, authData);
async create(@Body({ validate: true }) payload: CreateCouponDto): Promise<JsonResponse<string>> {
const response = await this.couponService.create(payload);
return {
data: response,
status: 'successful',
Expand Down
3 changes: 1 addition & 2 deletions src/modules/coupon/coupon.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,13 @@ export class CouponService {
@Inject() private readonly couponRepository: CouponRepository,
) {}

async create(request: CreateCouponRequest, authData: AuthData): Promise<string> {
async create(request: CreateCouponRequest): Promise<string> {
const coupon: CreateCouponDto = {
code: this.generateUUIDCouponCode('bonadocs'),
date_expire: request.date_expire,
plan_id: request.plan_id,
project_id: request.project_id,
status: SubscriptionStatus.Active,
creator_id: authData.userId!,
};
// validate if any active coupon exists for the project on the selected plan
const existingCoupons = await this.couponRepository.getCouponsByProjectIdAndPlanId(
Expand Down
11 changes: 1 addition & 10 deletions src/modules/repositories/coupon/coupon.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import { BonadocsLogger } from '@bonadocs/logger';

import { DbContext, withDbContext } from '../../connection/dbcontext';
import { SubscriptionStatus } from '../../shared/types/subscriptions';
import { ProjectPermissions, ProjectRepository } from '../projects';
import { queries as projectQueries } from '../projects/queries';
import { ProjectRepository } from '../projects';

import { queries } from './queries';
import { CouponDto, CreateCouponDto } from './types';
Expand Down Expand Up @@ -46,14 +45,6 @@ export class CouponRepository {
couponDto.date_expire,
);

// add admin user
await context!.query({
text: projectQueries.addUserToProject,
values: [couponDto.project_id, couponDto.creator_id, ProjectPermissions.admin],
validateResult: (result) => !!result.rowCount,
validationErrorMessage: 'Failed to add user to project',
});

// add subscription id to coupon
await context?.query({
text: queries.updateCouponSubscriptionId,
Expand Down
1 change: 0 additions & 1 deletion src/modules/repositories/coupon/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ export interface CreateCouponDto {
date_expire: Date;
plan_id: number;
status: SubscriptionStatus;
creator_id: number;
}

export interface UpdateCouponDto {
Expand Down
Loading