QList<QString> Server::getOnlineModeratorList() { // clients list should be locked by calling function prior to iteration otherwise sigfaults may occur QList<QString> results; for (int i = 0; i < clients.size(); ++i) { ServerInfo_User *data = clients[i]->getUserInfo(); //TODO: this line should be updated in the event there is any type of new user level created if (data && (data->user_level() & ServerInfo_User::IsModerator || data->user_level() & ServerInfo_User::IsAdmin) ) results << QString::fromStdString(data->name()).simplified(); } return results; }
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 QString country = query.value(5).toString(); if (!country.isEmpty()) result.set_country(country.toStdString()); if (complete) { const QByteArray avatarBmp = query.value(6).toByteArray(); if (avatarBmp.size()) result.set_avatar_bmp(avatarBmp.data(), avatarBmp.size()); } const QString genderStr = query.value(4).toString(); if (genderStr == "m") result.set_gender(ServerInfo_User::Male); else if (genderStr == "f") result.set_gender(ServerInfo_User::Female); const int is_admin = query.value(2).toInt(); int userLevel = ServerInfo_User::IsUser | ServerInfo_User::IsRegistered; if (is_admin == 1) userLevel |= ServerInfo_User::IsAdmin | ServerInfo_User::IsModerator; else if (is_admin == 2) userLevel |= ServerInfo_User::IsModerator; result.set_user_level(userLevel); const QString realName = query.value(3).toString(); if (!realName.isEmpty()) result.set_real_name(realName.toStdString()); const QDateTime regDate = query.value(7).toDateTime(); if(!regDate.toString(Qt::ISODate).isEmpty()) { qint64 accountAgeInSeconds = regDate.secsTo(QDateTime::currentDateTime()); result.set_accountage_secs(accountAgeInSeconds); } return result; }
QMap<QString, ServerInfo_User> Servatrice_DatabaseInterface::getIgnoreList(const QString &name) { QMap<QString, ServerInfo_User> result; if (server->getAuthenticationMethod() == Servatrice::AuthenticationSql) { checkSql(); QSqlQuery *query = prepareQuery("select a.id, a.name, a.admin, a.country, a.privlevel from {prefix}_users a left join {prefix}_ignorelist b on a.id = b.id_user2 left join {prefix}_users c on b.id_user1 = c.id where c.name = :name"); 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); } } return result; }
void Server::removeClient(Server_ProtocolHandler *client) { QWriteLocker locker(&clientsLock); clients.removeAt(clients.indexOf(client)); ServerInfo_User *data = client->getUserInfo(); if (data) { Event_UserLeft event; event.set_name(data->name()); SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); for (int i = 0; i < clients.size(); ++i) if (clients[i]->getAcceptsUserListChanges()) 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); emit endSession(sessionId); qDebug() << "closed session id:" << sessionId; } } qDebug() << "Server::removeClient: removed" << (void *) client << ";" << clients.size() << "clients; " << users.size() << "users left"; }
QMap<QString, ServerInfo_User *> Servatrice::getIgnoreList(const QString &name) { QMutexLocker locker(&dbMutex); QMap<QString, ServerInfo_User *> result; const QString method = settings->value("authentication/method").toString(); if (method == "sql") { checkSql(); QSqlQuery query; query.prepare("select a.name, a.admin, a.realname, a.gender, a.country from " + dbPrefix + "_users a left join " + dbPrefix + "_ignorelist b on a.id = b.id_user2 left join " + dbPrefix + "_users c on b.id_user1 = c.id where c.name = :name"); query.bindValue(":name", name); if (!execSqlQuery(query)) return result; while (query.next()) { ServerInfo_User *temp = evalUserQueryResult(query, false); result.insert(temp->getName(), temp); } } return result; }
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); }
ServerInfo_User Servatrice_DatabaseInterface::getUserData(const QString &name, bool withId) { 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(sqlDatabase); query.prepare("select id, name, admin, realname, gender, country, avatar_bmp, registrationDate from " + server->getDbPrefix() + "_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 return result; } else return result; }
ServerInfo_User LocalServer_DatabaseInterface::getUserData(const QString &name, bool /*withId*/) { ServerInfo_User result; result.set_name(name.toStdString()); return result; }
AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString &name, const QString &password, QString &reasonStr, int &secondsLeft, QString &clientid, QString &clientVersion, QString & /* connectionType */) { if (name.size() > 35) name = name.left(35); Server_DatabaseInterface *databaseInterface = getDatabaseInterface(); AuthenticationResult authState = databaseInterface->checkUserPassword(session, name, password, clientid, 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 if (authState == PasswordRight) { if (users.contains(name) || databaseInterface->userSessionExists(name)) { if (users.contains(name)) { qDebug("Session already logged in, logging old session out"); Event_ConnectionClosed event; event.set_reason(Event_ConnectionClosed::LOGGEDINELSEWERE); event.set_reason_str("You have been logged out due to logging in at another location."); event.set_end_time(QDateTime::currentDateTime().toTime_t()); SessionEvent *se = users.value(name)->prepareSessionEvent(event); users.value(name)->sendProtocolItem(*se); delete se; users.value(name)->prepareDestroy(); } else { qDebug() << "Active session and sessions table inconsistent, please validate session table information for user " << name; } } } else if (authState == UnknownUser) { // Change user name so that no two users have the same names, // don't interfere with registered user names though. if (getRegOnlyServerEnabled()) { qDebug("Login denied: registration required"); databaseInterface->unlockSessionTables(); return RegistrationRequired; } QString tempName = name; int i = 0; while (users.contains(tempName) || databaseInterface->activeUserExists(tempName) || databaseInterface->userSessionExists(tempName)) tempName = name + "_" + QString::number(++i); name = tempName; data.set_name(name.toStdString()); } QWriteLocker locker(&clientsLock); databaseInterface->lockSessionTables(); users.insert(name, session); qDebug() << "Server::loginUser:"******"name=" << name; data.set_session_id(databaseInterface->startSession(name, session->getAddress(), clientid, session->getConnectionType())); 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); for (int i = 0; i < clients.size(); ++i) 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 (getClientIDRequiredEnabled()) return ClientIdRequired; } else { // update users database table with client id databaseInterface->updateUsersClientID(name, clientid); } databaseInterface->updateUsersLastLoginData(name, clientVersion); se = Server_ProtocolHandler::prepareSessionEvent(event); sendIsl_SessionEvent(*se); delete se; return authState; }
void UserInfoBox::updateInfo(const ServerInfo_User &user) { const UserLevelFlags userLevel(user.user_level()); QPixmap avatarPixmap; const std::string bmp = user.avatar_bmp(); if (!avatarPixmap.loadFromData((const uchar *) bmp.data(), bmp.size())) avatarPixmap = UserLevelPixmapGenerator::generatePixmap(64, userLevel, false); avatarLabel.setPixmap(avatarPixmap.scaled(avatarLabel.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); nameLabel.setText(QString::fromStdString(user.name())); realNameLabel2.setText(QString::fromStdString(user.real_name())); QString country = QString::fromStdString(user.country()); if (country.length() != 0) { countryLabel2.setPixmap(CountryPixmapGenerator::generatePixmap(15, country)); countryLabel3.setText(QString("(%1)").arg(country.toUpper())); } else { countryLabel2.setText(""); countryLabel3.setText(""); } userLevelLabel2.setPixmap(UserLevelPixmapGenerator::generatePixmap(15, userLevel, false)); QString userLevelText; if (userLevel.testFlag(ServerInfo_User::IsAdmin)) userLevelText = tr("Administrator"); else if (userLevel.testFlag(ServerInfo_User::IsModerator)) userLevelText = tr("Moderator"); else if (userLevel.testFlag(ServerInfo_User::IsRegistered)) userLevelText = tr("Registered user"); else userLevelText = tr("Unregistered user"); userLevelLabel3.setText(userLevelText); QString accountAgeString = tr("Unregistered user"); if (userLevel.testFlag(ServerInfo_User::IsAdmin) || userLevel.testFlag(ServerInfo_User::IsModerator) || userLevel.testFlag(ServerInfo_User::IsRegistered)) { if (user.accountage_secs() == 0) accountAgeString = tr("Unknown"); else { qint64 seconds = user.accountage_secs(); qint64 minutes = seconds / SIXTY; qint64 hours = minutes / SIXTY; qint64 days = hours / HOURS_IN_A_DAY; qint64 years = days / DAYS_IN_A_YEAR; qint64 daysMinusYears = days - (years * DAYS_IN_A_YEAR); accountAgeString = ""; if (years >= 1) { accountAgeString = QString::number(years); accountAgeString.append(" "); accountAgeString.append(years == 1 ? tr("Year") : tr("Years")); accountAgeString.append(" "); } accountAgeString.append(QString::number(daysMinusYears)); accountAgeString.append(" "); accountAgeString.append(days == 1 ? tr("Day") : tr("Days")); } } accountAgeLabel2.setText(accountAgeString); }
void PlayerTarget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { ServerInfo_User *info = owner->getUserInfo(); const qreal border = 2; QRectF avatarBoundingRect = boundingRect().adjusted(border, border, -border, -border); QRectF translatedRect = painter->combinedTransform().mapRect(avatarBoundingRect); QSize translatedSize = translatedRect.size().toSize(); QPixmap cachedPixmap; const QString cacheKey = "avatar" + QString::number(translatedSize.width()) + "_" + QString::number(info->getUserLevel()) + "_" + QString::number(fullPixmap.cacheKey()); #if QT_VERSION >= 0x040600 if (!QPixmapCache::find(cacheKey, &cachedPixmap)) { #else if (!QPixmapCache::find(cacheKey, cachedPixmap)) { #endif cachedPixmap = QPixmap(translatedSize.width(), translatedSize.height()); QPainter tempPainter(&cachedPixmap); QRadialGradient grad(translatedRect.center(), sqrt(translatedSize.width() * translatedSize.width() + translatedSize.height() * translatedSize.height()) / 2); grad.setColorAt(1, Qt::black); grad.setColorAt(0, QColor(180, 180, 180)); tempPainter.fillRect(QRectF(0, 0, translatedSize.width(), translatedSize.height()), grad); QPixmap tempPixmap; if (fullPixmap.isNull()) tempPixmap = UserLevelPixmapGenerator::generatePixmap(translatedSize.height(), info->getUserLevel()); else tempPixmap = fullPixmap.scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); tempPainter.drawPixmap((translatedSize.width() - tempPixmap.width()) / 2, (translatedSize.height() - tempPixmap.height()) / 2, tempPixmap); QPixmapCache::insert(cacheKey, cachedPixmap); } painter->save(); painter->resetTransform(); painter->translate((translatedSize.width() - cachedPixmap.width()) / 2.0, 0); painter->drawPixmap(translatedRect, cachedPixmap, cachedPixmap.rect()); painter->restore(); QRectF nameRect = QRectF(0, boundingRect().height() - 20, 110, 20); painter->fillRect(nameRect, QColor(0, 0, 0, 160)); QRectF translatedNameRect = painter->combinedTransform().mapRect(nameRect); painter->save(); painter->resetTransform(); QString name = info->getName(); if (name.size() > 13) name = name.mid(0, 10) + "..."; QFont font; font.setPixelSize(qMax((int) round(translatedNameRect.height() / 1.5), 9)); painter->setFont(font); painter->setPen(Qt::white); painter->drawText(translatedNameRect, Qt::AlignVCenter | Qt::AlignLeft, " " + name); painter->restore(); QPen pen(QColor(100, 100, 100)); pen.setWidth(border); pen.setJoinStyle(Qt::RoundJoin); painter->setPen(pen); painter->drawRect(boundingRect().adjusted(border / 2, border / 2, -border / 2, -border / 2)); if (getBeingPointedAt()) painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); } AbstractCounter *PlayerTarget::addCounter(int _counterId, const QString &_name, int _value) { if (playerCounter) return 0; playerCounter = new PlayerCounter(owner, _counterId, _name, _value, this); playerCounter->setPos(boundingRect().width() - playerCounter->boundingRect().width(), boundingRect().height() - playerCounter->boundingRect().height()); connect(playerCounter, SIGNAL(destroyed()), this, SLOT(delCounter())); return playerCounter; } void PlayerTarget::delCounter() { playerCounter = 0; }
AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString &name, const QString &password, QString &reasonStr, int &secondsLeft) { 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)) 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) { if (users.contains(name) || databaseInterface->userSessionExists(name)) { qDebug("Login denied: would overwrite old session"); databaseInterface->unlockSessionTables(); return WouldOverwriteOldSession; } } else if (authState == UnknownUser) { // Change user name so that no two users have the same names, // don't interfere with registered user names though. QSettings settings("servatrice.ini", QSettings::IniFormat); bool requireReg = settings.value("authentication/regonly", 0).toBool(); if (requireReg) { qDebug("Login denied: registration required"); databaseInterface->unlockSessionTables(); return RegistrationRequired; } QString tempName = name; int i = 0; while (users.contains(tempName) || databaseInterface->userExists(tempName) || databaseInterface->userSessionExists(tempName)) tempName = name + "_" + QString::number(++i); name = tempName; data.set_name(name.toStdString()); } users.insert(name, session); qDebug() << "Server::loginUser:"******"name=" << name; 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); for (int i = 0; i < clients.size(); ++i) if (clients[i]->getAcceptsUserListChanges()) clients[i]->sendProtocolItem(*se); delete se; event.mutable_user_info()->CopyFrom(session->copyUserInfo(true, true, true)); locker.unlock(); se = Server_ProtocolHandler::prepareSessionEvent(event); sendIsl_SessionEvent(*se); delete se; return authState; }