var config = require('../config');

const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');
const jwtAuthz = require('express-jwt-authz');
const AuthenticationClient = require('auth0').AuthenticationClient;
var ManagementClient = require('auth0').ManagementClient;

// Create middleware for checking the JWT
const checkJwt = jwt({
  // Dynamically provide a signing key based on the kid in the header and the singing keys provided by the JWKS endpoint.
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: "https://" + config.auth0.domain + "/.well-known/jwks.json"
  }),

  // Validate the audience and the issuer.
  aud: config.auth0.audience,
  iss: "https://" + config.auth0.domain + "/",
  algorithms: ['RS256']
});

function checkAuth(scope_array) {
  return jwtAuthz(scope_array);
}

var authClient = new AuthenticationClient({
  domain:   config.auth0.domain,
  clientId:  config.auth0.clientID,
  clientSecret: config.auth0.secret
});

function registerAuthServices(app) {
  app.post('/services/getMetadata', checkJwt, function(req, res) {
    console.log(JSON.stringify(req.user));
    var metadata = {"user_metadata":
                    {"givenName": req.user["https://dashboard.votinginfoproject.org/givenName"]},
                    "app_metadata":
                    {"fipsCodes": req.user["https://dashboard.votinginfoproject.org/fipsCodes"],
                     "roles": req.user["https://dashboard.votinginfoproject.org/roles"]}}
    res.status(200).send(metadata);
  });
}

function obtainManagementToken(cb) {
  try {
    authClient.clientCredentialsGrant({
      audience: 'https://' + config.auth0.domain + '/api/v2/',
      scope: 'read:users read:users_app_metadata read:user_idp_tokens'
    }, function (err, response) {
      if (err) {
        // Handle error.
        console.log(err);
      }
      cb(response.access_token);
    });
  } catch (e) {
    console.log(e);
  };
};

function getUsersByFips(fips, cb) {
  obtainManagementToken(function (token) {
    var management = new ManagementClient({
      token: token,
      domain: config.auth0.domain
    });
    var params = {
      q: "app_metadata.fipsCodes." + fips + ": true"
    };
    management.getUsers(params, function(err, users) {
      if (err !== undefined) {
        console.log(err);
      } if (users !== undefined) {
        console.log(users);
      }
      cb(users);
    })
  });
};



exports.checkJwt = checkJwt;
exports.checkAuth = checkAuth;
exports.registerAuthServices = registerAuthServices;
exports.getUsersByFips = getUsersByFips;

@@ -1033,164 +1033,41 @@
 ion 
-registerAuthServices(app) %7B%0A  app.post('/services/getMetadata', checkJwt, function(req, res) %7B%0A    console.log(JSON.stringify(req.user));%0A    var metadata =
+getUserFromRequest(req) %7B%0A%09return
  %7B%22u
@@ -1081,33 +1081,20 @@
 adata%22:%0A
-                 
+%09%09%09%09
    %7B%22giv
@@ -1170,63 +1170,34 @@
 %5D%7D,%0A
-                    %22app_metadata%22:%0A                   
+%09%09%09%09%09%22app_metadata%22:%0A%09%09%09%09%09
  %7B%22f
@@ -1274,29 +1274,14 @@
 %22%5D,%0A
-                     
+%09%09%09%09%09%09
 %22rol
@@ -1344,16 +1344,557 @@
 oles%22%5D%7D%7D
+;%0A%7D;%0A%0Afunction getUserFipsCodes(req) %7B%0A%09var user = getUserFromRequest(req);%0A%09return Object.keys(user%5B%22app_metadata%22%5D%5B%22fipsCodes%22%5D);%0A%7D;%0A%0Afunction getUserRoles(req) %7B%0A%09var user = getUserFromRequest(req);%0A%09return user%5B%22app_metadata%22%5D%5B%22roles%22%5D;%0A%7D%0A%0Afunction isSuperAdmin(req) %7B%0A%09var roles = getUserRoles(req);%0A%09return roles.indexOf(%22super-admin%22) %3E= 0;%0A%7D%0A%0Afunction registerAuthServices(app) %7B%0A  app.post('/services/getMetadata', checkJwt, function(req, res) %7B%0A    console.log(JSON.stringify(req.user));%0A    var metadata = getUserFromRequest(req);
 %0A    res
@@ -2828,16 +2828,183 @@
 );%0A%7D;%0A%0A%0A
+exports.getUserFromRequest = getUserFromRequest;%0Aexports.getUserFipsCodes = getUserFipsCodes;%0Aexports.isSuperAdmin = isSuperAdmin;%0Aexports.getUserRoles = getUserRoles;
 %0Aexports

add functions in backend to get fips/roles/user/etc