{"size": 882, "ext": "js", "max_stars_repo_path": "src/controllers/login.js", "max_stars_repo_name": "kadriand/users-policies-assessment", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/controllers/login.js", "max_issues_repo_name": "kadriand/users-policies-assessment", "max_issues_repo_issues_event_min_datetime": "2021-05-11T17:42:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-11T17:42:53.000Z", "max_forks_repo_path": "src/controllers/login.js", "max_forks_repo_name": "kadriand/users-policies-assessment", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 1, "max_forks_count": null, "avg_line_length": 29.4, "max_line_length": 74, "alphanum_fraction": 0.5600907029}
// @flow

import * as clientsService from '../services/clients';
import {authenticate} from '../auth';
import type {Client} from "../models/client";
import * as Boom from "@hapi/boom";

/**
 * login user by email and password. The default password is the client id
 *
 * @param {Object} req
 * @param {Object} res
 * @param {Function} next
 */
export const login = (req, res, next) => {
    const {email, password} = req.body;
    clientsService.findClients({field: "email", value: email})
        .then((clients: Client[]) => {
                if (clients.length)
                    return clients[0];
                throw  Boom.notFound('Client not found');
            }
        )
        .then(client => authenticate(client, password))
        .then(authToken => {
                res.json({accessToken: authToken})
            }
        )
        .catch(err => next(err));
};