Moved the RegOnlyRequirement functions out of the Database interface into the proper Server block of code.

This commit is contained in:
woogerboy21 2015-08-08 16:24:37 -04:00
parent 129a6983ed
commit 17392f1ae5
7 changed files with 125 additions and 131 deletions

View file

@ -46,7 +46,7 @@ Server::Server(bool _threaded, QObject *parent)
qRegisterMetaType<GameEventContainer>("GameEventContainer");
qRegisterMetaType<IslMessage>("IslMessage");
qRegisterMetaType<Command_JoinGame>("Command_JoinGame");
connect(this, SIGNAL(sigSendIslMessage(IslMessage, int)), this, SLOT(doSendIslMessage(IslMessage, int)), Qt::QueuedConnection);
}
@ -62,9 +62,9 @@ void Server::prepareDestroy()
for (int i = 0; i < clients.size(); ++i)
QMetaObject::invokeMethod(clients.at(i), "prepareDestroy", Qt::QueuedConnection);
clientsLock.unlock();
bool done = false;
class SleeperThread : public QThread
{
public:
@ -83,7 +83,7 @@ void Server::prepareDestroy()
while (!clients.isEmpty())
clients.first()->prepareDestroy();
}
roomsLock.lockForWrite();
QMapIterator<int, Server_Room *> roomIterator(rooms);
while (roomIterator.hasNext())
@ -107,21 +107,21 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString
{
if (name.size() > 35)
name = name.left(35);
Server_DatabaseInterface *databaseInterface = getDatabaseInterface();
QWriteLocker locker(&clientsLock);
AuthenticationResult authState = databaseInterface->checkUserPassword(session, name, password, reasonStr, secondsLeft);
if (authState == NotLoggedIn || authState == UserIsBanned || authState == UsernameInvalid || authState == UserIsInactive)
return authState;
ServerInfo_User data = databaseInterface->getUserData(name, true);
data.set_address(session->getAddress().toStdString());
name = QString::fromStdString(data.name()); // Compensate for case indifference
databaseInterface->lockSessionTables();
if (authState == PasswordRight) {
// verify that new session would not cause problems with older existing session
@ -133,8 +133,7 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString
} else if (authState == UnknownUser) {
// Change user name so that no two users have the same names,
// don't interfere with registered user names though.
bool requireReg = databaseInterface->getRequireRegistration();
if (requireReg) {
if (getRegOnlyServer()) {
qDebug("Login denied: registration required");
databaseInterface->unlockSessionTables();
return RegistrationRequired;
@ -147,18 +146,18 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString
name = tempName;
data.set_name(name.toStdString());
}
users.insert(name, session);
qDebug() << "Server::loginUser:" << session << "name=" << name;
data.set_session_id(databaseInterface->startSession(name, session->getAddress()));
data.set_session_id(databaseInterface->startSession(name, session->getAddress()));
databaseInterface->unlockSessionTables();
usersBySessionId.insert(data.session_id(), session);
qDebug() << "session id:" << data.session_id();
session->setUserInfo(data);
Event_UserJoined event;
event.mutable_user_info()->CopyFrom(session->copyUserInfo(false));
SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
@ -166,10 +165,10 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString
if (clients[i]->getAcceptsUserListChanges())
clients[i]->sendProtocolItem(*se);
delete se;
event.mutable_user_info()->CopyFrom(session->copyUserInfo(true, true, true));
locker.unlock();
if (clientid.isEmpty()){
// client id is empty, either out dated client or client has been modified
if (getClientIdRequired())
@ -183,7 +182,7 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString
se = Server_ProtocolHandler::prepareSessionEvent(event);
sendIsl_SessionEvent(*se);
delete se;
return authState;
}
@ -208,7 +207,7 @@ QList<PlayerReference> Server::getPersistentPlayerReferences(const QString &user
Server_AbstractUserInterface *Server::findUser(const QString &userName) const
{
// Call this only with clientsLock set.
Server_AbstractUserInterface *userHandler = users.value(userName);
if (userHandler)
return userHandler;
@ -236,10 +235,10 @@ void Server::removeClient(Server_ProtocolHandler *client)
clients[i]->sendProtocolItem(*se);
sendIsl_SessionEvent(*se);
delete se;
users.remove(QString::fromStdString(data->name()));
qDebug() << "Server::removeClient: name=" << QString::fromStdString(data->name());
if (data->has_session_id()) {
const qint64 sessionId = data->session_id();
usersBySessionId.remove(sessionId);
@ -254,21 +253,21 @@ void Server::externalUserJoined(const ServerInfo_User &userInfo)
{
// This function is always called from the main thread via signal/slot.
clientsLock.lockForWrite();
Server_RemoteUserInterface *newUser = new Server_RemoteUserInterface(this, ServerInfo_User_Container(userInfo));
externalUsers.insert(QString::fromStdString(userInfo.name()), newUser);
externalUsersBySessionId.insert(userInfo.session_id(), newUser);
Event_UserJoined event;
event.mutable_user_info()->CopyFrom(userInfo);
SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
for (int i = 0; i < clients.size(); ++i)
if (clients[i]->getAcceptsUserListChanges())
clients[i]->sendProtocolItem(*se);
delete se;
clientsLock.unlock();
ResponseContainer rc(-1);
newUser->joinPersistentGames(rc);
newUser->sendResponseContainer(rc, Response::RespNothing);
@ -277,12 +276,12 @@ void Server::externalUserJoined(const ServerInfo_User &userInfo)
void Server::externalUserLeft(const QString &userName)
{
// This function is always called from the main thread via signal/slot.
clientsLock.lockForWrite();
Server_AbstractUserInterface *user = externalUsers.take(userName);
externalUsersBySessionId.remove(user->getUserInfo()->session_id());
clientsLock.unlock();
QMap<int, QPair<int, int> > userGames(user->getGames());
QMapIterator<int, QPair<int, int> > userGamesIterator(userGames);
roomsLock.lockForRead();
@ -291,26 +290,26 @@ void Server::externalUserLeft(const QString &userName)
Server_Room *room = rooms.value(userGamesIterator.value().first);
if (!room)
continue;
QReadLocker roomGamesLocker(&room->gamesLock);
Server_Game *game = room->getGames().value(userGamesIterator.key());
if (!game)
continue;
QMutexLocker gameLocker(&game->gameMutex);
Server_Player *player = game->getPlayers().value(userGamesIterator.value().second);
if (!player)
continue;
player->disconnectClient();
}
roomsLock.unlock();
delete user;
Event_UserLeft event;
event.set_name(userName.toStdString());
SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
clientsLock.lockForRead();
for (int i = 0; i < clients.size(); ++i)
@ -324,7 +323,7 @@ void Server::externalRoomUserJoined(int roomId, const ServerInfo_User &userInfo)
{
// This function is always called from the main thread via signal/slot.
QReadLocker locker(&roomsLock);
Server_Room *room = rooms.value(roomId);
if (!room) {
qDebug() << "externalRoomUserJoined: room id=" << roomId << "not found";
@ -337,7 +336,7 @@ void Server::externalRoomUserLeft(int roomId, const QString &userName)
{
// This function is always called from the main thread via signal/slot.
QReadLocker locker(&roomsLock);
Server_Room *room = rooms.value(roomId);
if (!room) {
qDebug() << "externalRoomUserLeft: room id=" << roomId << "not found";
@ -350,7 +349,7 @@ void Server::externalRoomSay(int roomId, const QString &userName, const QString
{
// This function is always called from the main thread via signal/slot.
QReadLocker locker(&roomsLock);
Server_Room *room = rooms.value(roomId);
if (!room) {
qDebug() << "externalRoomSay: room id=" << roomId << "not found";
@ -365,7 +364,7 @@ void Server::externalRoomGameListChanged(int roomId, const ServerInfo_Game &game
{
// This function is always called from the main thread via signal/slot.
QReadLocker locker(&roomsLock);
Server_Room *room = rooms.value(roomId);
if (!room) {
qDebug() << "externalRoomGameListChanged: room id=" << roomId << "not found";
@ -377,11 +376,11 @@ void Server::externalRoomGameListChanged(int roomId, const ServerInfo_Game &game
void Server::externalJoinGameCommandReceived(const Command_JoinGame &cmd, int cmdId, int roomId, int serverId, qint64 sessionId)
{
// This function is always called from the main thread via signal/slot.
try {
QReadLocker roomsLocker(&roomsLock);
QReadLocker clientsLocker(&clientsLock);
Server_Room *room = rooms.value(roomId);
if (!room) {
qDebug() << "externalJoinGameCommandReceived: room id=" << roomId << "not found";
@ -392,7 +391,7 @@ void Server::externalJoinGameCommandReceived(const Command_JoinGame &cmd, int cm
qDebug() << "externalJoinGameCommandReceived: session id=" << sessionId << "not found";
throw Response::RespNotInRoom;
}
ResponseContainer responseContainer(cmdId);
Response::ResponseCode responseCode = room->processJoinGameCommand(cmd, responseContainer, userInterface);
userInterface->sendResponseContainer(responseContainer, responseCode);
@ -400,7 +399,7 @@ void Server::externalJoinGameCommandReceived(const Command_JoinGame &cmd, int cm
Response response;
response.set_cmd_id(cmdId);
response.set_response_code(code);
sendIsl_Response(response, serverId, sessionId);
}
}
@ -408,44 +407,44 @@ void Server::externalJoinGameCommandReceived(const Command_JoinGame &cmd, int cm
void Server::externalGameCommandContainerReceived(const CommandContainer &cont, int playerId, int serverId, qint64 sessionId)
{
// This function is always called from the main thread via signal/slot.
try {
ResponseContainer responseContainer(cont.cmd_id());
Response::ResponseCode finalResponseCode = Response::RespOk;
QReadLocker roomsLocker(&roomsLock);
Server_Room *room = rooms.value(cont.room_id());
if (!room) {
qDebug() << "externalGameCommandContainerReceived: room id=" << cont.room_id() << "not found";
throw Response::RespNotInRoom;
}
QReadLocker roomGamesLocker(&room->gamesLock);
Server_Game *game = room->getGames().value(cont.game_id());
if (!game) {
qDebug() << "externalGameCommandContainerReceived: game id=" << cont.game_id() << "not found";
throw Response::RespNotInRoom;
}
QMutexLocker gameLocker(&game->gameMutex);
Server_Player *player = game->getPlayers().value(playerId);
if (!player) {
qDebug() << "externalGameCommandContainerReceived: player id=" << playerId << "not found";
throw Response::RespNotInRoom;
}
GameEventStorage ges;
for (int i = cont.game_command_size() - 1; i >= 0; --i) {
const GameCommand &sc = cont.game_command(i);
qDebug() << "[ISL]" << QString::fromStdString(sc.ShortDebugString());
Response::ResponseCode resp = player->processGameCommand(sc, responseContainer, ges);
if (resp != Response::RespOk)
finalResponseCode = resp;
}
ges.sendToGame(game);
if (finalResponseCode != Response::RespNothing) {
player->playerMutex.lock();
player->getUserInterface()->sendResponseContainer(responseContainer, finalResponseCode);
@ -455,7 +454,7 @@ void Server::externalGameCommandContainerReceived(const CommandContainer &cont,
Response response;
response.set_cmd_id(cont.cmd_id());
response.set_response_code(code);
sendIsl_Response(response, serverId, sessionId);
}
}
@ -463,9 +462,9 @@ void Server::externalGameCommandContainerReceived(const CommandContainer &cont,
void Server::externalGameEventContainerReceived(const GameEventContainer &cont, qint64 sessionId)
{
// This function is always called from the main thread via signal/slot.
QReadLocker usersLocker(&clientsLock);
Server_ProtocolHandler *client = usersBySessionId.value(sessionId);
if (!client) {
qDebug() << "externalGameEventContainerReceived: session" << sessionId << "not found";
@ -477,9 +476,9 @@ void Server::externalGameEventContainerReceived(const GameEventContainer &cont,
void Server::externalResponseReceived(const Response &resp, qint64 sessionId)
{
// This function is always called from the main thread via signal/slot.
QReadLocker usersLocker(&clientsLock);
Server_ProtocolHandler *client = usersBySessionId.value(sessionId);
if (!client) {
qDebug() << "externalResponseReceived: session" << sessionId << "not found";
@ -491,10 +490,10 @@ void Server::externalResponseReceived(const Response &resp, qint64 sessionId)
void Server::broadcastRoomUpdate(const ServerInfo_Room &roomInfo, bool sendToIsl)
{
// This function is always called from the main thread via signal/slot.
Event_ListRooms event;
event.add_room_list()->CopyFrom(roomInfo);
SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
clientsLock.lockForRead();
@ -502,10 +501,10 @@ void Server::broadcastRoomUpdate(const ServerInfo_Room &roomInfo, bool sendToIsl
if (clients[i]->getAcceptsRoomListChanges())
clients[i]->sendProtocolItem(*se);
clientsLock.unlock();
if (sendToIsl)
sendIsl_SessionEvent(*se);
delete se;
}
@ -543,7 +542,7 @@ void Server::sendIsl_Response(const Response &item, int serverId, qint64 session
if (sessionId != -1)
msg.set_session_id(sessionId);
msg.mutable_response()->CopyFrom(item);
emit sigSendIslMessage(msg, serverId);
}
@ -554,7 +553,7 @@ void Server::sendIsl_SessionEvent(const SessionEvent &item, int serverId, qint64
if (sessionId != -1)
msg.set_session_id(sessionId);
msg.mutable_session_event()->CopyFrom(item);
emit sigSendIslMessage(msg, serverId);
}
@ -565,7 +564,7 @@ void Server::sendIsl_GameEventContainer(const GameEventContainer &item, int serv
if (sessionId != -1)
msg.set_session_id(sessionId);
msg.mutable_game_event_container()->CopyFrom(item);
emit sigSendIslMessage(msg, serverId);
}
@ -576,7 +575,7 @@ void Server::sendIsl_RoomEvent(const RoomEvent &item, int serverId, qint64 sessi
if (sessionId != -1)
msg.set_session_id(sessionId);
msg.mutable_room_event()->CopyFrom(item);
emit sigSendIslMessage(msg, serverId);
}
@ -586,11 +585,11 @@ void Server::sendIsl_GameCommand(const CommandContainer &item, int serverId, qin
msg.set_message_type(IslMessage::GAME_COMMAND_CONTAINER);
msg.set_session_id(sessionId);
msg.set_player_id(playerId);
CommandContainer *cont = msg.mutable_game_command();
cont->CopyFrom(item);
cont->set_room_id(roomId);
emit sigSendIslMessage(msg, serverId);
}
@ -599,10 +598,10 @@ void Server::sendIsl_RoomCommand(const CommandContainer &item, int serverId, qin
IslMessage msg;
msg.set_message_type(IslMessage::ROOM_COMMAND_CONTAINER);
msg.set_session_id(sessionId);
CommandContainer *cont = msg.mutable_room_command();
cont->CopyFrom(item);
cont->set_room_id(roomId);
emit sigSendIslMessage(msg, serverId);
}

View file

@ -57,6 +57,7 @@ public:
virtual bool getGameShouldPing() const { return false; }
virtual bool getClientIdRequired() const { return false; }
virtual bool getRegOnlyServer() const { return false; }
virtual int getPingClockInterval() const { return 0; }
virtual int getMaxGameInactivityTime() const { return 9999999; }
virtual int getMaxPlayerInactivityTime() const { return 9999999; }

View file

@ -62,8 +62,8 @@ method=none
; if the chosen authentication method is password, here you can define the password your users will use to log in
password=123456
; Accept only registered users? default is 0 (accept unregistered users)
regonly=0
; Accept only registered users? default is false (accept unregistered users)
regonly=false
[users]

View file

@ -143,7 +143,7 @@ bool Servatrice::initServer()
serverName = settingsCache->value("server/name", "My Cockatrice server").toString();
serverId = settingsCache->value("server/id", 0).toInt();
clientIdRequired = settingsCache->value("server/requireclientid",0).toBool();
bool regServerOnly = settingsCache->value("authentication/regonly", 0).toBool();
regServerOnly = settingsCache->value("authentication/regonly", 0).toBool();
const QString authenticationMethodStr = settingsCache->value("authentication/method").toString();
if (authenticationMethodStr == "sql") {
@ -161,7 +161,7 @@ bool Servatrice::initServer()
qDebug() << "Authenticating method: none";
authenticationMethod = AuthenticationNone;
}
qDebug() << "Client ID Required: " << clientIdRequired;
bool maxUserLimitEnabled = settingsCache->value("security/enable_max_user_limit", false).toBool();
qDebug() << "Maximum user limit enabled: " << maxUserLimitEnabled;
@ -174,7 +174,7 @@ bool Servatrice::initServer()
bool registrationEnabled = settingsCache->value("registration/enabled", false).toBool();
bool requireEmailForRegistration = settingsCache->value("registration/requireemail", true).toBool();
qDebug() << "Registration enabled: " << registrationEnabled;
qDebug() << "Registration enabled: " << regServerOnly;
if (registrationEnabled)
qDebug() << "Require email address to register: " << requireEmailForRegistration;

View file

@ -120,7 +120,7 @@ private:
QString shutdownReason;
int shutdownMinutes;
QTimer *shutdownTimer;
bool isFirstShutdownMessage, clientIdRequired;
bool isFirstShutdownMessage, clientIdRequired, regServerOnly;
mutable QMutex serverListMutex;
QList<ServerProperties> serverList;
@ -138,6 +138,7 @@ public:
QString getLoginMessage() const { QMutexLocker locker(&loginMessageMutex); return loginMessage; }
bool getGameShouldPing() const { return true; }
bool getClientIdRequired() const { return clientIdRequired; }
bool getRegOnlyServer() const { return regServerOnly; }
int getPingClockInterval() const { return pingClockInterval; }
int getMaxGameInactivityTime() const { return maxGameInactivityTime; }
int getMaxPlayerInactivityTime() const { return maxPlayerInactivityTime; }

View file

@ -44,7 +44,7 @@ bool Servatrice_DatabaseInterface::initDatabase(const QString &type, const QStri
sqlDatabase.setDatabaseName(databaseName);
sqlDatabase.setUserName(userName);
sqlDatabase.setPassword(password);
return openDatabase();
}
@ -52,7 +52,7 @@ bool Servatrice_DatabaseInterface::openDatabase()
{
if (sqlDatabase.isOpen())
sqlDatabase.close();
const QString poolStr = instanceId == -1 ? QString("main") : QString("pool %1").arg(instanceId);
qDebug() << QString("[%1] Opening database...").arg(poolStr);
if (!sqlDatabase.open()) {
@ -92,7 +92,7 @@ bool Servatrice_DatabaseInterface::checkSql()
{
if (!sqlDatabase.isValid())
return false;
if (!sqlDatabase.exec("select 1").isActive())
return openDatabase();
return true;
@ -152,12 +152,6 @@ bool Servatrice_DatabaseInterface::usernameIsValid(const QString &user, QString
return re.exactMatch(user);
}
// TODO move this to Server
bool Servatrice_DatabaseInterface::getRequireRegistration()
{
return settingsCache->value("authentication/regonly", 0).toBool();
}
bool Servatrice_DatabaseInterface::registerUser(const QString &userName, const QString &realName, ServerInfo_User_Gender const &gender, const QString &password, const QString &emailAddress, const QString &country, QString &token, bool active)
{
if (!checkSql())
@ -252,23 +246,23 @@ AuthenticationResult Servatrice_DatabaseInterface::checkUserPassword(Server_Prot
if (!usernameIsValid(user, reasonStr))
return UsernameInvalid;
if (checkUserIsBanned(handler->getAddress(), user, reasonStr, banSecondsLeft))
return UserIsBanned;
QSqlQuery *passwordQuery = prepareQuery("select password_sha512, active from {prefix}_users where name = :name");
passwordQuery->bindValue(":name", user);
if (!execSqlQuery(passwordQuery)) {
qDebug("Login denied: SQL error");
return NotLoggedIn;
}
if (passwordQuery->next()) {
const QString correctPassword = passwordQuery->value(0).toString();
const bool userIsActive = passwordQuery->value(1).toBool();
if(!userIsActive) {
qDebug("Login denied: user not active");
return UserIsInactive;
return UserIsInactive;
}
if (correctPassword == PasswordHasher::computeHash(password, correctPassword.left(16))) {
qDebug("Login accepted: password right");
@ -363,7 +357,7 @@ bool Servatrice_DatabaseInterface::activeUserExists(const QString &user)
{
if (server->getAuthenticationMethod() == Servatrice::AuthenticationSql) {
checkSql();
QSqlQuery *query = prepareQuery("select 1 from {prefix}_users where name = :name and active = 1");
query->bindValue(":name", user);
if (!execSqlQuery(query))
@ -377,7 +371,7 @@ bool Servatrice_DatabaseInterface::userExists(const QString &user)
{
if (server->getAuthenticationMethod() == Servatrice::AuthenticationSql) {
checkSql();
QSqlQuery *query = prepareQuery("select 1 from {prefix}_users where name = :name");
query->bindValue(":name", user);
if (!execSqlQuery(query))
@ -405,13 +399,13 @@ bool Servatrice_DatabaseInterface::isInBuddyList(const QString &whoseList, const
{
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone)
return false;
if (!checkSql())
return false;
int id1 = getUserIdInDB(whoseList);
int id2 = getUserIdInDB(who);
QSqlQuery *query = prepareQuery("select 1 from {prefix}_buddylist where id_user1 = :id_user1 and id_user2 = :id_user2");
query->bindValue(":id_user1", id1);
query->bindValue(":id_user2", id2);
@ -424,13 +418,13 @@ bool Servatrice_DatabaseInterface::isInIgnoreList(const QString &whoseList, cons
{
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone)
return false;
if (!checkSql())
return false;
int id1 = getUserIdInDB(whoseList);
int id2 = getUserIdInDB(who);
QSqlQuery *query = prepareQuery("select 1 from {prefix}_ignorelist where id_user1 = :id_user1 and id_user2 = :id_user2");
query->bindValue(":id_user1", id1);
query->bindValue(":id_user2", id2);
@ -442,11 +436,11 @@ bool Servatrice_DatabaseInterface::isInIgnoreList(const QString &whoseList, cons
ServerInfo_User Servatrice_DatabaseInterface::evalUserQueryResult(const QSqlQuery *query, bool complete, bool withId)
{
ServerInfo_User result;
if (withId)
result.set_id(query->value(0).toInt());
result.set_name(query->value(1).toString().toStdString());
const int is_admin = query->value(2).toInt();
int userLevel = ServerInfo_User::IsUser | ServerInfo_User::IsRegistered;
if (is_admin == 1)
@ -492,16 +486,16 @@ ServerInfo_User Servatrice_DatabaseInterface::getUserData(const QString &name, b
ServerInfo_User result;
result.set_name(name.toStdString());
result.set_user_level(ServerInfo_User::IsUser);
if (server->getAuthenticationMethod() == Servatrice::AuthenticationSql) {
if (!checkSql())
return result;
QSqlQuery *query = prepareQuery("select id, name, admin, country, gender, realname, avatar_bmp, registrationDate, email from {prefix}_users where name = :name and active = 1");
query->bindValue(":name", name);
if (!execSqlQuery(query))
return result;
if (query->next())
return evalUserQueryResult(query, true, withId);
else
@ -534,7 +528,7 @@ void Servatrice_DatabaseInterface::unlockSessionTables()
bool Servatrice_DatabaseInterface::userSessionExists(const QString &userName)
{
// Call only after lockSessionTables().
QSqlQuery *query = prepareQuery("select 1 from {prefix}_sessions where user_name = :user_name and id_server = :id_server and end_time is null");
query->bindValue(":id_server", server->getServerId());
query->bindValue(":user_name", userName);
@ -546,10 +540,10 @@ qint64 Servatrice_DatabaseInterface::startSession(const QString &userName, const
{
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone)
return -1;
if (!checkSql())
return -1;
QSqlQuery *query = prepareQuery("insert into {prefix}_sessions (user_name, id_server, ip_address, start_time) values(:user_name, :id_server, :ip_address, NOW())");
query->bindValue(":user_name", userName);
query->bindValue(":id_server", server->getServerId());
@ -563,13 +557,13 @@ void Servatrice_DatabaseInterface::endSession(qint64 sessionId)
{
if (server->getAuthenticationMethod() == Servatrice::AuthenticationNone)
return;
if (!checkSql())
return;
QSqlQuery *query = prepareQuery("lock tables {prefix}_sessions write");
execSqlQuery(query);
query = prepareQuery("update {prefix}_sessions set end_time=NOW() where id = :id_session");
query->bindValue(":id_session", sessionId);
execSqlQuery(query);
@ -581,7 +575,7 @@ void Servatrice_DatabaseInterface::endSession(qint64 sessionId)
QMap<QString, ServerInfo_User> Servatrice_DatabaseInterface::getBuddyList(const QString &name)
{
QMap<QString, ServerInfo_User> result;
if (server->getAuthenticationMethod() == Servatrice::AuthenticationSql) {
checkSql();
@ -589,7 +583,7 @@ QMap<QString, ServerInfo_User> Servatrice_DatabaseInterface::getBuddyList(const
query->bindValue(":name", name);
if (!execSqlQuery(query))
return result;
while (query->next()) {
const ServerInfo_User &temp = evalUserQueryResult(query, false);
result.insert(QString::fromStdString(temp.name()), temp);
@ -601,7 +595,7 @@ QMap<QString, ServerInfo_User> Servatrice_DatabaseInterface::getBuddyList(const
QMap<QString, ServerInfo_User> Servatrice_DatabaseInterface::getIgnoreList(const QString &name)
{
QMap<QString, ServerInfo_User> result;
if (server->getAuthenticationMethod() == Servatrice::AuthenticationSql) {
checkSql();
@ -609,7 +603,7 @@ QMap<QString, ServerInfo_User> Servatrice_DatabaseInterface::getIgnoreList(const
query->bindValue(":name", name);
if (!execSqlQuery(query))
return result;
while (query->next()) {
ServerInfo_User temp = evalUserQueryResult(query, false);
result.insert(QString::fromStdString(temp.name()), temp);
@ -622,13 +616,13 @@ int Servatrice_DatabaseInterface::getNextGameId()
{
if (!sqlDatabase.isValid())
return server->getNextLocalGameId();
if (!checkSql())
return -1;
QSqlQuery *query = prepareQuery("insert into {prefix}_games (time_started) values (now())");
execSqlQuery(query);
return query->lastInsertId().toInt();
}
@ -636,10 +630,10 @@ int Servatrice_DatabaseInterface::getNextReplayId()
{
if (!checkSql())
return -1;
QSqlQuery *query = prepareQuery("insert into {prefix}_replays () values ()");
execSqlQuery(query);
return query->lastInsertId().toInt();
}
@ -647,7 +641,7 @@ void Servatrice_DatabaseInterface::storeGameInformation(const QString &roomName,
{
if (!checkSql())
return;
QVariantList gameIds1, playerNames, gameIds2, userIds, replayNames;
QSetIterator<QString> playerIterator(allPlayersEver);
while (playerIterator.hasNext()) {
@ -665,20 +659,20 @@ void Servatrice_DatabaseInterface::storeGameInformation(const QString &roomName,
userIds.append(id);
replayNames.append(QString::fromStdString(gameInfo.description()));
}
QVariantList replayIds, replayGameIds, replayDurations, replayBlobs;
for (int i = 0; i < replayList.size(); ++i) {
QByteArray blob;
const unsigned int size = replayList[i]->ByteSize();
blob.resize(size);
replayList[i]->SerializeToArray(blob.data(), size);
replayIds.append(QVariant((qulonglong) replayList[i]->replay_id()));
replayGameIds.append(gameInfo.game_id());
replayDurations.append(replayList[i]->duration_seconds());
replayBlobs.append(blob);
}
{
QSqlQuery *query = prepareQuery("update {prefix}_games set room_name=:room_name, descr=:descr, creator_name=:creator_name, password=:password, game_types=:game_types, player_count=:player_count, time_finished=now() where id=:id_game");
query->bindValue(":room_name", roomName);
@ -717,17 +711,17 @@ void Servatrice_DatabaseInterface::storeGameInformation(const QString &roomName,
DeckList *Servatrice_DatabaseInterface::getDeckFromDatabase(int deckId, int userId)
{
checkSql();
QSqlQuery *query = prepareQuery("select content from {prefix}_decklist_files where id = :id and id_user = :id_user");
query->bindValue(":id", deckId);
query->bindValue(":id_user", userId);
execSqlQuery(query);
if (!query->next())
throw Response::RespNameNotFound;
DeckList *deck = new DeckList;
deck->loadFromString_Native(query->value(0).toString());
return deck;
}
@ -789,7 +783,7 @@ bool Servatrice_DatabaseInterface::changeUserPassword(const QString &user, const
qDebug("Change password denied: SQL error");
return true;
}
if (!passwordQuery->next())
return true;
@ -831,7 +825,7 @@ int Servatrice_DatabaseInterface::getActiveUserCount()
void Servatrice_DatabaseInterface::updateUsersClientID(const QString &userName, const QString &userClientID)
{
if (!checkSql())
return;
@ -839,5 +833,5 @@ void Servatrice_DatabaseInterface::updateUsersClientID(const QString &userName,
query->bindValue(":clientid", userClientID);
query->bindValue(":username", userName);
execSqlQuery(query);
}

View file

@ -27,7 +27,7 @@ private:
bool checkUserIsNameBanned(QString const &userName, QString &banReason, int &banSecondsRemaining);
protected:
AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, const QString &user,
AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, const QString &user,
const QString &password, QString &reasonStr, int &secondsLeft);
public slots:
@ -36,7 +36,7 @@ public slots:
public:
Servatrice_DatabaseInterface(int _instanceId, Servatrice *_server);
~Servatrice_DatabaseInterface();
bool initDatabase(const QString &type, const QString &hostName, const QString &databaseName,
bool initDatabase(const QString &type, const QString &hostName, const QString &databaseName,
const QString &userName, const QString &password);
bool openDatabase();
bool checkSql();
@ -52,7 +52,7 @@ public:
bool isInBuddyList(const QString &whoseList, const QString &who);
bool isInIgnoreList(const QString &whoseList, const QString &who);
ServerInfo_User getUserData(const QString &name, bool withId = false);
void storeGameInformation(const QString &roomName, const QStringList &roomGameTypes, const ServerInfo_Game &gameInfo,
void storeGameInformation(const QString &roomName, const QStringList &roomGameTypes, const ServerInfo_Game &gameInfo,
const QSet<QString> &allPlayersEver, const QSet<QString>&allSpectatorsEver, const QList<GameReplay *> &replayList);
DeckList *getDeckFromDatabase(int deckId, int userId);
@ -68,12 +68,11 @@ public:
bool usernameIsValid(const QString &user, QString & error);
bool checkUserIsBanned(const QString &ipAddress, const QString &userName, QString &banReason, int &banSecondsRemaining);
bool getRequireRegistration();
bool registerUser(const QString &userName, const QString &realName, ServerInfo_User_Gender const &gender,
bool registerUser(const QString &userName, const QString &realName, ServerInfo_User_Gender const &gender,
const QString &password, const QString &emailAddress, const QString &country, QString &token, bool active = false);
bool activateUser(const QString &userName, const QString &token);
void updateUsersClientID(const QString &userName, const QString &userClientID);
void logMessage(const int senderId, const QString &senderName, const QString &senderIp, const QString &logMessage,
void logMessage(const int senderId, const QString &senderName, const QString &senderIp, const QString &logMessage,
LogMessage_TargetType targetType, const int targetId, const QString &targetName);
bool changeUserPassword(const QString &user, const QString &oldPassword, const QString &newPassword);
QChar getGenderChar(ServerInfo_User_Gender const &gender);