{"size": 1342, "ext": "js", "max_stars_repo_path": "servers/controllers/UserController.js", "max_stars_repo_name": "JustineRobert/Teamwork", "max_stars_repo_stars_event_min_datetime": "2019-11-14T15:30:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T12:03:45.000Z", "max_issues_repo_path": "servers/controllers/UserController.js", "max_issues_repo_name": "JustineRobert/Teamwork", "max_issues_repo_issues_event_min_datetime": "2019-11-10T10:01:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T06:24:58.000Z", "max_forks_repo_path": "servers/controllers/UserController.js", "max_forks_repo_name": "JustineRobert/Teamwork", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 3, "max_issues_count": 61, "max_forks_count": null, "avg_line_length": 41.9375, "max_line_length": 99, "alphanum_fraction": 0.7078986587}
const Helpers = require('../helpers/Helpers');
const users = require('../mock/user');
const { User } = require('../models');

const user = new User();

class UserController {
  static async signUp(request, response) {
    const data = request.body;
    data.password = Helpers.hashPassword(request.body.password);
    const checkEmail = await user.getByEmail(data.email);
    if (checkEmail.errors) return Helpers.dbError(response, checkEmail);
    if (checkEmail.count > 0) return Helpers.sendResponse(response, 409, 'Email already exists !');
    const saveUser = await user.create(data);
    if (saveUser.errors) return Helpers.dbError(response, saveUser);
    const token = Helpers.generateToken(saveUser.rows[0].id);
    return Helpers.sendResponse(response, 201, 'User created successfully', { token });
  }

  static async signIn(request, response) {
    const { email, password } = request.body;
    const _user = await user.getByEmail(email);
    Helpers.dbError(response, _user);
    if (_user.count > 0 && Helpers.comparePassword(_user.row.password, password)) {
      const token = Helpers.generateToken(_user.row.id);
      return Helpers.sendResponse(response, 200, 'User is successfully logged in', { token });
    }
    return Helpers.sendResponse(response, 400, 'Invalid credentials');
  }
}

module.exports = UserController;