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.

login.js 3.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. 'use strict'
  2. const Joi = require('joi')
  3. const errorSchema = require('../../schemas/errors')
  4. const userSchema = require('../../schemas/user')
  5. const pluginConfig = {
  6. handlerType: 'user',
  7. docs: {
  8. description: 'login',
  9. notes: 'Attempt login',
  10. },
  11. }
  12. /** Validator functions by request method */
  13. const validators = {
  14. post: {
  15. payload: Joi.object({
  16. user_email: Joi.string(),
  17. password: Joi.string(),
  18. }),
  19. },
  20. user: userSchema.single,
  21. error: errorSchema.single,
  22. }
  23. module.exports = {
  24. method: 'POST',
  25. path: '/login',
  26. options: {
  27. ...pluginConfig.docs,
  28. tags: ['api'],
  29. auth: false,
  30. handler: async function (request, h) {
  31. try {
  32. const { userService } = request.server.services()
  33. const res = request.payload
  34. // Callback to use as transaction
  35. const login = async txn => {
  36. return await userService.login(
  37. {
  38. email: res.user_email,
  39. password: res.password,
  40. },
  41. txn,
  42. )
  43. }
  44. // Bound context from your plugin server declaration
  45. await h.context.transaction(login)
  46. // Uses Same Logic Behind Initial Sign Up,
  47. // passing expected credentials to be used for logging in
  48. const { userCredentials, token } =
  49. await userService.makeUserCredentials(res.user_email)
  50. return {
  51. ok: true,
  52. handler: pluginConfig.handlerType,
  53. data: {
  54. user_email: userCredentials.email,
  55. jwt: token,
  56. answered: userCredentials,
  57. },
  58. }
  59. } catch (err) {
  60. console.error(err)
  61. return {
  62. ok: false,
  63. handler: pluginConfig.handlerType,
  64. data: { error: `${err}` },
  65. }
  66. }
  67. },
  68. validate: validators.post,
  69. response: {
  70. status: {
  71. 201: Joi.object({
  72. ok: Joi.bool(),
  73. handler: Joi.string(),
  74. data: Joi.object({
  75. user_email: Joi.string(),
  76. jwt: Joi.string(),
  77. answered: Joi.object({
  78. email: Joi.string(),
  79. name: Joi.string(),
  80. seeking: Joi.string(),
  81. }),
  82. }),
  83. }).label('login_res'),
  84. 409: Joi.object({
  85. ok: Joi.bool(),
  86. handler: Joi.string(),
  87. data: validators.error,
  88. }).label('login_error'),
  89. },
  90. },
  91. },
  92. }