<commit_before>/**
 *  Copyright 2012 <NAME>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

var async = require('async');
var log = require('logmagic').local('lib.middleware.authentication');
var sprintf = require('sprintf').sprintf;

var client = require('../database').getClient();
var request = require('../util/request').request;
var KeystoneClient = require('../util/keystone_client').KeystoneClient;

var US_AUTH_SERVICE_URL = 'https://auth.api.rackspacecloud.com/v2.0';
var UK_AUTH_SERVICE_URL = 'https://lon.auth.api.rackspacecloud.com/v2.0';


/**
 * Middleware for authenticating against the Rackspace Cloud Auth API.
 *
 * If a valid token is provided is also cached in Redis until it expires.
 */

function cacheToken(cacheKey, tenantId, token, expires, callback) {
  var expiresTs = misc.dateStrToUnixTimestamp(expires),
      nowTs = new Date().getTime() / 1000,
      ttl = (expiresTs - nowTs),
      data = {
        'token': token,
        'tenantId': tenantId
      },
      multi = client.multi();

  if (ttl < 1) {
    log.info('Token already expired, not caching it...');
    callback();
    return;
  }

  log.info('Caching new auth token', {'tenantId': tenantId, 'expires': expires});

  multi.set(key, value);
  expire.ttl(key, ttl);
  multi.exec(callback);
}

function verifyToken(tenantId, token, callback) {
  var clientParams = [{'url': US_AUTH_SERVICE_URL, 'options': {}}, {'url': UK_AUTH_SERVICE_URL, 'options': {}}],
      result = {};

  async.some(clientParams, function(params, callback) {
    var client = new KeystoneClient(params.url, params.options);

    client.validateTokenForTenant(tenantId, token, function(err, data) {
      if (err) {
        log.error('Auth service returned an error', {'url': params.url, 'err': err});
        callback(false);
      }

      if (!err && data) {
        log.debug('Auth service returned that a token is valid', {'url': params.url});
        result.username = data.token.userId;
        result.expires = data.token.expires;
        callback(true);
      }
    });
  },<commit_msg>Add missing return.<commit_after>/**
 *  Copyright 2012 <NAME>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

var async = require('async');
var log = require('logmagic').local('lib.middleware.authentication');
var sprintf = require('sprintf').sprintf;

var client = require('../database').getClient();
var request = require('../util/request').request;
var KeystoneClient = require('../util/keystone_client').KeystoneClient;

var US_AUTH_SERVICE_URL = 'https://auth.api.rackspacecloud.com/v2.0';
var UK_AUTH_SERVICE_URL = 'https://lon.auth.api.rackspacecloud.com/v2.0';


/**
 * Middleware for authenticating against the Rackspace Cloud Auth API.
 *
 * If a valid token is provided is also cached in Redis until it expires.
 */

function cacheToken(cacheKey, tenantId, token, expires, callback) {
  var expiresTs = misc.dateStrToUnixTimestamp(expires),
      nowTs = new Date().getTime() / 1000,
      ttl = (expiresTs - nowTs),
      data = {
        'token': token,
        'tenantId': tenantId
      },
      multi = client.multi();

  if (ttl < 1) {
    log.info('Token already expired, not caching it...');
    callback();
    return;
  }

  log.info('Caching new auth token', {'tenantId': tenantId, 'expires': expires});

  multi.set(key, value);
  expire.ttl(key, ttl);
  multi.exec(callback);
}

function verifyToken(tenantId, token, callback) {
  var clientParams = [{'url': US_AUTH_SERVICE_URL, 'options': {}}, {'url': UK_AUTH_SERVICE_URL, 'options': {}}],
      result = {};

  async.some(clientParams, function(params, callback) {
    var client = new KeystoneClient(params.url, params.options);

    client.validateTokenForTenant(tenantId, token, function(err, data) {
      if (err) {
        log.error('Auth service returned an error', {'url': params.url, 'err': err});
        callback(false);
        return;
      }

      if (!err && data) {
        log.debug('Auth service returned that a token is valid', {'url': params.url});
        result.username = data.token.userId;
        result.expires = data.token.expires;
        callback(true);
      }
    });
  },
{'fraction_non_alphanumeric': 0.13664357197844496, 'fraction_numerical': 0.006543494996150885, 'mean_word_length': 3.415463041631266, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '950107', 'n_tokens_mistral': 1597, 'n_tokens_neox': 1554, 'n_words': 465}