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

View file

@ -57,6 +57,7 @@ public:
virtual bool getGameShouldPing() const { return false; } virtual bool getGameShouldPing() const { return false; }
virtual bool getClientIdRequired() const { return false; } virtual bool getClientIdRequired() const { return false; }
virtual bool getRegOnlyServer() const { return false; }
virtual int getPingClockInterval() const { return 0; } virtual int getPingClockInterval() const { return 0; }
virtual int getMaxGameInactivityTime() const { return 9999999; } virtual int getMaxGameInactivityTime() const { return 9999999; }
virtual int getMaxPlayerInactivityTime() 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 ; if the chosen authentication method is password, here you can define the password your users will use to log in
password=123456 password=123456
; Accept only registered users? default is 0 (accept unregistered users) ; Accept only registered users? default is false (accept unregistered users)
regonly=0 regonly=false
[users] [users]

View file

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

View file

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

View file

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

View file

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