#ifndef _WIN32 #include "AuthSessionManager.h" #include "lib/utils/datetime.h" #include "lib/utils/crypto/KeyCodeHelper.h" #include "lib/utils/crypto/CryptoInit.h" #include "lib/utils/crypto/PrivateKey.h" #include "lib/utils/crypto/PublicKey.h" #include "lib/logging/logging.h" #include "lib/utils/bts_assert.h" #include "lib/utils/helper_macros.h" #include "lib/config/config.h" #include "lib/config/protos/Ports.pb.h" #include "lib/config/protos/keycode.pb.h" #include #include #include #include //ip/port stuff #include #include #include #include namespace bts { namespace api { namespace auth { const std::string AuthSessionManager::PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAseguRgLD88QdhK0agy8f" "gz3SXp/hmp377+Q+z3OQqGG5kWyKnQfkAQDFeSv8o1iwSQupN0D1QOXyDnV1jmue" "rqTitasGeq4AwKLhY89O/VuXc+URAO+HZ7EqVWfb3Nv4EOZRiiVsxmVBkld73Rcy" "UAS4OXh4jDtE8IzOoXB7HhlMPBIAkueqdyy/v9zamzKrxPzWd+IW/IYEdCrUS8ES" "mxOkeadSHVeH2nlHVREdktE3wKRd3fZ3OkyGaHnUPxBoUW1Ex57BpwdMGUqLZ3W2" "92yQa/32dsLocoTri4iiImvQ/0JvfhnY9MDTZnmIgb8bPWSvPblQN0RR9OkRDFT9" "3QIDAQAB" "\n-----END PUBLIC KEY-----\n"; AuthSessionManager::AuthSessionManager() : _map(), _nusers(), _expiration() { const auto& ekc = config::get(); auto pub = bts::crypto::PublicKey::read_string(PUBLIC_KEY); bts::config::KeyCode kc; auto valid = bts::crypto::decrypt_keycode(*pub, ekc, &kc); bts_assert_msg(valid, "Your BTS Keycode is invalid"); _nusers = kc.nusers(); _expiration = kc.expiration(); bts_assert_msg(validate_ip_port(kc), "invalid ip or port in keycode"); } bool AuthSessionManager::validate_ip_port(const bts::config::KeyCode& kc) { bool portgood = true; if(kc.has_port() && kc.port() != "") { const auto& ports = config::get(); portgood = std::to_string(ports.config_port()) == kc.port(); } bool ipgood = true; if(kc.has_ip() && kc.ip() != "") { auto ipmap = bts::os::host_ips(); for(const auto& x: ipmap) { if(x.second == kc.ip()) { ipgood = true; break; } else ipgood = false; } } return portgood && ipgood; } bool AuthSessionManager::add_or_replace_session(const api::user::TokenPayload& tok) { if(tok.wheel()) return true; if(datetime::ll_diff_in_us(datetime::ll_now(), _expiration) < 0) { LOG(Gen,Error, "Your BTS Keycode is expired!"); return false; } auto it = _map.find(tok.id()); if(it != _map.end()) { _map[tok.id()] = Session{tok}; return true; } else if(_map.size() < _nusers) { _map[tok.id()] = Session{tok}; return true; } return false; } bool AuthSessionManager::check_session(const api::user::TokenPayload& tok) { if(tok.wheel()) return true; if(datetime::ll_diff_in_us(datetime::ll_now(), _expiration) > 0) { auto it = _map.find(tok.id()); if(it != _map.end()) { //return google::protobuf::util::MessageDifferencer::Equivalent(tok, it->second.token) //this is probably slow return tok.date() == it->second.token.date() && //ids are equal datetime::ll_diff_in_us(tok.date(), _expiration) > 0; } } return false; } }}} #endif