'use strict';

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

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

var middleware = function middleware(req, res, next) {
  if (!_cli.config.users.enable) {
    if (req.url.indexOf('/abe/users/login') > -1) {
      res.redirect('/abe/editor');
      return;
    } else {
      next();
      return;
    }
  }

  var decoded = _cli.User.utils.decodeUser(req, res);
  var user = _cli.User.utils.findSync(decoded.iss);
  res.user = user;

  if (!_cli.User.utils.isAbeRestrictedUrl(req.url)) {
    if (user != null && req.url.indexOf('/abe/users/login') > -1 && req.method === 'GET') {
      res.redirect('/abe/editor');
      return;
    } else {
      next();
      return;
    }
  }

  var isHtml = /text\/html/.test(req.get('accept')) ? true : false;

  if (user != null && _cli.User.utils.isUserAllowedOnRoute(user.role.workflow, req.url)) {
    next();
  } else {
    if (isHtml) {
      res.redirect('/abe/users/login');
    } else {
      var notAuthorized = {
        success: 0,
        message: 'Not authorized !'
      };
      res.set('Content-Type', 'application/json');
      res.send(JSON.stringify(notAuthorized));
    }
  }
};

exports.default = middleware;