{"size": 1281, "ext": "js", "max_stars_repo_path": "api/auth/auth-routes.js", "max_stars_repo_name": "BW-Intl-Child-Nutrition-Status-Tracking/back-end", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "api/auth/auth-routes.js", "max_issues_repo_name": "BW-Intl-Child-Nutrition-Status-Tracking/back-end", "max_issues_repo_issues_event_min_datetime": "2021-05-10T19:49:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-10T19:49:55.000Z", "max_forks_repo_path": "api/auth/auth-routes.js", "max_forks_repo_name": "BW-Intl-Child-Nutrition-Status-Tracking/back-end", "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": 22.4736842105, "max_line_length": 66, "alphanum_fraction": 0.5683060109}
const router = require('express').Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

const secret = require('../../data/config/secrets.js');
const Users = require('../models/user-models.js');

router.post('/add-user', (req, res) => {
  let user = req.body;
  const hash = bcrypt.hashSync(user.password, 14);
  user.password = hash;

  Users
    .add(user)
    .then(saved => {
      res.status(201).json(saved);
    })
    .catch(err => {
      res.status(500).json(err);
    });
})

router.post('/login', (req, res) => {
  let { username, password } = req.body;

  Users
    .findBy({ username })
    .first()
    .then(user => {
      if(user && bcrypt.compareSync(password, user.password)) {
        const token = getJwtToken(user.name);

        Users
          .findById(user.id)
          .then(() => {
            res.status(200).json(token);
          });
      } else {
        res.status(401).json({ message: `Invalid credentials.` });
      };
    })
    .catch(err => {
      console.log(err);
      res.status(500).json(err);
    });
});

function getJwtToken(username) {
  const payload = { username };
  const options = {
    expiresIn: '30d'
  };

  return jwt.sign(payload, secret.jwtSecrets, options);
};

module.exports = router;