'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _cookies = require('cookies');

var _cookies2 = _interopRequireDefault(_cookies);

var _moment = require('moment');

var _moment2 = _interopRequireDefault(_moment);

var _passportLocal = require('passport-local');

var _passportLocal2 = _interopRequireDefault(_passportLocal);

var _passport = require('passport');

var _passport2 = _interopRequireDefault(_passport);

var _jwtSimple = require('jwt-simple');

var _jwtSimple2 = _interopRequireDefault(_jwtSimple);

var _cli = require('../../../../cli');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Strategy
 */
_passport2.default.use(new _passportLocal2.default(function (username, password, done) {
  _cli.User.utils.findByUsername(username, function (err, user) {
    if (err) {
      return done(err);
    }
    if (!user) {
      return done(null, false, { message: 'Incorrect username or password.' });
    }
    if (!_cli.User.utils.isValid(user, password)) {
      return done(null, false, { message: 'Incorrect username or password.' });
    }
    return done(null, user);
  });
}));

_passport2.default.serializeUser(function (user, done) {
  done(null, user.id);
});

_passport2.default.deserializeUser(function (id, done) {
  _cli.User.utils.find(id, function (err, user) {
    done(err, user);
  });
});

var route = function route(req, res, next) {
  _cli.User.utils.loginLimitTry(req.body.username).then(function (limit) {
    if (limit != null) {
      // all good
      if (!limit.remaining) {
        req.flash('info', 'Rate limit exceeded');
        return res.redirect('/abe/users/login');
      }
    }

    _passport2.default.authenticate('local', { session: false }, function (err, user, info) {
      var secret = _cli.config.users.secret;
      if (err) {
        return next(err);
      }

      if (!user) {
        req.flash('info', info.message);
        return res.redirect('/abe/users/login');
        // return res.status(401).json({ error: info });
      }
      var expires = (0, _moment2.default)().add(7, 'days').valueOf();
      var token = _jwtSimple2.default.encode({
        iss: user.id,
        exp: expires,
        username: user.username,
        name: user.name,
        email: user.email,
        role: user.role
      }, secret);

      var cookies = new _cookies2.default(req, res, {
        secure: _cli.config.cookie.secure
      });
      cookies.set('x-access-token', token);

      res.redirect('/abe/editor/');
    })(req, res, next);
  });
};

exports.default = route;