text: "use strict";
  var __importDefault = (this && this.__importDefault) || function (mod) {
      return (mod && mod.__esModule) ? mod : { "default": mod };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.authRouter = void 0;
  const express_1 = __importDefault(require("express"));
  const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
  const lodash_1 = __importDefault(require("lodash"));
  const app_error_1 = require("../core/app-error");
  const config_1 = require("../core/config");
  const account_manager_1 = require("../core/services/account-manager");
  const security_1 = require("../core/utils/security");
  // route for auth web pages
  exports.authRouter = express_1.default.Router();
  exports.authRouter.get('/password', (req, res) => {
      res.render('auth/password', { title: 'CodePushServer' });
  });
  exports.authRouter.get('/login', (req, res) => {
      res.render('auth/login', {
          title: 'CodePushServer',
          email: req.query.email || '',
          showRegister: config_1.config.common.allowRegistration,
      });
  });
  exports.authRouter.get('/link', (req, res) => {
      res.redirect(`/auth/login`);
  });
  exports.authRouter.get('/register', (req, res) => {
      if (config_1.config.common.allowRegistration) {
          res.render('auth/register', { title: 'CodePushServer', email: req.query.email || '' });
      }
      else {
          res.redirect(`/auth/login`);
      }
  });
  exports.authRouter.get('/confirm', (req, res) => {
      res.render('auth/confirm', { title: 'CodePushServer', email: req.query.email || '' });
  });
  exports.authRouter.post('/logout', (req, res) => {
      res.send('ok');
  });
  exports.authRouter.post('/login', (req, res, next) => {
      const { logger, body } = req;
      const account = lodash_1.default.trim(body.account);
      const password = lodash_1.default.trim(body.password);
      logger.info('try login', {
          account,
      });
      account_manager_1.accountManager
          .login(account, password)
          .then((users) => {
          logger.info('login success', {
              account,
              uid: users.id,
          });
          return jsonwebtoken_1.default.sign({ uid: users.id, hash: (0, security_1.md5)(users.ack_code), expiredIn: 7200 }, config_1.config.jwt.tokenSecret);
      })
          .then((token) => {
          logger.info('jwt token signed', {
              account,
          });
          res.send({ status: 'OK', results: { tokens: token } });
      })
          .catch((e) => {
          if (e instanceof app_error_1.AppError) {
              logger.info('login failed', {
                  account,
                  error: e.message,
              });
              res.send({ status: 'ERROR', message: e.message });
          }
          else {
              next(e);
          }
      });
  });
  