<commit_before>
/**
 *
 * Copyright 2015 Landstinget Dalarna Bibliotek och Informationscentral
 * Copyright 2015 <NAME> (@emilhem)
 *
 *
 * This file is part of Aaron.
 *
 * Aaron is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Aaron is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Aaron.  If not, see <http://www.gnu.org/licenses/>.
 *
 */


/**
 *
 * TODO: Make sure that a user can't be created as a number.
 * Test this by passing their username to isNaN(val) and make sure it's true.
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
 *
 */


'use strict';

var util    = require('util');

var jadeGen = require('../lib/jadeGenerator.js');

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

var maxRetries = 5;

var pool = {
  getConnection: function() {
    throw 'pool is not set!';
  }
};

var mysql_selectUser = [
  'SELECT user_id, user_legacyUsername, user_firstName, user_lastName, user_workplace, user_place, user_email, user_pemail, user_phonenumber, user_password, user_admin, user_activated',
  'FROM users',
  'WHERE ?? = ?;'
].join('\n');

var mysql_legacyToUserId = [
  'SELECT user_id',
  'FROM users',
  'WHERE user_legacyUsername = ?;'
].join('\n');

function setPool(newPool) {
  pool = newPool;
}

function mysqlError(err, callback) {
  console.error(err);
  if(callback) {
    callback('mysql-error', null);
  }
}

function legacyToID(user, callback, retries) {
  if(typeof user !== 'string' && typeof user !== 'number') {
    return callback('invalid-user-param');
  }
  pool.getConnection(function(err, connection) {
    if(err) {
      connection.release();
      if(retries && retries > maxRetries) {
        return mysqlError(err, callback);
      }
      return setTimeout(legacyToID, 100, user, callback, retries ? retries + 1 : 1);
    }
    connection.query(mysql_legacyToUserId, [user], function(err, rows) {
      connection.release();
      if(err) { // for connection releasing reasons, don't copy this one.
        if(retries && retries > maxRetries) {
          return mysqlError(err, callback);
        }
        return setTimeout(legacyToID, 100, user, callback, retries ? retries + 1 : 1);
      }
      callback(null, rows[0].user_id);
    });
  });
}

function getUser(user, callback, retries) {
  if(typeof user !== 'string' && typeof user !== 'number') {
    return callback('invalid-user-param');
  }
  pool.getConnection(function(err, connection) {
    if(err) {
      connection.release();
      if(retries && retries > maxRetries) {
        return mysqlError(err, callback);
      }
      return setTimeout(getUser, 100, user, callback, retries ? retries + 1 : 1);
    }
    connection.query(mysql_selectUser, [typeof user === 'string' ? 'user_legacyUsername' : 'user_id', user], function(err, data) {
      connection.release();
      if(err) { // for connection releasing reasons, don't copy this one.
        if(retries && retries > maxRetries) {
          return mysqlError(err, callback);
        }
        return setTimeout(getUser, 100, user, callback, retries ? retries + 1 : 1);
      }
      callback(null, data);
    });
  });
}

var mysql_getPermissions = [
  'SELECT permissions_id',
  'FROM users u',
  'LEFT JOIN users_has_groups ug ON u.user_id = ug.users_user_id',
  'LEFT JOIN groups g ON g.group_id = ug.groups_group_id',
  'LEFT JOIN groups_has_permissions gp ON g.group_id = gp.groups_group_id',
  'LEFT JOIN permissions p ON p.permission_id = gp.permissions_permission_id',
  'LEFT JOIN permissions_has_applications pa ON p.permission_id = pa.permissions_permission_id',
  'LEFT JOIN applications a ON a.application_shortname = pa.applications_application_shortname',
  'WHERE user_email = ?',
  'AND a.application_shortname = ?;'
].join('\n');

function getPermissions (req, res, next, retries) {
  if(req.loggedIn) {
    pool.getConnection(function(err, connection) {
      if(err) {
        connection.release();
        if(retries && retries > maxRetries) {
          mysqlError(err);
          res.status(500).end(jadeGen['500.jade']({debugInfo: config.debug ? util.inspect(err, { showHidden: true, depth: 5 }) : null}));
          return;
        }
        return setTimeout(getPermissions, 100, req, res, next, retries ? retries + 1 : 1);
      }
      connection.query(
        mysql_getPermissions,
        [req.authUser, 'aaron'],
        function(err, rows) {
          var i;
          connection.release();
          if(err) {
            if(retries && retries > maxRetries) {
              mysqlError(err);
              res.status(500).end(jadeGen['500.jade']({debugInfo: config.debug ? util.inspect(err, { showHidden: true, depth: 5 }) : null}));
              return;
            }
            return setTimeout(getPermissions, 100, req, res, next, retries ? retries + 1 : 1);
          }
          for (i = rows.length - 1; i >= 0; i--) {
            rows[i] = rows[i].permissions_id;
          }
          req.permissions = rows;
          next();
        }
      );
    });
  }
}


/*
exports.getAccountByUser = function(user, callback) {
  accounts.findOne({_id:user}, function(e, o) { callback(e, o); });
};

/* record insertion, update & deletion methods */
/*
exports.addNewAccount = function(prefix, newData, locked, callback) {
  accounts.findOne({_id:prefix+'-'+newData.user}, function(e, o) {
    if(o) {
      return callback('username-taken');
    }
    accounts.findOne({$or: [{email: newData.email}, {privateEmail: newData.email}]}, function(e, o) {
      if(o) {
         return callback('email-taken');
      }
      newData.locked = locked;<commit_msg>For some reason express didn't run getPermissions. This is fixed.<commit_after>
/**
 *
 * Copyright 2015 Landstinget Dalarna Bibliotek och Informationscentral
 * Copyright 2015 <NAME> (@emilhem)
 *
 *
 * This file is part of Aaron.
 *
 * Aaron is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Aaron is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Aaron.  If not, see <http://www.gnu.org/licenses/>.
 *
 */


/**
 *
 * TODO: Make sure that a user can't be created as a number.
 * Test this by passing their username to isNaN(val) and make sure it's true.
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
 *
 */


'use strict';

var util    = require('util');

var jadeGen = require('../lib/jadeGenerator.js');

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

var maxRetries = 5;

var pool = {
  getConnection: function() {
    throw 'pool is not set!';
  }
};

var mysql_selectUser = [
  'SELECT user_id, user_legacyUsername, user_firstName, user_lastName, user_workplace, user_place, user_email, user_pemail, user_phonenumber, user_password, user_admin, user_activated',
  'FROM users',
  'WHERE ?? = ?;'
].join('\n');

var mysql_legacyToUserId = [
  'SELECT user_id',
  'FROM users',
  'WHERE user_legacyUsername = ?;'
].join('\n');

function setPool(newPool) {
  pool = newPool;
}

function mysqlError(err, callback) {
  console.error(err);
  if(callback) {
    callback('mysql-error', null);
  }
}

function legacyToID(user, callback, retries) {
  if(typeof user !== 'string' && typeof user !== 'number') {
    return callback('invalid-user-param');
  }
  pool.getConnection(function(err, connection) {
    if(err) {
      connection.release();
      if(retries && retries > maxRetries) {
        return mysqlError(err, callback);
      }
      return setTimeout(legacyToID, 100, user, callback, retries ? retries + 1 : 1);
    }
    connection.query(mysql_legacyToUserId, [user], function(err, rows) {
      connection.release();
      if(err) { // for connection releasing reasons, don't copy this one.
        if(retries && retries > maxRetries) {
          return mysqlError(err, callback);
        }
        return setTimeout(legacyToID, 100, user, callback, retries ? retries + 1 : 1);
      }
      callback(null, rows[0].user_id);
    });
  });
}

function getUser(user, callback, retries) {
  if(typeof user !== 'string' && typeof user !== 'number') {
    return callback('invalid-user-param');
  }
  pool.getConnection(function(err, connection) {
    if(err) {
      connection.release();
      if(retries && retries > maxRetries) {
        return mysqlError(err, callback);
      }
      return setTimeout(getUser, 100, user, callback, retries ? retries + 1 : 1);
    }
    connection.query(mysql_selectUser, [typeof user === 'string' ? 'user_legacyUsername' : 'user_id', user], function(err, data) {
      connection.release();
      if(err) { // for connection releasing reasons, don't copy this one.
        if(retries && retries > maxRetries) {
          return mysqlError(err, callback);
        }
        return setTimeout(getUser, 100, user, callback, retries ? retries + 1 : 1);
      }
      callback(null, data);
    });
  });
}

var mysql_getPermissions = [
  'SELECT permission_id',
  'FROM users u',
  'LEFT JOIN users_has_groups ug ON u.user_id = ug.users_user_id',
  'LEFT JOIN groups g ON g.group_id = ug.groups_group_id',
  'LEFT JOIN groups_has_permissions gp ON g.group_id = gp.groups_group_id',
  'LEFT JOIN permissions p ON p.permission_id = gp.permissions_permission_id',
  'LEFT JOIN permissions_has_applications pa ON p.permission_id = pa.permissions_permission_id',
  'LEFT JOIN applications a ON a.application_shortname = pa.applications_application_shortname',
  'WHERE user_email = ?',
  'AND a.application_shortname = ?;'
].join('\n');

function getPermissions (req, res, next) {
  var retries = -1;
  function run() {
    retries++;
    if(req.loggedIn) {
      pool.getConnection(function(err, connection) {
        if(err) {
          connection.release();
          if(retries && retries > maxRetries) {
            mysqlError(err);
            res.status(500).end(jadeGen['500.jade']({debugInfo: config.debug ? util.inspect(err, { showHidden: true, depth: 5 }) : null}));
            return;
          }
          return setTimeout(run, 100);
        }
        connection.query(
          mysql_getPermissions,
          [req.authUser, 'aaron'],
          function(err, rows) {
            var i;
            connection.release();
            if(err) {
              if(retries && retries > maxRetries) {
                mysqlError(err);
                res.status(500).end(jadeGen['500.jade']({debugInfo: config.debug ? util.inspect(err, { showHidden: true, depth: 5 }) : null}));
                return;
              }
              return setTimeout(run, 100);
            }
            for (i = rows.length - 1; i >= 0; i--) {
              rows[i] = rows[i].permission_id;
            }
            console.log('check perms');
            console.log(rows);
            req.permissions = rows;
            next();
          }
        );
      });
    }
  }
  run();
}


/*
exports.getAccountByUser = function(user, callback) {
  accounts.findOne({_id:user}, function(e, o) { callback(e, o); });
};

/* record insertion, update & deletion methods */
/*
exports.addNewAccount = function(prefix, newData, locked, callback) {
  accounts.findOne({_id:prefix+'-'+newData.user}, function(e, o) {
    if(o) {
      return callback('username-taken');
    }
    accounts.findOne({$or: [{email: newData.email}, {privateEmail: newData.email}]}, function(e, o) {
      if(o) {
         return callback('email-taken');
      }
      newData.locked = locked;
{'fraction_non_alphanumeric': 0.13337130767352917, 'fraction_numerical': 0.009032468060867443, 'mean_word_length': 2.9504982320797173, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 21, 'https://': 2, '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': '7518653', 'n_tokens_mistral': 3916, 'n_tokens_neox': 3789, 'n_words': 1009}