if (fcf.isServer())
  var libCryptoJS = require("crypto-js");

fcf.module({
  name: "fcf:NSystem/authorizationHandler.js",
  dependencies: [],
  module: function(){
    var Namespace = fcf.prepareObject(fcf, "NAuthorization");

    class AuthorizationHandler {
      constructor(){
      }

      initialize(){
        fcf.application.getEventChannel().on("loading_template", (a_event)=>{
          if (fcf.empty(a_event.template.options.access))
            return;
          let roles = fcf.getContext().session.user.roles ? fcf.getContext().session.user.roles : {};
          if ("root" in roles)
            return;
          for(let i = 0; i < a_event.template.options.access.length; ++i)
            if (a_event.template.options.access[i] in roles)
              return;
          throw new fcf.Exception("ERROR_ACCESS", {resource: a_event.path, responseCode: 403});
        });
      }

      getDBPassword(a_pass){
        a_pass += "789" + a_pass + "789";
        return libCryptoJS.MD5(
                libCryptoJS.MD5(
                  libCryptoJS.MD5(
                    libCryptoJS.MD5(
                      libCryptoJS.MD5(a_pass).toString()
                      ).toString()
                    ).toString()
                  ).toString()
                ).toString();
      }
    };

    Namespace.authorizationHandler = new AuthorizationHandler();

    return Namespace.authorizationHandler;
  }
});
