'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: userSchema.single, error: errorSchema.single, }) .append() .label('login_payload'), }, user: userSchema.single, } module.exports = { method: 'POST', path: '/login', options: { ...pluginConfig.docs, tags: ['api'], auth: false, handler: async function (request, h) { try { const { userService, displayService } = request.services() const res = request.payload // Callback to use as transaction const login = async txn => { return await userService.login( { email: res.user.email, password: res.user.password, }, txn, ) } // Bound context from your plugin server declaration const user = await h.context.transaction(login) const token = userService.createToken(user) return { ok: true, handler: pluginConfig.handlerType, data: displayService.user(user, token), } } catch (err) { console.error(err) return { ok: false, handler: pluginConfig.handlerType, data: { error: `${err}` }, } } }, validate: validators.post, response: { schema: Joi.object({ ok: Joi.bool(), handler: Joi.string(), data: validators.user, }).label('login_res'), failAction: 'log', }, }, }