'use strict';

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _debug = require('debug');

var _debug2 = _interopRequireDefault(_debug);

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

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var debug = (0, _debug2.default)('feathers-authentication-jwt:verify');

var JWTVerifier = function () {
  function JWTVerifier(app) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    _classCallCheck(this, JWTVerifier);

    this.app = app;
    this.options = options;
    this.service = typeof options.service === 'string' ? app.service(options.service) : options.service;

    if (!this.service) {
      throw new Error('options.service does not exist.\n\tMake sure you are passing a valid service path or service instance and it is initialized before feathers-authentication-jwt.');
    }

    this.verify = this.verify.bind(this);
  }

  _createClass(JWTVerifier, [{
    key: 'verify',
    value: function verify(req, payload, done) {
      var _this = this;

      debug('Received JWT payload', payload);

      var id = payload[this.options.entity + 'Id'];

      if (id === undefined) {
        debug('JWT payload does not contain ' + this.options.entity + 'Id');
        return done(null, {}, payload);
      }

      debug('Looking up ' + this.options.entity + ' by id', id);

      this.service.get(id).then(function (entity) {
        var newPayload = _defineProperty({}, _this.options.entity + 'Id', id);
        return done(null, entity, newPayload);
      }).catch(function (error) {
        debug('Error populating ' + _this.options.entity + ' with id ' + id, error);
        return done(null, {}, payload);
      });
    }
  }]);

  return JWTVerifier;
}();

exports.default = JWTVerifier;
module.exports = exports['default'];