<commit_before>var API = module.exports = exports;
var Whisk = undefined;

// init

API.init = function (attr) {
  Whisk = attr.whisk; // whisk instance
}


/* 
  session sync protocol (between the web app and the ws connection)

  NOTE: this function is used to connect the web session to the ws session.
    start_ws_session_sync() should be called from the web service, then
    within WS_SESSION_SYNC_TIMEOUT seconds, confirm_ws_session_sync() should be called
*/

const WS_SESSION_SYNC_TIMEOUT_c = 10;


// get sid from web req

API.get_sid_from_web_req = function get_sid_from_web_req (req) {

  //console.log('Whisk.Auth cookies: ', req.cookies);
  if (!req.cookies[Whisk.Redis.session.key()]) {
    console.error("Whisk.Auth.get_sid_from_web_req: the sid was not found via req.cookies." + Whisk.Redis.session.key() + "!");
  }

  // some clients fail to store session, this is a fallback
  var sid = req.cookies[Whisk.Redis.session.key()] ? req.cookies[Whisk.Redis.session.key()] : req.sessionID;

  return [Whisk.Redis.session.prefix(), sid].join("")
}


// get sid from web req cookies
// NOTE: will be deprecated, replace with get_sid_from_web_req

API.get_sid_from_web_req_cookies = function get_sid_from_web_req_cookies (cookies) {
  
  console.log('Whisk.Auth.get_sid_from_web_req_cookies will be deprecated! Use Whisk.Auth.get_sid_from_web_req instead.');
  
  //console.log('Whisk.Auth cookies: ', cookies);
  if (!cookies[Whisk.Redis.session.key()]) {
    console.error("Whisk.Auth.get_sid_from_web_req_cookies: the sid was not found via cookies." + Whisk.Redis.session.key() + "!");
  }

  return [Whisk.Redis.session.prefix(), cookies[Whisk.Redis.session.key()]].join("")
}


// get cipher address from ws

API.get_cipher_address_from_ws = function get_cipher_address_from_ws (attr) {

  /* attrs:
    socket
  */
  
  var cipher_address = Whisk.Cipher.getInstance().getAddress();

  return {
    ns: cipher_address.ns,
    nid: cipher_address.nid,
    tid: attr.socket.id,
  };

}


/*
  get session
  
  Notes:
  - requires sid, socket_id, or user_id
  - use whisk.Auth.get_sid_from_web_req(req) to get the sid
  - returns a rapt-modelrizerly obj containing session data

*/

API.get_session = function (attr, cb) {

  /* attrs:
      sid - whisk session id
      socket_id - socket.io socket id
      user_id - implementation user id (must be be unique)
  */

  // get session using the whisk sid
  if (attr.sid) {

    Whisk.Models.Session({ sid: attr.sid }).read(null, function(err, session) { 
      if (err) {
        console.error("Whisk.Auth.get_session: Whisk.Models.Session could not read the session with sid! " + err);
        return cb(err);
      } 
      
      return cb(null, session);
      
    }); 
  
  // get session using user_id
  } else if (attr.user_id || attr.socket_id)  {

    var session_client;

    // loop over all clients in the websocket service
    var client_ids = Object.keys(Whisk.Config.io_instance().engine.clients); // all client ids
    client_ids.forEach(function (client_id, idx) { // (aside) engine client id should match the socket id

      var client = Whisk.Config.io_instance().engine.clients[client_id];
      
      // matched session client via socket_id
      if (attr.socket_id) {
        //console.log(attr.socket_id + '==' + client.id);
        if (client && client_id == attr.socket_id) session_client = client;
      
      // matched session client via user_id
      } else if (attr.user_id) {
        //console.log(attr.user_id + '==' + client.whisk_user_id);
        if (client && client.whisk_user_id == attr.user_id) session_client = client;
      }

    });

    if (session_client) {
      Whisk.Models.Session({ sid: session_client.whisk_sid }).read(null, function(err, session) { 
        if (err) {
          console.error("Whisk.Auth.get_session: Whisk.Models.Session could not read the session with socket_id or user_id! " + err);
          return cb(err);
        } 
        if (!session) {
          err = "Whisk.Auth.get_session: Whisk.Models.Session could not find the session with socket_id or user_id!";
          console.error(err);
          return cb(err);
        }            
        return cb(null, session);
        
      }); 
    } else {
      var err = "Whisk.Auth.get_session: Could not find session!";
      console.error(err);
      return cb(err);

    }

  // not yet implemented
  } else {

    var err = "Whisk.Auth.get_session: Finding session with that attribute not implemented!";
    console.error(err);
    return cb(err);

  }

}



/*
  get websocket sessions
  
  Notes:
  - requires active Whisk.Config.io_instance()

*/

API.get_websocket_sessions = function (attr, cb) {

  /* attrs:
  */

  console.log("Whisk.Auth.get_websocket_sessions");

  Whisk.Models.Session().find({}, {}, function(err, sessions) {
    if (err) {
      var err = "Whisk.Auth.get_websocket_sessions: Could not find sessions: " + err;
      console.error(err);
      return cb(err);
    }
    
    if (!sessions) {
      var err = "Whisk.Auth.get_websocket_sessions: Could not find any sessions!";
      console.error(err);
      return cb(err);<commit_msg>Continued work on post-1.0 socket.io and the chat-room example app. Improved Whisk.Auth.get_session, it now accepts user_id and socket_id. Added Whisk.Auth.get_websocket_sessions to allow the retrieval of active session data for all websocket clients.<commit_after>var API = module.exports = exports;
var Whisk = undefined;

// init

API.init = function (attr) {
  Whisk = attr.whisk; // whisk instance
}


/* 
  session sync protocol (between the web app and the ws connection)

  NOTE: this function is used to connect the web session to the ws session.
    start_ws_session_sync() should be called from the web service, then
    within WS_SESSION_SYNC_TIMEOUT seconds, confirm_ws_session_sync() should be called
*/

const WS_SESSION_SYNC_TIMEOUT_c = 10;


// get sid from web req

API.get_sid_from_web_req = function get_sid_from_web_req (req) {

  //console.log('Whisk.Auth cookies: ', req.cookies);
  if (!req.cookies[Whisk.Redis.session.key()]) {
    console.error("Whisk.Auth.get_sid_from_web_req: the sid was not found via req.cookies." + Whisk.Redis.session.key() + "!");
  }

  // some clients fail to store session, this is a fallback
  var sid = req.cookies[Whisk.Redis.session.key()] ? req.cookies[Whisk.Redis.session.key()] : req.sessionID;

  return [Whisk.Redis.session.prefix(), sid].join("")
}


// get sid from web req cookies
// NOTE: will be deprecated, replace with get_sid_from_web_req

API.get_sid_from_web_req_cookies = function get_sid_from_web_req_cookies (cookies) {
  
  console.log('Whisk.Auth.get_sid_from_web_req_cookies will be deprecated! Use Whisk.Auth.get_sid_from_web_req instead.');
  
  //console.log('Whisk.Auth cookies: ', cookies);
  if (!cookies[Whisk.Redis.session.key()]) {
    console.error("Whisk.Auth.get_sid_from_web_req_cookies: the sid was not found via cookies." + Whisk.Redis.session.key() + "!");
  }

  return [Whisk.Redis.session.prefix(), cookies[Whisk.Redis.session.key()]].join("")
}


// get cipher address from ws

API.get_cipher_address_from_ws = function get_cipher_address_from_ws (attr) {

  /* attrs:
    socket
  */
  
  var cipher_address = Whisk.Cipher.getInstance().getAddress();

  return {
    ns: cipher_address.ns,
    nid: cipher_address.nid,
    tid: attr.socket.id,
  };

}


/*
  get session
  
  Notes:
  - requires sid, socket_id, or user_id
  - use whisk.Auth.get_sid_from_web_req(req) to get the sid
  - returns a rapt-modelrizerly obj containing session data

*/

API.get_session = function (attr, cb) {

  /* attrs:
      sid - whisk session id
      socket_id - socket.io socket id
      user_id - implementation user id (must be be unique)
  */

  // get session using the whisk sid
  if (attr.sid) {

    Whisk.Models.Session({ sid: attr.sid }).read(null, function(err, session) { 
      if (err) {
        console.error("Whisk.Auth.get_session: Whisk.Models.Session could not read the session with sid! " + err);
        return cb(err);
      } 
      
      return cb(null, session);
      
    }); 
  
  // get session using user_id
  } else if (attr.user_id || attr.socket_id)  {

    var session_client;

    // loop over all clients in the websocket service
    var client_ids = Object.keys(Whisk.Config.io_instance().engine.clients); // all client ids
    client_ids.forEach(function (client_id, idx) { // (aside) engine client id should match the socket id

      var client = Whisk.Config.io_instance().engine.clients[client_id];
      
      // matched session client via socket_id
      if (attr.socket_id) {
        //console.log(attr.socket_id + '==' + client.id);
        if (client && client_id == attr.socket_id) session_client = client;
      
      // matched session client via user_id
      } else if (attr.user_id) {
        //console.log(attr.user_id + '==' + client.whisk_user_id);
        if (client && client.whisk_user_id == attr.user_id) session_client = client;
      }

    });

    if (session_client) {
      Whisk.Models.Session({ sid: session_client.whisk_sid }).read(null, function(err, session) { 
        if (err) {
          console.error("Whisk.Auth.get_session: Whisk.Models.Session could not read the session with socket_id or user_id! " + err);
          return cb(err);
        } 
        if (!session) {
          err = "Whisk.Auth.get_session: Whisk.Models.Session could not find the session with socket_id or user_id!";
          console.error(err);
          return cb(err);
        }            
        return cb(null, session);
        
      }); 
    } else {
      var err = "Whisk.Auth.get_session: Could not find session!";
      console.error(err);
      return cb(err);

    }

  // not yet implemented
  } else {

    var err = "Whisk.Auth.get_session: Finding session with that attribute not implemented!";
    console.error(err);
    return cb(err);

  }

}



/*
  get websocket sessions
  
  Notes:
  - requires active Whisk.Config.io_instance()

*/

API.get_websocket_sessions = function (attr, cb) {

  /* attrs:
  */

  //console.log("Whisk.Auth.get_websocket_sessions");

  Whisk.Models.Session().find({}, {}, function(err, sessions) {
    if (err) {
      var err = "Whisk.Auth.get_websocket_sessions: Could not find sessions: " + err;
      console.error(err);
      return cb(err);
    }
    
    if (!sessions) {
      var err = "Whisk.Auth.get_websocket_sessions: Could not find any sessions!";
      console.error(err);
      return cb(err);
{'fraction_non_alphanumeric': 0.12087912087912088, 'fraction_numerical': 0.0005683971201212581, 'mean_word_length': 2.9172541743970317, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '4955448', 'n_tokens_mistral': 3542, 'n_tokens_neox': 3440, 'n_words': 868}