{"size": 1176, "ext": "js", "max_stars_repo_path": "src/controllers/auth-controller.js", "max_stars_repo_name": "corbiton/authenticator", "max_stars_repo_stars_event_min_datetime": "2020-03-15T08:30:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-15T08:30:44.000Z", "max_issues_repo_path": "src/controllers/auth-controller.js", "max_issues_repo_name": "yasir18/authenticator", "max_issues_repo_issues_event_min_datetime": "2020-03-14T08:11:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T08:01:04.000Z", "max_forks_repo_path": "src/controllers/auth-controller.js", "max_forks_repo_name": "yasir18/authenticator", "max_forks_repo_forks_event_min_datetime": "2020-03-14T06:54:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T11:39:21.000Z"}
{"max_stars_count": 1, "max_issues_count": 10, "max_forks_count": 8, "avg_line_length": 29.4, "max_line_length": 70, "alphanum_fraction": 0.6054421769}
const authService = require("../services/auth-service");

class AuthController {
  async register(req, res) {
    const { username, password } = req.body;
    try {
      await authService.register(username, password);
      res.status(201).json({ status: "Registration success" });
    } catch (e) {
      res.status(500).json({ status: "Internal server error" });
    }
  }

  async login(req, res) {
    const { username, password } = req.body;
    try {
      const loginStatus = await authService.login(username, password);
      if (loginStatus) {
        let payload = { username };
        const token = await authService.getToken(payload);
        payload.token = token;
        res.status(200).json({ status: "Login success", payload });
      } else {
        res.status(401).json({ status: "Login failed" });
      }
    } catch (e) {
      res.status(500).json({ status: "Internal server error" });
    }
  }

  authenticate(req, res) {
    authService.authenticate(req.body.token, (err, payload) => {
      if (err) res.status(401).json({ status: "Unauthorized" });
      else res.status(200).json(payload);
    });
  }
}

module.exports = new AuthController();
