From 53c0edf18985aecd1c2322cd2e95eae3abb9160d Mon Sep 17 00:00:00 2001 From: Tereshchenko Aleksandr Date: Wed, 20 Mar 2024 14:48:51 +0200 Subject: [PATCH] backend: Add person search endpoint to enable Login As flow --- backend/src/controllers/PersonController.js | 10 ++++++++++ backend/src/routes/persons.js | 2 ++ backend/src/services/PersonService.js | 17 +++++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/backend/src/controllers/PersonController.js b/backend/src/controllers/PersonController.js index 592f2b40..38f3f2af 100644 --- a/backend/src/controllers/PersonController.js +++ b/backend/src/controllers/PersonController.js @@ -8,6 +8,16 @@ const programmeService = require('../services/ProgrammeService') // const emailInviteService = require('../services/EmailInviteService') const emailService = require('../services/EmailService') +export async function findPersons(req, res) { + const { search } = req.query + if (search.length < 5) { + throw Error('Search string must be at least 5 characters long') + } + + const persons = await personService.searchPersons(search) + res.status(200).json(persons) +} + /** * Get persons that are of interest to the person doing query */ diff --git a/backend/src/routes/persons.js b/backend/src/routes/persons.js index 502e4add..7f25bde7 100644 --- a/backend/src/routes/persons.js +++ b/backend/src/routes/persons.js @@ -43,6 +43,8 @@ const jsonParser = bodyParser.json() */ router.get('/', auth.checkManagerOrAdmin, (req, res, next) => personController.getPersons(req, res).catch(next)) +router.get('/search', auth.checkAdmin, (req, res, next) => personController.findPersons(req, res).catch(next)) + /** * @api {post} persons/invite Invite person to role * @apiName InvitePerson diff --git a/backend/src/services/PersonService.js b/backend/src/services/PersonService.js index 161ae201..2e5e8332 100644 --- a/backend/src/services/PersonService.js +++ b/backend/src/services/PersonService.js @@ -184,6 +184,23 @@ export const getPendingPersonsWithRole = async (roleId, programmeId) => ( export const getPersonByEmail = async email => Person.where({ email: email.toLowerCase() }).fetch() +export const searchPersons = async (userQuery) => { + let query + + if (userQuery.split(' ').length === 2) { + const firstName = userQuery.split(' ')[0] + const lastName = userQuery.split(' ')[1] + query = qb => qb.where('firstname', 'iLIKE', `%${firstName}%`) + .orWhere('lastname', 'iLIKE', `%${lastName}%`) + } else { + query = qb => qb.where('email', 'iLIKE', `%${userQuery}%`) + .orWhere('firstname', 'iLIKE', `%${userQuery}%`) + .orWhere('lastname', 'iLIKE', `%${userQuery}%`) + } + + return Person.query(query).fetchAll() +} + export const updateNonRegisteredPerson = async (person, studentNumber, shibbolethId) => ( person.set({ studentNumber, shibbolethId }).save() )