'use strict' const Joi = require('joi') const errorSchema = require('../../schemas/errors') const userSchema = require('../../schemas/user') const pluginConfig = { handlerType: 'user', docs: { description: 'login', notes: 'Attempt login', }, } /** Validator functions by request method */ const validators = { post: { payload: Joi.object({ user_email: Joi.string(), password: Joi.string(), }), }, user: userSchema.single, error: errorSchema.single, } module.exports = { method: 'POST', path: '/login', options: { ...pluginConfig.docs, tags: ['api'], auth: false, handler: async function (request, h) { try { const { userService } = request.server.services() const res = request.payload // Callback to use as transaction const login = async txn => { return await userService.login( { email: res.user_email, password: res.password, }, txn, ) } // Bound context from your plugin server declaration await h.context.transaction(login) // Uses Same Logic Behind Initial Sign Up, // passing expected credentials to be used for logging in const { userCredentials, token } = await userService.makeUserCredentials(res.user_email) return { ok: true, handler: pluginConfig.handlerType, data: { user_email: userCredentials.email, jwt: token, answered: userCredentials, }, } } catch (err) { console.error(err) return { ok: false, handler: pluginConfig.handlerType, data: { error: `${err}` }, } } }, validate: validators.post, response: { status: { 201: Joi.object({ ok: Joi.bool(), handler: Joi.string(), data: Joi.object({ user_email: Joi.string(), jwt: Joi.string(), answered: Joi.object({ email: Joi.string(), name: Joi.string(), seeking: Joi.string(), }), }), }).label('login_res'), 409: Joi.object({ ok: Joi.bool(), handler: Joi.string(), data: validators.error, }).label('login_error'), }, }, }, }