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

feat(validation): Adds response and service-code validation. #59

Merged
merged 2 commits into from
May 23, 2023
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
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ DATABASE_URL=
DEFAULT_VOUCHER_ADDRESS=
DEFAULT_VOUCHER_SYMBOL=
DISABLE_REQUEST_LOGGING=
KE_SERVICE_CODES=
KE_SUPPORT_PHONE=
LOG_LEVEL=
LOG_NAME=
Expand Down
8 changes: 5 additions & 3 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as process from 'process';

function stringToList (value: string | undefined): string[] | void {
if (value === undefined) {
throw new Error('Value is undefined')
console.error('Error parsing string to list.')
} else {
return value.split(',')
}
Expand All @@ -17,8 +17,7 @@ export const config = {
USERNAME: process.env.AT_USERNAME ?? 'x',
USSD_ENDPOINT_SECRET: process.env.AT_USSD_ENDPOINT_SECRET ?? 'xE',
VALID_IPS: stringToList(process.env.AT_VALID_IPS) ?? [
'0.0.0.0',
'127.0.0.1'
'0.0.0.0', '127.0.0.1'
]
},
CIC: {
Expand All @@ -37,6 +36,9 @@ export const config = {
DEV: process.env.NODE_ENV !== 'production',
KE: {
SUPPORT_PHONE: process.env.SUPPORT_PHONE ?? '0757628885',
SERVICE_CODES: stringToList(process.env.KE_SERVICE_CODES) ?? [
'*384*96#', '*483*061#', '*483*46#'
],
},
LOG: {
LEVEL: process.env.LOG_LEVEL ?? 'info',
Expand Down
5 changes: 5 additions & 0 deletions src/services/africasTalking.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { SystemError } from '@lib/errors';
import { SessionRequest } from '@services/session';
import { getCountryCode } from '@lib/ussd';
import { config } from '@/config';

export const ATRequestBody = {
type: 'object',
Expand Down Expand Up @@ -33,6 +34,10 @@ export async function ATPreHandlerHook(request: SessionRequest) {
throw new SystemError(`Could not determine country code from phone number: ${phoneNumber}`);
}

if(!config.KE.SERVICE_CODES.includes(serviceCode)) {
throw new SystemError(`Invalid service code: ${serviceCode}`);
}

request.uContext.ussd = {
countryCode,
input: text.split('*').pop() || '',
Expand Down
28 changes: 24 additions & 4 deletions src/services/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { Connections } from '@machines/utils';
import { UserService } from '@services/user';
import { buildResponse, MachineContext } from '@services/machine';
import { fallbackLanguage, tHelpers } from '@i18n/translators';
import { logger } from '@/app';
import { Locales } from '@i18n/i18n-types';

declare module 'fastify' {
interface FastifyRequest {
Expand Down Expand Up @@ -78,7 +80,7 @@ async function buildContext(request: SessionRequest): Promise<MachineContext> {
return {...context, user}
}

export async function sessionHandler(request: SessionRequest, reply: FastifyReply){
export async function sessionHandler(request: SessionRequest, reply: FastifyReply) {
try {
const context = await buildContext(request)
const sessionService = new SessionService(context.connections.db, context.ussd.requestId, context.connections.redis.ephemeral)
Expand All @@ -97,13 +99,31 @@ export async function sessionHandler(request: SessionRequest, reply: FastifyRepl
context.data = session.data
}
const response = await buildResponse(context, session)
reply.send(response)
let language = fallbackLanguage();
if ('user' in context && context.user) {
language = context.user.account.language
}
await handleResponse(language, reply, response)
} catch (error: any){
const response = tHelpers("systemError", fallbackLanguage())
reply.send(response)
logger.error(`Error handling session: ${error.message}`)
await handleError(reply)
}
}

async function handleResponse(language: Locales, reply: FastifyReply, response: string) {
if (!response || !response.startsWith("CON") && !response.startsWith("END")) {
logger.error(`Error building response. Invalid response: ${response}`)
await handleError(reply, language)
return
}
reply.send(response)
}

async function handleError(reply: FastifyReply, language = fallbackLanguage()) {
reply.send(tHelpers("systemError", language))
}


export class SessionService {

private cache: CacheService<SessionInterface>
Expand Down