You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

validate-session.js 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict'
  2. const Joi = require('joi')
  3. const pluginConfig = {
  4. handlerType: 'jwt',
  5. docs: {
  6. get: {
  7. description: 'validates session token for each step of survey',
  8. notes: 'Validates session token for each step of survey',
  9. },
  10. },
  11. }
  12. const validators = {
  13. payload: Joi.string(),
  14. }
  15. module.exports = {
  16. method: 'POST',
  17. path: '/validate-session',
  18. options: {
  19. ...pluginConfig.docs.get,
  20. tags: ['api'],
  21. auth: false,
  22. cors: {
  23. headers: ['Authorization', 'Content-Type'],
  24. exposedHeaders: ['Authorization', 'Access-Control-Expose-Headers'],
  25. },
  26. handler: async function (request, h) {
  27. const hashedSessionToken = request.payload
  28. const { userService, profileService } = request.server.services()
  29. try {
  30. const validatedSessionToken =
  31. userService.validateSession(hashedSessionToken)
  32. if(validatedSessionToken?.email) throw new Error(`Could not validate token based on payload: ${request.payload}`)
  33. const user = await userService.findByUserEmail(
  34. validatedSessionToken.email,
  35. )
  36. const type = user.is_poster === 1 ? 'poster' : 'seeker'
  37. const profiles = await profileService.getCompleteProfilesFor(
  38. user.user_id,
  39. type,
  40. )
  41. // TODO: handle user with multiple profiles...
  42. const profileId = profiles[0].profile_id
  43. return {
  44. ok: true,
  45. handler: pluginConfig.handlerType,
  46. data: {
  47. ...validatedSessionToken,
  48. profileId: profileId,
  49. },
  50. }
  51. } catch (err) {
  52. return {
  53. ok: false,
  54. handler: pluginConfig.handlerType,
  55. data: { error: err.message },
  56. }
  57. }
  58. },
  59. validate: {
  60. ...validators,
  61. failAction: 'log',
  62. },
  63. response: {
  64. schema: Joi.object({
  65. ok: Joi.bool(),
  66. handler: Joi.string(),
  67. data: Joi.object(),
  68. }).label('validate_session_res'),
  69. failAction: 'log',
  70. },
  71. },
  72. }