Skip to content

Commit

Permalink
fix(fa): Fixing error messages in financial-aid (#15589)
Browse files Browse the repository at this point in the history
* adding sortable feature

* Revert "adding sortable feature"

This reverts commit d9691c5.

* adding more detail for api

* removing white space break just adding html element to the db

* adding children to api

* checing if municpality code or api key are valid

* adding error message if header info is missing

* fixing error

* adding date check

* code rabbit fix

* moving logic to guard instead of controller

* chaning to string that allows two possibilities

* fixing linting
  • Loading branch information
MargretFinnboga authored Aug 7, 2024
1 parent 9020fbf commit 390aa85
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 8 deletions.
25 changes: 22 additions & 3 deletions apps/financial-aid/backend/src/app/guards/apiKey.guard.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,33 @@
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'
import {
Injectable,
CanActivate,
ExecutionContext,
BadRequestException,
} from '@nestjs/common'
import { ApiUserService } from '../modules/municipalityApiUsers/user.service'

@Injectable()
export class ApiKeyGuard implements CanActivate {
constructor(private userService: ApiUserService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest()

const apiKey = request.headers['api-key']
const municipalityCode = request.headers['municipality-code']

if (!apiKey && !municipalityCode) {
throw new BadRequestException('API-Key and Municipality-Code are missing')
}
if (!apiKey) {
throw new BadRequestException('API-Key is missing')
}
if (!municipalityCode) {
throw new BadRequestException('Municipality-Code is missing')
}

const user = await this.userService.findByMunicipalityCodeAndApiKey(
request.headers['api-key'],
request.headers['municipality-code'],
apiKey,
municipalityCode,
)

if (!user) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { Injectable, NotFoundException } from '@nestjs/common'
import {
BadRequestException,
Injectable,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common'
import { InjectModel } from '@nestjs/sequelize'
import CryptoJS from 'crypto-js'
import { ApiUserModel } from './models/user.model'
Expand All @@ -25,9 +30,18 @@ export class ApiUserService {
},
})

return keysWithMunicipalityCode.find(
if (keysWithMunicipalityCode.length === 0) {
throw new BadRequestException('Municipality-Code is invalid')
}

const findKeysWithMunicipalityCode = keysWithMunicipalityCode.find(
(m) => this.decryptApiKey(m).apiKey === apiKey,
)

if (!findKeysWithMunicipalityCode) {
throw new UnauthorizedException('API-Key is invalid')
}
return findKeysWithMunicipalityCode
}

async findByMunicipalityCode(
Expand Down
12 changes: 9 additions & 3 deletions apps/financial-aid/open-api/src/app/app.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,22 @@ import { ApplicationState } from '@island.is/financial-aid/shared/lib'
export class FilterApplicationsDto {
@IsNotEmpty()
@IsString()
@ApiProperty()
@ApiProperty({
description: 'Format: 2024-02-22 - year-month-date',
})
readonly startDate!: string

@IsOptional()
@IsString()
@ApiProperty()
@ApiProperty({
description: 'Format: 2024-02-22 - year-month-date',
})
readonly endDate?: string

@IsOptional()
@IsString()
@ApiProperty()
@ApiProperty({
description: 'States are: New, InProgress, DataNeeded, Rejected, Approved',
})
readonly state?: ApplicationState
}
6 changes: 6 additions & 0 deletions apps/financial-aid/open-api/src/app/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { LOGGER_PROVIDER } from '@island.is/logging'

import appModuleConfig from './app.config'
import { FilterApplicationsDto } from './app.dto'
import { isDateValid } from './helpers'
import { ApplicationModel } from './models'

@Injectable()
Expand All @@ -33,13 +34,18 @@ export class AppService {
`${this.config.backend.url}/api/financial-aid/open-api-applications/getAll`,
)
url.searchParams.append('startDate', filters.startDate)
isDateValid(filters.startDate, 'startDate')

url.searchParams.append(
'endDate',
filters.endDate ??
formatISO(new Date(), {
representation: 'date',
}),
)
if (filters.endDate) {
isDateValid(filters.endDate, 'endDate')
}
if (filters.state) {
url.searchParams.append('state', filters.state)
}
Expand Down
39 changes: 39 additions & 0 deletions apps/financial-aid/open-api/src/app/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { BadRequestException } from '@nestjs/common'

export const isDateValid = (
startDate: string,
dateType: 'endDate' | 'startDate',
): boolean => {
// Regular expression to match the YYYY-MM-DD format
const regex = /^\d{4}-\d{2}-\d{2}$/
if (!regex.test(startDate)) {
throw new BadRequestException(
`${dateType} is not formatted correctly, should be year-month-date e.g. 2024-02-22`,
)
}

// Parse the input string into a Date object
const date = new Date(startDate)
const isValidDate = date instanceof Date && !Number.isNaN(date.getTime())
const [year, month, day] = startDate.split('-').map(Number)
const isCorrectDate =
date.getFullYear() === year &&
date.getMonth() + 1 === month &&
date.getDate() === day

if (!isValidDate || !isCorrectDate) {
throw new BadRequestException(`${dateType} is not valid`)
}

// Get the current date without the time portion
const today = new Date()
today.setHours(0, 0, 0, 0)

// Check that the date is not in the future
const isNotInFuture = date <= today
if (!isNotInFuture) {
throw new BadRequestException(`${dateType} cannot be in the future`)
}

return true
}

0 comments on commit 390aa85

Please sign in to comment.