Reverted webAPI and converted auth to old version

This commit is contained in:
seefo
2018-04-15 10:22:16 -04:00
parent 2635dd00f3
commit fbf2b0ca93
5 changed files with 252 additions and 538 deletions
@@ -126,8 +126,6 @@
#include "webAPI.h"
using namespace StellaBellum;
namespace CentralServerNamespace
{
bool gs_connectionServersPublic=false;
@@ -2941,7 +2939,7 @@ void CentralServer::sendPopulationUpdateToLoginServer()
void CentralServer::sendMetricsToWebAPI()
{
static const std::string metricsURL(ConfigCentralServer::getMetricsDataURL());
/*static const std::string metricsURL(ConfigCentralServer::getMetricsDataURL());
if (!metricsURL.empty())
{
@@ -2979,7 +2977,7 @@ void CentralServer::sendMetricsToWebAPI()
#else
api.submit();
#endif
}
}*/
}
//-----------------------------------------------------------------------
@@ -56,8 +56,6 @@
#include "webAPI.h"
using namespace StellaBellum;
//-----------------------------------------------------------------------
namespace ClientConnectionNamespace {
@@ -269,137 +267,91 @@ void ClientConnection::handleGameServerForLoginMessage(uint32 serverId) {
* to be validated. Central will reply with a list of permissions.
* @see onIdValidated
*/
void ClientConnection::handleClientIdMessage(const ClientIdMsg &msg) {
//Only check clients that have not been validated.
if (m_hasBeenValidated) {
return;
}
void ClientConnection::handleClientIdMessage(const ClientIdMsg& msg)
{
//Only check clients that have not been validated.
if (m_hasBeenValidated)
return;
DEBUG_FATAL(m_hasSelectedCharacter, ("Trying to validate a client who already has a character selected.\n"));
bool result = false;
m_gameBitsToClear = msg.getGameBitsToClear();
DEBUG_FATAL(m_hasSelectedCharacter, ("Trying to validate a client who already has a character selected.\n"));
bool result = false;
char sessionId[apiSessionIdWidth];
if (msg.getTokenSize() > 0) {
Archive::ByteStream t(msg.getToken(), msg.getTokenSize());
Archive::ReadIterator ri(t);
KeyShare::Token token(ri);
char sessionId[apiSessionIdWidth];
m_gameBitsToClear = msg.getGameBitsToClear();
if (!ConfigConnectionServer::getValidateStationKey()) {
// get SUID from token
result = ConnectionServer::decryptToken(token, m_suid, m_isSecure, m_accountName);
} else {
result = ConnectionServer::decryptToken(token, sessionId, m_requestedSuid);
}
if(msg.getTokenSize() > 0)
{
Archive::ByteStream t(msg.getToken(), msg.getTokenSize());
Archive::ReadIterator ri(t);
KeyShare::Token token(ri);
static const std::string sessURL(ConfigConnectionServer::getSessionURL());
if (!ConfigConnectionServer::getValidateStationKey())
{
// get SUID from token
result = ConnectionServer::decryptToken(token, m_suid, m_isSecure, m_accountName);
}
else
{
result = ConnectionServer::decryptToken(token, sessionId, m_requestedSuid);
}
if (result || strlen(sessionId) != 0) {
if (ConfigConnectionServer::getValidateStationKey()) {
bool cont = false;
StationId apiSuid = 0;
static const std::string loginTrace("TRACE_LOGIN");
LOG(loginTrace, ("ClientConnection SUID = %d", m_suid));
FATAL(sessURL.empty(), ("Session URL is empty in connection server."));
}
if (result)
{
// verify version
if (ConfigConnectionServer::getValidateClientVersion() && msg.getVersion() != GameNetworkMessage::NetworkVersionId)
{
std::string strSessionId(sessionId, apiSessionIdWidth);
strSessionId += '\0';
const std::string clientIP(getRemoteAddress());
const std::string sess(sessionId);
const int bufferSize = 255 + apiSessionIdWidth;
char * buffer = new char[bufferSize];
snprintf(buffer, bufferSize-1, "network version mismatch: got (ip=[%s], sessionId=[%s], version=[%s]), required (version=[%s])", getRemoteAddress().c_str(), strSessionId.c_str(), msg.getVersion().c_str(), GameNetworkMessage::NetworkVersionId.c_str());
buffer[bufferSize-1] = '\0';
FATAL(clientIP.empty(), ("Remote IP is empty"));
ConnectionServer::dropClient(this, std::string(buffer));
disconnect();
DEBUG_WARNING(true, ("ConnectionServer::handleClientIdMessage - For ip %s suid is %lu requestedSUID is %lu and session is %s", clientIP.c_str(), m_suid, m_requestedSuid, sess.c_str()));
delete[] buffer;
webAPI api(sessURL);
return;
}
// add our data
api.addJsonData<std::string>("session_key", sess);
if (api.submit()) {
bool status = api.getNullableValue<bool>("status");
if (status) {
std::string apiUser = api.getString("user_name");
std::string apiIP = api.getString("ip");
int expired = api.getNullableValue<int>("expired");
if (!ConfigConnectionServer::getUseOldSuidGenerator()) {
apiSuid = api.getNullableValue<int>("user_id");
} else {
if (apiUser.length() > MAX_ACCOUNT_NAME_LENGTH) {
apiUser.resize(MAX_ACCOUNT_NAME_LENGTH);
}
apiSuid = std::hash < std::string > {}(apiUser.c_str());
}
if (apiIP == clientIP && expired == 0) {
m_suid = apiSuid;
cont = true;
}
}
}
if (!cont) {
LOG("ClientDisconnect", ("SUID %d (%d) passed a bad token to the connections erver. Disconnecting.", m_suid, apiSuid));
disconnect();
return;
}
}
static const std::string loginTrace("TRACE_LOGIN");
LOG(loginTrace, ("ClientConnection SUID = %d", m_suid));
//check for duplicate login
ClientConnection *oldConnection = ConnectionServer::getClientConnection(m_suid);
if (oldConnection) {
//There is already someone connected to this cluster with this suid.
LOG("Network", ("SUID %d already logged in, disconnecting client.\n", m_suid));
ConnectionServer::dropClient(oldConnection, "Already Connected");
disconnect();
return;
}
// verify version
if (ConfigConnectionServer::getValidateClientVersion() &&
msg.getVersion() != GameNetworkMessage::NetworkVersionId) {
std::string strSessionId(sessionId, apiSessionIdWidth);
strSessionId += '\0';
const int bufferSize = 255 + apiSessionIdWidth;
char *buffer = new char[bufferSize];
snprintf(buffer, bufferSize -
1, "network version mismatch: got (ip=[%s], sessionId=[%s], version=[%s]), required (version=[%s])", getRemoteAddress().c_str(), strSessionId.c_str(), msg.getVersion().c_str(), GameNetworkMessage::NetworkVersionId.c_str());
buffer[bufferSize - 1] = '\0';
ConnectionServer::dropClient(this, std::string(buffer));
disconnect();
delete[] buffer;
return;
}
// test mode only
if (!m_suid && !ConfigConnectionServer::getValidateStationKey()) {
WARNING(true, ("Generating suid from username. This is not safe or secure."));
m_suid = atoi(m_accountName.c_str());
if (m_suid == 0) {
m_suid = std::hash < std::string > {}(m_accountName.c_str());
}
}
onValidateClient(m_suid, m_accountName, m_isSecure, nullptr, ConfigConnectionServer::getDefaultGameFeatures(), ConfigConnectionServer::getDefaultSubscriptionFeatures(), 0, 0, 0, 0, ConfigConnectionServer::getFakeBuddyPoints());
}
} else {
WARNING(true, ("SUID %d passed a bad token to the connections server (cache issue or hacker?). Disconnecting.", m_suid));
// They sent us a token that was no good -- either a hack attempt, or
// possibly it was just too old.
LOG("ClientDisconnect", ("SUID %d passed a bad token to the connections server (cache issue or hacker?). Disconnecting.", m_suid));
disconnect();
}
if (ConfigConnectionServer::getValidateStationKey())
{
SessionApiClient * session = ConnectionServer::getSessionApiClient();
NOT_NULL(session);
if(session)
{
session->validateClient(this, sessionId);
}
else
{
ConnectionServer::dropClient(this, "SessionApiClient is not available!");
disconnect();
}
}
else
{
m_suid = atoi(m_accountName.c_str());
if (m_suid == 0)
{
std::hash<std::string> h;
m_suid = h(m_accountName.c_str());
}
onValidateClient(m_suid, m_accountName, m_isSecure, nullptr, ConfigConnectionServer::getDefaultGameFeatures(), ConfigConnectionServer::getDefaultSubscriptionFeatures(), 0, 0, 0, 0, ConfigConnectionServer::getFakeBuddyPoints());
}
}
else
{
// They sent us a token that was no good -- either a hack attempt, or
// possibly it was just too old.
LOG("ClientDisconnect", ("SUID %d passed a bad token to the connections erver. Disconnecting.", m_suid));
disconnect();
}
}
//-----------------------------------------------------------------------
@@ -23,8 +23,6 @@
#include "webAPI.h"
using namespace StellaBellum;
//-----------------------------------------------------------------------
ClientConnection::ClientConnection(UdpConnectionMT *u, TcpClient *t)
@@ -150,127 +148,64 @@ void ClientConnection::onReceive(const Archive::ByteStream &message) {
//-----------------------------------------------------------------------
// originally was used to validate station API credentials, now uses our custom api
void ClientConnection::validateClient(const std::string &id, const std::string &key) {
bool authOK = false;
bool testMode = false;
static const std::string authURL(ConfigLoginServer::getExternalAuthUrl());
void ClientConnection::validateClient(const std::string & id, const std::string & key)
{
// to avoid having to re-type this stupid var all over the place
// ideally we wouldn't copy this here, but it would be a huge pain
const std::string trimmedId = trim(id);
const std::string trimmedKey = trim(key);
std::string uname;
std::string parentAccount;
std::string sessionID;
// and to avoid funny business with atoi and casing
// make it a separate var than the one we send the auth server
std::string lcaseId;
lcaseId.resize(trimmedId.size());
StationId user_id;
StationId parent_id;
std::unordered_map<int, std::string> childAccounts;
std::transform(trimmedId.begin(),trimmedId.end(),lcaseId.begin(),::tolower);
if (!authURL.empty()) {
// create the object
webAPI api(authURL);
StationId suid = atoi(lcaseId.c_str());
int authOK = 0;
// add our data
api.addJsonData<std::string>("user_name", id);
api.addJsonData<std::string>("user_password", key);
api.addJsonData<std::string>("ip", getRemoteAddress());
if (suid == 0)
{
std::hash<std::string> h;
suid = h(lcaseId.c_str()); //lint !e603 // Symbol 'h' not initialized (it's a functor)
}
LOG("LoginClientConnection", ("validateClient() for stationId (%lu) at IP (%s), id (%s)", m_stationId, getRemoteAddress().c_str(), lcaseId.c_str()));
if (api.submit()) {
bool status = api.getNullableValue<bool>("status");
uname = api.getString("username");
sessionID = api.getString("session_key");
std::string authURL(ConfigLoginServer::getExternalAuthUrl());
if (status && !sessionID.empty() && !uname.empty()) {
authOK = true;
if (!authURL.empty())
{
std::ostringstream postBuf;
postBuf << "user_name=" << trimmedId << "&user_password=" << trimmedKey << "&stationID=" << suid << "&ip=" << getRemoteAddress();
parentAccount = api.getString("mainAccount");
childAccounts = api.getStringMap("subAccounts");
std::string response = webAPI::simplePost(authURL, std::string(postBuf.str()), "");
if (!ConfigLoginServer::getUseOldSuidGenerator()) {
user_id = static_cast<StationId>(api.getNullableValue<int>("user_id"));
parent_id = static_cast<StationId>(api.getNullableValue<int>("parent_id"));
} else {
if (parentAccount.length() > MAX_ACCOUNT_NAME_LENGTH) {
parentAccount.resize(MAX_ACCOUNT_NAME_LENGTH);
}
if (response == "success")
{
authOK = 1;
}
else
{
ErrorMessage err("Login Failed", response);
this->send(err, true);
}
}
else
{
authOK = 1;
}
if (uname.length() > MAX_ACCOUNT_NAME_LENGTH) {
uname.resize(MAX_ACCOUNT_NAME_LENGTH);
}
parent_id = std::hash < std::string > {}(parentAccount.c_str());
user_id = std::hash < std::string > {}(uname.c_str());
}
} else {
std::string msg(api.getString("message"));
if (msg.empty()) {
msg = "Invalid username or password.";
}
ErrorMessage err("Login Failed", msg);
this->send(err, true);
}
} else {
ErrorMessage err("Login Failed", "Could not connect to remote.");
this->send(err, true);
}
} else {
// test mode
authOK = true;
testMode = true;
uname = id;
if (uname.length() > MAX_ACCOUNT_NAME_LENGTH) {
uname.resize(MAX_ACCOUNT_NAME_LENGTH);
}
user_id = std::hash < std::string > {}(uname.c_str());
}
if (authOK) {
m_stationId = user_id;
if (!testMode) {
REPORT_LOG(true, ("Client connected. Username: %s (%i) \n", uname.c_str(), user_id));
if (!parentAccount.empty()) {
if (parentAccount != uname) {
REPORT_LOG(true, ("\t%s's parent is %s (%i) \n", uname.c_str(), parentAccount.c_str(), parent_id));
}
} else {
parentAccount = "(Empty Parent!) " + uname;
}
for (auto i : childAccounts) {
StationId child_id = static_cast<StationId>(i.first);
std::string child(i.second);
if (!child.empty() && i.first > 0) {
if (ConfigLoginServer::getUseOldSuidGenerator()) {
if (child.length() > MAX_ACCOUNT_NAME_LENGTH) {
child.resize(MAX_ACCOUNT_NAME_LENGTH);
}
child_id = std::hash < std::string > {}(child.c_str());
}
REPORT_LOG((parent_id !=
child_id), ("\tchild of %s (%i) is %s (%i) \n", parentAccount.c_str(), parent_id, child.c_str(), child_id));
// insert all related accounts, if not already there, into the db
if (parent_id != child_id) {
DatabaseConnection::getInstance().upsertAccountRelationship(parent_id, child_id);
}
} else {
WARNING(true, ("Login API returned empty child account(s)."));
}
}
LoginServer::getInstance().onValidateClient(m_stationId, uname, this, true, sessionID.c_str(), 0xFFFFFFFF, 0xFFFFFFFF);
} else {
LoginServer::getInstance().onValidateClient(m_stationId, uname, this, true, nullptr, 0xFFFFFFFF, 0xFFFFFFFF);
}
LOG("LoginClientConnection", ("validateClient() for stationId (%i) at IP (%s), id (%s)", user_id, getRemoteAddress().c_str(), uname.c_str()));
}
if (authOK)
{
LoginServer::getInstance().onValidateClient(suid, lcaseId, this, true, NULL, 0xFFFFFFFF, 0xFFFFFFFF);
}
// else this case will never be reached, noop
}
// ----------------------------------------------------------------------------
/**