Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

login.js 3.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. cors: true,
  31. handler: async function (request, h) {
  32. try {
  33. const { userService } = request.server.services()
  34. const res = request.payload
  35. // Callback to use as transaction
  36. const login = async txn => {
  37. return await userService.login(
  38. {
  39. email: res.user_email,
  40. password: res.password,
  41. },
  42. txn,
  43. )
  44. }
  45. // Bound context from your plugin server declaration
  46. await h.context.transaction(login)
  47. // Uses Same Logic Behind Initial Sign Up,
  48. // passing expected credentials to be used for logging in
  49. const { userCredentials, token } =
  50. await userService.makeUserCredentials(res.user_email)
  51. return {
  52. ok: true,
  53. handler: pluginConfig.handlerType,
  54. data: {
  55. user_email: userCredentials.email,
  56. jwt: token,
  57. answered: userCredentials,
  58. },
  59. }
  60. } catch (err) {
  61. console.error(err)
  62. return {
  63. ok: false,
  64. handler: pluginConfig.handlerType,
  65. data: { error: `${err}` },
  66. }
  67. }
  68. },
  69. validate: validators.post,
  70. response: {
  71. status: {
  72. 201: Joi.object({
  73. ok: Joi.bool(),
  74. handler: Joi.string(),
  75. data: Joi.object({
  76. user_email: Joi.string(),
  77. jwt: Joi.string(),
  78. answered: Joi.object({
  79. email: Joi.string(),
  80. name: Joi.string(),
  81. seeking: Joi.string(),
  82. }),
  83. }),
  84. }).label('login_res'),
  85. 409: Joi.object({
  86. ok: Joi.bool(),
  87. handler: Joi.string(),
  88. data: validators.error,
  89. }).label('login_error'),
  90. },
  91. },
  92. },
  93. }