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.

authenticatelogin.js 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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: 'authenticate 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.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. const user = await h.context.transaction(login)
  46. const token = userService.createToken(user)
  47. return {
  48. ok: true,
  49. handler: pluginConfig.handlerType,
  50. data: { user_email: user.user_email, jwtToken: token },
  51. }
  52. } catch (err) {
  53. console.error(err)
  54. return {
  55. ok: false,
  56. handler: pluginConfig.handlerType,
  57. data: { error: `${err}` },
  58. }
  59. }
  60. },
  61. validate: validators.post,
  62. response: {
  63. status: {
  64. 201: Joi.object({
  65. ok: Joi.bool(),
  66. handler: Joi.string(),
  67. data: Joi.object({
  68. user_email: Joi.string(),
  69. jwtToken: Joi.string(),
  70. }),
  71. }).label('login_res'),
  72. 409: Joi.object({
  73. ok: Joi.bool(),
  74. handler: Joi.string(),
  75. data: validators.error,
  76. }).label('login_error'),
  77. },
  78. },
  79. },
  80. }