Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge Develop onto Main #470

Merged
merged 5 commits into from
Jun 13, 2024
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
25 changes: 23 additions & 2 deletions .github/workflows/community-issue-comment.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# This workflow handles issue comments.
# See for more info: https://github.com/actions/github-script

name: Issue Assignee Comment
name: Issue Comments

on:
issues:
Expand All @@ -11,8 +12,8 @@ on:
jobs:
# When issues are assigned, a comment is posted
# Tags the assignee with links to helpful resources
# See for more info: https://github.com/actions/github-script
assigned-comment:
if: github.event.action == 'assigned'
runs-on: ubuntu-latest
steps:
- name: Post assignee issue comment
Expand All @@ -33,3 +34,23 @@ jobs:
Support Chayn's mission? ⭐ Please star this repo to help us find more contributors like you!
Learn more about Chayn [here](https://linktr.ee/chayn) and [explore our projects](https://org.chayn.co/projects). 🌸`
})

# When issues are labeled as stale, a comment is posted.
# Tags the assignee with warning.
# Enables manual issue management in addition to community-stale-management.yml
stale-label-comment:
if: github.event.action == 'labeled' && github.event.label.name == 'stale'
runs-on: ubuntu-latest
steps:
- name: Post stale issue comment
id: stale-label-comment
uses: actions/github-script@v7
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.issue.number,
body: `@${context.payload.issue.assignee.login} As per Chayn policy, after 30 days of inactivity, we will be unassigning this issue. Please comment to stay assigned.`
})
1 change: 0 additions & 1 deletion .github/workflows/community-stale-management.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,3 @@ jobs:
ignore-pr-updates: true
stale-pr-message: "As per Chayn policy, after 30 days of inactivity, we will close this PR."
close-pr-message: "This PR has been closed due to inactivity."
stale-issue-message: "As per Chayn policy, after 30 days of inactivity, we will be unassigning this issue. Please comment to stay assigned."
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { AuthModule } from './auth/auth.module';
import { CoursePartnerModule } from './course-partner/course-partner.module';
import { CourseUserModule } from './course-user/course-user.module';
import { CourseModule } from './course/course.module';
import { EventLoggerModule } from './event-logger/event-logger.module';
import { FeatureModule } from './feature/feature.module';
import { LoggerModule } from './logger/logger.module';
import { PartnerAccessModule } from './partner-access/partner-access.module';
Expand Down Expand Up @@ -37,6 +38,7 @@ import { WebhooksModule } from './webhooks/webhooks.module';
SubscriptionUserModule,
FeatureModule,
PartnerFeatureModule,
EventLoggerModule,
],
})
export class AppModule {}
20 changes: 9 additions & 11 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
import { DecodedIdToken } from 'firebase-admin/lib/auth/token-verifier';
import { Logger } from 'src/logger/logger';
import {
CREATE_USER_ALREADY_EXISTS,
CREATE_USER_FIREBASE_ERROR,
CREATE_USER_INVALID_EMAIL,
CREATE_USER_WEAK_PASSWORD,
Expand Down Expand Up @@ -55,24 +56,21 @@ export class AuthService {
return firebaseUser;
} catch (err) {
const errorCode = err.code;

if (errorCode === 'auth/invalid-email') {
this.logger.warn(
`Create user: user tried to create email with invalid email: ${email} - ${err}`,
);
throw new HttpException(CREATE_USER_INVALID_EMAIL, HttpStatus.BAD_REQUEST);
}
if (
errorCode === 'auth/weak-password' ||
err.message.includes('The password must be a string with at least 6 characters')
) {
} else if (errorCode === 'auth/weak-password' || errorCode === 'auth/invalid-password') {
this.logger.warn(`Create user: user tried to create email with weak password - ${err}`);
throw new HttpException(CREATE_USER_WEAK_PASSWORD, HttpStatus.BAD_REQUEST);
}
if (errorCode === 'auth/email-already-in-use' && errorCode === 'auth/email-already-exists') {
this.logger.log(
`Create user: Firebase user already exists so fetching firebase user: ${email}`,
);
return await this.getFirebaseUser(email);
} else if (
errorCode === 'auth/email-already-in-use' ||
errorCode === 'auth/email-already-exists'
) {
this.logger.warn(`Create user: Firebase user already exists: ${email}`);
throw new HttpException(CREATE_USER_ALREADY_EXISTS, HttpStatus.BAD_REQUEST);
} else {
this.logger.error(`Create user: Error creating firebase user - ${email}: ${err}`);
throw new HttpException(CREATE_USER_FIREBASE_ERROR, HttpStatus.BAD_REQUEST);
Expand Down
28 changes: 28 additions & 0 deletions src/event-logger/event-logger.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Body, Controller, Post, Req, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { FirebaseAuthGuard } from 'src/firebase/firebase-auth.guard';
import { ControllerDecorator } from 'src/utils/controller.decorator';
import { EVENT_NAME } from './event-logger.interface';
import { EventLoggerService } from './event-logger.service';

@ApiTags('Event Logger')
@ControllerDecorator()
@Controller('/v1/event-logger')
export class EventLoggerController {
constructor(private readonly eventLoggerService: EventLoggerService) {}

@Post()
@ApiOperation({
description: 'Creates an event log',
})
@ApiBearerAuth('access-token')
@UseGuards(FirebaseAuthGuard)
async createEventLog(@Req() req: Request, @Body() { event }: { event: EVENT_NAME }) {
const now = new Date();
return await this.eventLoggerService.createEventLog({
userId: req['userEntity'].id,
event,
date: now,
});
}
}
2 changes: 2 additions & 0 deletions src/event-logger/event-logger.interface.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
export enum EVENT_NAME {
CHAT_MESSAGE_SENT = 'CHAT_MESSAGE_SENT',
LOGGED_IN = 'LOGGED_IN',
LOGGED_OUT = 'LOGGED_OUT',
}

export interface ICreateEventLog {
Expand Down
40 changes: 37 additions & 3 deletions src/event-logger/event-logger.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,44 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { SlackMessageClient } from 'src/api/slack/slack-api';
import { ZapierWebhookClient } from 'src/api/zapier/zapier-webhook-client';
import { EventLogEntity } from 'src/entities/event-log.entity';
import { PartnerAccessEntity } from 'src/entities/partner-access.entity';
import { PartnerEntity } from 'src/entities/partner.entity';
import { SubscriptionUserEntity } from 'src/entities/subscription-user.entity';
import { SubscriptionEntity } from 'src/entities/subscription.entity';
import { TherapySessionEntity } from 'src/entities/therapy-session.entity';
import { UserEntity } from 'src/entities/user.entity';
import { PartnerAccessService } from 'src/partner-access/partner-access.service';
import { SubscriptionUserService } from 'src/subscription-user/subscription-user.service';
import { SubscriptionService } from 'src/subscription/subscription.service';
import { TherapySessionService } from 'src/therapy-session/therapy-session.service';
import { UserService } from 'src/user/user.service';
import { EventLoggerController } from './event-logger.controller';
import { EventLoggerService } from './event-logger.service';

@Module({
imports: [TypeOrmModule.forFeature([EventLogEntity])],
providers: [EventLoggerService],
imports: [
TypeOrmModule.forFeature([
EventLogEntity,
UserEntity,
PartnerAccessEntity,
PartnerEntity,
SubscriptionUserEntity,
TherapySessionEntity,
SubscriptionEntity,
]),
],
controllers: [EventLoggerController],
providers: [
EventLoggerService,
UserService,
SubscriptionUserService,
TherapySessionService,
PartnerAccessService,
SubscriptionService,
ZapierWebhookClient,
SlackMessageClient,
],
})
export class SessionModule {}
export class EventLoggerModule {}
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { ExceptionsFilter } from './utils/exceptions.filter';

async function bootstrap() {
const PORT = process.env.PORT || 35001;
const app = await NestFactory.create(AppModule, { cors: true });
const app = await NestFactory.create(AppModule, { cors: true, rawBody: true });

app.setGlobalPrefix('api');

Expand Down
9 changes: 7 additions & 2 deletions src/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
createServiceUserProfiles,
updateServiceUserProfilesUser,
} from 'src/utils/serviceUserProfiles';
import { And, ILike, Raw, Repository } from 'typeorm';
import { And, ILike, Raw, Repository, IsNull, Not } from 'typeorm';
import { deleteCypressCrispProfiles } from '../api/crisp/crisp-api';
import { AuthService } from '../auth/auth.service';
import { PartnerAccessService, basePartnerAccess } from '../partner-access/partner-access.service';
Expand Down Expand Up @@ -63,6 +63,7 @@ export class UserService {
}

const firebaseUser = await this.authService.createFirebaseUser(email, password);

const user = await this.userRepository.save({
...createUserDto,
firebaseUid: firebaseUser.uid,
Expand Down Expand Up @@ -289,7 +290,11 @@ export class UserService {
}),
...(filters.partnerAdmin && {
partnerAdmin: {
...(filters.partnerAdmin && { id: filters.partnerAdmin.partnerAdminId }),
...(filters.partnerAdmin && {
id: filters.partnerAdmin.partnerAdminId === 'IS NOT NULL'
? Not(IsNull())
: filters.partnerAdmin.partnerAdminId
}),
},
}),
},
Expand Down
5 changes: 5 additions & 0 deletions src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ export const slackWebhookUrl = getEnv(process.env.SLACK_WEBHOOK_URL, 'SLACK_WEBH

export const storyblokToken = getEnv(process.env.STORYBLOK_PUBLIC_TOKEN, 'STORYBLOK_PUBLIC_TOKEN');

export const storyblokWebhookSecret = getEnv(
process.env.STORYBLOK_WEBHOOK_SECRET,
'STORYBLOK_WEBHOOK_SECRET',
);

export const simplybookCredentials = getEnv(
process.env.SIMPLYBOOK_CREDENTIALS,
'SIMPLYBOOK_CREDENTIALS',
Expand Down
1 change: 1 addition & 0 deletions src/utils/errors.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export const CREATE_USER_FIREBASE_ERROR = 'CREATE_USER_FIREBASE_ERROR';
export const CREATE_USER_INVALID_EMAIL = 'CREATE_USER_INVALID_EMAIL';
export const CREATE_USER_WEAK_PASSWORD = 'CREATE_USER_WEAK_PASSWORD';
export const CREATE_USER_ALREADY_EXISTS = 'CREATE_USER_ALREADY_EXISTS';
43 changes: 42 additions & 1 deletion src/webhooks/webhooks.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
import { createMock } from '@golevelup/ts-jest';
import { HttpException, HttpStatus } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { mockSimplybookBodyBase, mockTherapySessionEntity } from 'test/utils/mockData';
import { createHmac } from 'crypto';
import { storyblokWebhookSecret } from 'src/utils/constants';
import {
mockSessionEntity,
mockSimplybookBodyBase,
mockStoryDto,
mockTherapySessionEntity,
} from 'test/utils/mockData';
import { mockWebhooksServiceMethods } from 'test/utils/mockedServices';
import { WebhooksController } from './webhooks.controller';
import { WebhooksService } from './webhooks.service';

const getWebhookSignature = (body) => {
return createHmac('sha1', storyblokWebhookSecret)
.update('' + body)
.digest('hex');
};

const generateMockHeaders = (body) => {
return {
'webhook-signature': getWebhookSignature(body),
};
};

const createRequestObject = (body) => {
return {
rawBody: JSON.stringify(body),
setEncoding: () => {},
encoding: 'utf8',
};
};

describe('AppController', () => {
let webhooksController: WebhooksController;
const mockWebhooksService = createMock<WebhooksService>(mockWebhooksServiceMethods);
Expand Down Expand Up @@ -35,5 +62,19 @@ describe('AppController', () => {
webhooksController.updatePartnerAccessTherapy(mockSimplybookBodyBase),
).rejects.toThrow('Therapy session not found');
});
describe('updateStory', () => {
it('updateStory should pass if service returns true', async () => {
jest.spyOn(mockWebhooksService, 'updateStory').mockImplementationOnce(async () => {
return mockSessionEntity;
});
await expect(
webhooksController.updateStory(
createRequestObject(mockStoryDto),
mockStoryDto,
generateMockHeaders(mockStoryDto),
),
).resolves.toBe(mockSessionEntity);
});
});
});
});
32 changes: 30 additions & 2 deletions src/webhooks/webhooks.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
import { Body, Controller, Headers, Logger, Post, Request, UseGuards } from '@nestjs/common';
import {
Body,
Controller,
Headers,
HttpException,
HttpStatus,
Logger,
Post,
Request,
UseGuards,
} from '@nestjs/common';
import { ApiBody, ApiTags } from '@nestjs/swagger';
import { createHmac } from 'crypto';
import { EventLogEntity } from 'src/entities/event-log.entity';
import { TherapySessionEntity } from 'src/entities/therapy-session.entity';
import { storyblokWebhookSecret } from 'src/utils/constants';
import { ControllerDecorator } from 'src/utils/controller.decorator';
import { WebhookCreateEventLogDto } from 'src/webhooks/dto/webhook-create-event-log.dto';
import { ZapierSimplybookBodyDto } from '../partner-access/dtos/zapier-body.dto';
Expand Down Expand Up @@ -36,6 +48,22 @@ export class WebhooksController {
@ApiBody({ type: StoryDto })
async updateStory(@Request() req, @Body() data: StoryDto, @Headers() headers) {
const signature: string | undefined = headers['webhook-signature'];
return this.webhooksService.updateStory(req, data, signature);
// Verify storyblok signature uses storyblok webhook secret - see https://www.storyblok.com/docs/guide/in-depth/webhooks#securing-a-webhook
if (!signature) {
const error = `Storyblok webhook error - no signature provided`;
this.logger.error(error);
throw new HttpException(error, HttpStatus.UNAUTHORIZED);
}

req.rawBody = '' + data;
req.setEncoding('utf8');

const bodyHmac = createHmac('sha1', storyblokWebhookSecret).update(req.rawBody).digest('hex');
if (bodyHmac !== signature) {
const error = `Storyblok webhook error - signature mismatch`;
this.logger.error(error);
throw new HttpException(error, HttpStatus.UNAUTHORIZED);
}
return this.webhooksService.updateStory(data);
}
}
Loading
Loading