| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- 'use strict'
-
- const Joi = require('joi')
- const errorSchema = require('../../schemas/errors')
- const userSchema = require('../../schemas/user')
-
- const pluginConfig = {
- handlerType: 'user',
- docs: {
- description: 'authenticate 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.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
- const user = await h.context.transaction(login)
- const token = userService.createToken(user)
-
- return {
- ok: true,
- handler: pluginConfig.handlerType,
- data: { user_email: user.user_email, jwtToken: token },
- }
- } 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(),
- jwtToken: Joi.string(),
- }),
- }).label('login_res'),
- 409: Joi.object({
- ok: Joi.bool(),
- handler: Joi.string(),
- data: validators.error,
- }).label('login_error'),
- },
- },
- },
- }
|