Skip to content

Commit 911c423

Browse files
committed
riskiapi: skip normal auth + tests
1 parent 30715a4 commit 911c423

File tree

5 files changed

+179
-20
lines changed

5 files changed

+179
-20
lines changed

config/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ export const HDR_API_TOKEN = process.env.HDR_API_TOKEN ?? ''
2121
export const HDR_YEAR = process.env.HDR_YEAR ?? '2023'
2222
export const ORGANISATION_ID = process.env.ORGANISATION_ID ?? ''
2323

24-
export const HY_API_TOKEN = process.env.HY_API_TOKEN ?? ''
24+
export const HY_API_TOKEN = process.env.HY_API_TOKEN ?? 'default'
2525

2626
//Hy related
2727
export const JAMI_URL = inProduction

src/server/middleware/apiKey.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import type { Request, Response, NextFunction } from 'express'
2+
import { HY_API_TOKEN } from '@userconfig'
3+
4+
export const validateApiKey = (req: Request, res: Response, next: NextFunction) => {
5+
const apiKey = req.get('api-key')
6+
if (!apiKey || !HY_API_TOKEN || apiKey !== HY_API_TOKEN) {
7+
return res.status(401).json({ error: 'unauthorised' })
8+
}
9+
next()
10+
}

src/server/routes/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,13 @@ router.use('/results', resultRouter)
6767
router.use('/countries', countryRouter)
6868
router.use('/warnings', warningsRouter)
6969
router.use('/users', userRouter)
70+
router.use('/riskiapi', myResearchApiRouter)
7071

7172
router.use(userAccessMiddleware)
7273

7374
router.use('/entries', entryRouter)
7475
router.use('/organizations', organizationRouter)
7576
router.use('/tuhatprojects', tuhatProjectsRouter)
76-
router.use('/riskiapi', myResearchApiRouter)
7777

7878
router.get('/explode', () => {
7979
throw new Error('Bad thing happened!')

src/server/routes/myResearchApi.ts

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,29 @@ import express from 'express'
22

33
import { getRisksWithTuhatProject, getRiskWithTuhatProjectId } from '../services/myResearchApi'
44
import { MyResearchData, Error } from '@server/types'
5-
import { HY_API_TOKEN } from '@userconfig'
5+
import { validateApiKey } from '../middleware/apiKey'
66

77
const myResearchApiRouter = express.Router()
88

9-
myResearchApiRouter.get<never, MyResearchData[] | Error, never, never>('/projects', async (req, res) => {
10-
const apiKey = req.get('api-key')
11-
if (!apiKey || !HY_API_TOKEN || apiKey !== HY_API_TOKEN) {
12-
return res.status(401).json({ error: 'unauthorised' })
13-
}
9+
myResearchApiRouter.get<never, MyResearchData[] | Error, never, never>(
10+
'/projects',
11+
validateApiKey,
12+
async (req, res) => {
13+
const tuhatProjects = await getRisksWithTuhatProject()
1414

15-
const tuhatProjects = await getRisksWithTuhatProject()
15+
return res.send(tuhatProjects)
16+
}
17+
)
1618

17-
return res.send(tuhatProjects)
18-
})
19+
myResearchApiRouter.get<never, MyResearchData | Error, never, never>(
20+
'/projects/:projectUuid',
21+
validateApiKey,
22+
async (req, res) => {
23+
const { projectUuid } = req.params
24+
const tuhatProjects = await getRiskWithTuhatProjectId(projectUuid)
1925

20-
myResearchApiRouter.get<never, MyResearchData | Error, never, never>('/projects/:projectUuid', async (req, res) => {
21-
const apiKey = req.get('api-key')
22-
if (!apiKey || !HY_API_TOKEN || apiKey !== HY_API_TOKEN) {
23-
return res.status(401).json({ error: 'unauthorised' })
26+
return res.send(tuhatProjects)
2427
}
25-
const { projectUuid } = req.params
26-
const tuhatProjects = await getRiskWithTuhatProjectId(projectUuid)
27-
28-
return res.send(tuhatProjects)
29-
})
28+
)
3029

3130
export default myResearchApiRouter

tests/api.spec.ts

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,3 +385,153 @@ test.describe('api', () => {
385385
expect(putError.error).toContain('Unauthorized')
386386
})
387387
})
388+
389+
test.describe('riskiapi', () => {
390+
const tuhatId1 = 'test-tuhat-project-123'
391+
const tuhatId2 = 'test-tuhat-project-456'
392+
393+
test.beforeAll(async () => {
394+
const payload1 = {
395+
data: {
396+
'1': 'Testi Kayttaja',
397+
'2': testUser,
398+
'3': 'Tuhat Project Test',
399+
'4': 'bilateral',
400+
'6': 'university',
401+
'8': 'Afghanistan',
402+
'9': 'partner',
403+
'10': 'agreementNotDone',
404+
'11': ['education'],
405+
'12': 'mediumDuration',
406+
'13': 'noExternalFunding',
407+
'16': 'mediumBudget',
408+
'17': 'noTransferPersonalData',
409+
'20': 'Kardan University',
410+
'23': 'noTransferMilitaryKnowledge',
411+
'24': 'noSuccessfulCollaboration',
412+
'25': 'likelyNoEthicalIssues',
413+
faculty: 'H40',
414+
unit: 'H528',
415+
tuhatProjectExists: 'tuhatOptionPositive',
416+
},
417+
sessionToken: 'riskiapi-test-session',
418+
tuhatData: {
419+
tuhatId: tuhatId1,
420+
name: { fi: 'Testiprojekti', en: 'Test Project' },
421+
startDate: '2024-01-01',
422+
endDate: '2025-12-31',
423+
},
424+
}
425+
426+
const payload2 = {
427+
data: {
428+
'1': 'Testi Kayttaja',
429+
'2': testUser,
430+
'3': 'Specific Tuhat Project',
431+
'4': 'bilateral',
432+
'6': 'university',
433+
'8': 'Sweden',
434+
'9': 'coordinator',
435+
'10': 'agreementDone',
436+
'11': ['research'],
437+
'12': 'shortDuration',
438+
'13': 'noExternalFunding',
439+
'16': 'smallBudget',
440+
'17': 'noTransferPersonalData',
441+
'20': 'Stockholm University',
442+
'23': 'noTransferMilitaryKnowledge',
443+
'24': 'successfulCollaboration',
444+
'25': 'likelyNoEthicalIssues',
445+
faculty: 'H40',
446+
unit: 'H528',
447+
tuhatProjectExists: 'tuhatOptionPositive',
448+
},
449+
sessionToken: 'riskiapi-specific-test-session',
450+
tuhatData: {
451+
tuhatId: tuhatId2,
452+
name: { fi: 'Yksittäinen projekti', en: 'Individual Project' },
453+
startDate: '2024-06-01',
454+
endDate: '2025-05-31',
455+
},
456+
}
457+
458+
await fetch(`${baseUrl}/api/entries/1`, {
459+
method: 'POST',
460+
headers: { 'Content-Type': 'application/json' },
461+
body: JSON.stringify(payload1),
462+
})
463+
464+
await fetch(`${baseUrl}/api/entries/1`, {
465+
method: 'POST',
466+
headers: { 'Content-Type': 'application/json' },
467+
body: JSON.stringify(payload2),
468+
})
469+
})
470+
471+
test('GET /api/riskiapi/projects requires API key', async () => {
472+
const response = await fetch(`${baseUrl}/api/riskiapi/projects`, {
473+
method: 'GET',
474+
headers: { 'Content-Type': 'application/json' },
475+
})
476+
477+
expect(response.status).toBe(401)
478+
const data = await response.json()
479+
expect(data.error).toBe('unauthorised')
480+
})
481+
482+
test('GET /api/riskiapi/projects works with valid API key and returns data', async () => {
483+
const response = await fetch(`${baseUrl}/api/riskiapi/projects`, {
484+
method: 'GET',
485+
headers: {
486+
'Content-Type': 'application/json',
487+
'api-key': 'default',
488+
},
489+
})
490+
491+
expect(response.status).toBe(200)
492+
const data = await response.json()
493+
expect(Array.isArray(data)).toBe(true)
494+
expect(data.length).toBeGreaterThan(0)
495+
496+
const project = data.find(p => p.tuhatId === tuhatId1)
497+
expect(project).toBeDefined()
498+
expect(project.tuhatId).toBe(tuhatId1)
499+
expect(project.riskAnalysis).toBeDefined()
500+
expect(project.riskAnalysis.totalRisk).toBeDefined()
501+
expect(project.riskAnalysis.totalRisk.level).toBe(3)
502+
expect(project.createdAt).toBeDefined()
503+
expect(project.updatedAt).toBeDefined()
504+
})
505+
506+
test('GET /api/riskiapi/projects/:projectUuid requires API key', async () => {
507+
const response = await fetch(`${baseUrl}/api/riskiapi/projects/${tuhatId2}`, {
508+
method: 'GET',
509+
headers: { 'Content-Type': 'application/json' },
510+
})
511+
512+
expect(response.status).toBe(401)
513+
const data = await response.json()
514+
expect(data.error).toBe('unauthorised')
515+
})
516+
517+
test('GET /api/riskiapi/projects/:projectUuid works with valid API key and returns data', async () => {
518+
const response = await fetch(`${baseUrl}/api/riskiapi/projects/${tuhatId2}`, {
519+
method: 'GET',
520+
headers: {
521+
'Content-Type': 'application/json',
522+
'api-key': 'default',
523+
},
524+
})
525+
526+
expect(response.status).toBe(200)
527+
const data = await response.json()
528+
expect(data).toBeDefined()
529+
expect(data.tuhatId).toBe(tuhatId2)
530+
expect(data.riskAnalysis).toBeDefined()
531+
expect(data.riskAnalysis.totalRisk).toBeDefined()
532+
expect(data.riskAnalysis.totalRisk.level).toBe(1)
533+
expect(data.riskAnalysis.countryTotal).toBeDefined()
534+
expect(data.createdAt).toBeDefined()
535+
expect(data.updatedAt).toBeDefined()
536+
})
537+
})

0 commit comments

Comments
 (0)