bool DisconnectHandler::execute(GameNet::Box * box) { CCLOG("%s disconnected.", box->getAddress().ToString()); int id = box->getId(); auto player = game->getPlayer(id); if(player == nullptr){ CCLOG("Player not found in the Game."); return false; } game->getStadium()->removeChild( player->getSprite() ); game->removePlayer(player); // set new admin if( player->isAdmin() && game->playersCount() >= 1 ) { auto newAdmin = game->getRandomPlayer(); game->setAsAdmin(newAdmin); CCLOG("New admin is %s", newAdmin->getName().c_str()); } else if (game->playersCount() == 0) { game->getStadium()->setAdminName(""); } player->destroy(); return false; }
/** * \brief Function to delete VISHNU user * \fn int deleteUser(UMS_Data::User user) * \param user The user data structure * \return raises an exception on error */ int UserServer::deleteUser(UMS_Data::User user) { //If the user to delete is not the super VISHNU admin if (user.getUserId().compare(ROOTUSERNAME) != 0) { //If the user exists if (exist()) { if (isAdmin()) { //if the user who will be deleted exist if (getAttribut("where userid='"+user.getUserId()+"'").size() != 0) { //Execution of the sql code to delete the user mdatabaseVishnu->process("DELETE FROM users where userid='"+user.getUserId()+"'"); } // End if the user who will be deleted exist else { UMSVishnuException e (ERRCODE_UNKNOWN_USERID); throw e; } } //END if the user is an admin else { UMSVishnuException e (ERRCODE_NO_ADMIN); throw e; } } //END if the user exists else { UMSVishnuException e (ERRCODE_UNKNOWN_USER); throw e; } }//END If the user to delete is not the super VISHNU admin else { UserException e (ERRCODE_INVALID_PARAM, "It is not possible to delete this user. It is the VISHNU root user"); throw e; } return 0; }//END: deleteUser(UMS_Data::User user)
QString ChannelNick::tooltip() const { QString strTooltip; QTextStream tooltip( &strTooltip, QIODevice::WriteOnly ); tooltip << "<qt>"; tooltip << "<table cellspacing=\"5\" cellpadding=\"0\">"; m_nickInfo->tooltipTableData(tooltip); QStringList modes; if(isOp()) modes << i18n("Operator"); if(isAdmin()) modes << i18n("Admin"); if(isOwner()) modes << i18n("Owner"); if(isHalfOp()) modes << i18n("Half-operator"); if(hasVoice()) modes << i18n("Has voice"); //Don't show anything if the user is just a normal user //if(modes.empty()) modes << i18n("A normal user"); if(!modes.empty()) { tooltip << "<tr><td><b>" << i18n("Mode") << ":</b></td><td>" << modes.join(QStringLiteral(", ")) << "</td></tr>"; } tooltip << "</table></qt>"; //qDebug() << strTooltip ; //if(!dirty) return QString(); return strTooltip; }
/** * \brief Function to change VISHNU user password * \fn int resetPassword(UMS_Data::User user, std::string sendmailScriptPath) * \param user The user data structure * \param sendmailScriptPath The path to the script for sending emails * \return raises an exception on error */ int UserServer::resetPassword(UMS_Data::User& user, std::string sendmailScriptPath) { std::string sqlResetPwd; std::string sqlUpdatePwdState; std::string passwordCrypted; std::string pwd; //If the user exists if (exist()) { //if the user is an admin if (isAdmin()) { //if the user whose password will be reset exists if (getAttribut("where userid='"+user.getUserId()+"'").size() != 0) { //generation of a new password pwd = generatePassword(user.getUserId(), user.getUserId()); user.setPassword(pwd.substr(0,PASSWORD_MAX_SIZE)); //to get the password encryptes passwordCrypted = vishnu::cryptPassword(user.getUserId(), user.getPassword()); //The sql code to reset the password sqlResetPwd = "UPDATE users SET pwd='"+passwordCrypted+"' where " "userid='"+user.getUserId()+"';"; //sql code to update the passwordstate sqlUpdatePwdState = "UPDATE users SET passwordstate=0 " "where userid='"+user.getUserId()+"' and pwd='"+passwordCrypted+"';"; //To append the previous sql codes sqlResetPwd.append(sqlUpdatePwdState); //Execution of the sql code on the database mdatabaseVishnu->process( sqlResetPwd.c_str()); //to get the email adress of the user std::string email = getAttribut("where userid='"+user.getUserId()+"'", "email"); user.setEmail(email); //Send email std::string emailBody = getMailContent(user, false); sendMailToUser(user, emailBody, "Vishnu message: password reset", sendmailScriptPath); } // End if the user whose password will be reset exists else { UMSVishnuException e (ERRCODE_UNKNOWN_USERID, "You must use a global VISHNU identifier"); throw e; } } //END if the user is an admin else { UMSVishnuException e (ERRCODE_NO_ADMIN); throw e; } } //END if the user exists else { UMSVishnuException e (ERRCODE_UNKNOWN_USER); throw e; } return 0; }//END: resetPassword(UMS_Data::User user)
Role requestRole (Role const& required, HTTP::Port const& port, Json::Value const& params, beast::IP::Endpoint const& remoteIp) { Role role (Role::GUEST); if (isAdmin(port, params, remoteIp.address ())) role = Role::ADMIN; if (required == Role::ADMIN && role != required) role = Role::FORBID; return role; }
Message::Message( int direction, const std::string& string, const DataDictionary& sessionDataDictionary, const DataDictionary& applicationDataDictionary, const ValidationRules* validationRules ) throw( Exception ) : m_validStructure( true ) { setStringHeader( string ); if( isAdmin() ) setString( direction, string, validationRules, &sessionDataDictionary, NULL ); else setString( direction, string, validationRules, &sessionDataDictionary, &applicationDataDictionary ); }
void MainWindow::on_pushButton_3_clicked() { if(!utilizatori.isOpen()){ //verificam daca baza de date e deschisa //qDebug()<<"Esuare la conectarea la baza de date.."; return; } user=ui->lineEdit->text(); //salvam in variabila user numele utilizatorului pass=ui->lineEdit_2->text();//salvam in variabila pass parola utilizatorului QSqlQuery qry; //login if(qry.exec("select * from users where nume='"+user+"' and pass='******'")){ int count=0; while(qry.next()){ count++; } if(count==1){//verificam daca exista user-ul si continuam spre urmatorul meniu ui->lineEdit->setVisible(false); ui->pushButton_3->setVisible(false); ui->pushButton_4->setVisible(true); ui->butstatistici->setVisible(true); ui->buttop3->setVisible(true); ui->pushButton_8->setVisible(true); ui->lineEdit_2->setVisible(false); ui->label_7->setVisible(false); ui->label_6->setVisible(false); ui->label_2->setText("Salut, "+user+"!"); ui->label_2->setStyleSheet("text-decoration: none; color: #666; position: absolute; font-size: 24px"); ui->pushButton_9->setVisible(false); ui->pushButton_10->setVisible(false); if(isAdmin(user)){ ui->butadmin->setVisible(true); } } if(count<1) //in cazul in care userul nu exista, cream unul nou { if(!exist(user)) { QMessageBox::critical(this,tr("Eroare!"),tr("Userul nu exista!")); ui->pushButton_8->setVisible(true); } else{ QMessageBox::critical(this,tr("Eroare!"),tr("Parola e gresita")); ui->pushButton_10->setVisible(true); ui->pushButton_8->setVisible(true); } } } }
IResponse *GroupsService::getUsersGroups( IRequest *req) { QVariantList groups; QSqlQuery query; if(m_proxyConnection->session()->value("logged") !=""){ int page; if(!(page= req->parameterValue("page").toInt())){ QVariantMap error; error.insert("page_number","error"); return req->response(QVariant(error), IResponse::BAD_REQUEST); } query.prepare("SELECT * FROM groups " "INNER JOIN group_users ON groups.id = group_users.group_id " "WHERE group_users.status = 1 AND group_users.user_id = :user_id " "ORDER BY groups.name ASC LIMIT :limit OFFSET :offset "); query.bindValue(":user_id", m_proxyConnection->session()->value("logged").toString()); query.bindValue(":limit",PER_PAGE); query.bindValue(":offset", (page-1)* PER_PAGE); if(!query.exec()) return req->response(IResponse::INTERNAL_SERVER_ERROR); while(query.next()){ QString user_id = m_proxyConnection->session()->value("logged").toString(); QVariantMap group; QString group_id = query.value(query.record().indexOf("id")).toString(); group.insert("id",query.value(query.record().indexOf("id"))); group.insert("name",query.value(query.record().indexOf("name"))); group.insert("description",query.value(query.record().indexOf("description"))); group.insert("date_created", query.value(query.record().indexOf("date_created"))); if(isAdmin(user_id.toUInt(),group_id.toUInt())) group.insert("admin","1"); else group.insert("admin","0"); group.insert("member","1"); groups.append(group); } return req->response(QVariant(groups),IResponse::OK); } return req->response(IResponse::UNAUTHORIZED); }
int CGlobalSettings::SetGlobalValue(const char *product, const char *key, const char *value, const char *buffer) { HKEY hKey,hSubKey; DWORD dwLen; cvs::string regkey; if(!isAdmin()) return -1; if(!product || !strcmp(product,"cvsnt")) regkey="Software\\CVS"; else cvs::sprintf(regkey,64,"Software\\March Hare Software Ltd\\%s",product); if(RegOpenKeyExA(HKEY_LOCAL_MACHINE,regkey.c_str(),0,KEY_READ|KEY_WRITE,&hKey) && RegCreateKeyExA(HKEY_LOCAL_MACHINE,regkey.c_str(),0,NULL,0,KEY_READ|KEY_WRITE,NULL,&hKey,NULL)) { return -1; // Couldn't open or create key } if(key) { if(RegOpenKeyExA(hKey,key,0,KEY_WRITE,&hSubKey) && RegCreateKeyExA(hKey,key,0,NULL,0,KEY_WRITE,NULL,&hSubKey,NULL)) { RegCloseKey(hKey); return -1; // Couldn't open or create key } RegCloseKey(hKey); hKey=hSubKey; } if(!buffer) { RegDeleteValueA(hKey,value); } else { dwLen=(DWORD)strlen(buffer); if(RegSetValueExA(hKey,value,0,REG_SZ,(LPBYTE)buffer,dwLen+1)) { RegCloseKey(hKey); return -1; } } RegCloseKey(hKey); return 0; }
IResponse *GroupsService::getIsAdmin(IRequest *req){ QString user_id = req->parameterValue("user_id"); QString group_id = req->parameterValue("group_id"); QVariantMap res; if(isAdmin(user_id.toUInt(), group_id.toUInt())) res.insert("admin","1"); else res.insert("admin","0"); return req->response(QVariant(res),IResponse::OK); }
void ClientSystem::frameTrigger(int curtime) { if (scenarioStarted()) { PlayerControl::handleExtraPlayerMovements(curtime); TargetingControl::determineMouseTarget(); can_edit = int(isAdmin()); IntensityTexture::doBackgroundLoading(); } ClientSystem::cleanupHUD(); #ifdef INTENSITY_PLUGIN PluginListener::frameTrigger(); #endif }
int CGlobalSettings::SetGlobalValue(const char *product, const char *key, const char *value, int ival) { HKEY hKey,hSubKey; DWORD dwLen; cvs::string regkey; if(!isAdmin()) return -1; if(!product || !strcmp(product,"cvsnt")) regkey="Software\\CVS"; else cvs::sprintf(regkey,64,"Software\\March Hare Software Ltd\\%s",product); if(RegOpenKeyExA(HKEY_LOCAL_MACHINE,regkey.c_str(),0,KEY_READ|KEY_WRITE,&hKey) && RegCreateKeyExA(HKEY_LOCAL_MACHINE,regkey.c_str(),0,NULL,0,KEY_READ|KEY_WRITE,NULL,&hKey,NULL)) { return -1; // Couldn't open or create key } if(key) { if(RegOpenKeyExA(hKey,key,0,KEY_WRITE,&hSubKey) && RegCreateKeyExA(hKey,key,0,NULL,0,KEY_WRITE,NULL,&hSubKey,NULL)) { RegCloseKey(hKey); return -1; // Couldn't open or create key } RegCloseKey(hKey); hKey=hSubKey; } DWORD dw = (DWORD)ival,err; dwLen=(DWORD)sizeof(DWORD); err = RegSetValueExA(hKey,value,0,REG_DWORD,(LPBYTE)&dw,dwLen); if(err) { dw = GetLastError(); RegCloseKey(hKey); return -1; } RegCloseKey(hKey); return 0; }
int HttpListener::writeStatusReport( int fd ) { char achBuf[1024]; int len = safe_snprintf( achBuf, 1024, "LISTENER%d [%s] %s\n", isAdmin(), getName(), getAddrStr() ); if ( ::write( fd, achBuf, len ) != len ) return -1; if ( getVHostMap()->writeStatusReport( fd ) == -1 ) return -1; if ( m_pSubIpMap && m_pSubIpMap->writeStatusReport( fd ) == -1 ) return -1; if ( ::write( fd, "ENDL\n", 5 ) != 5 ) return -1; return 0; }
void MainWindow::on_butback_clicked() { //Butonul de inapoi ui->pushButton_4->setVisible(true); ui->butstatistici->setVisible(true); ui->buttop3->setVisible(true); ui->pushButton_8->setVisible(true); ui->stat1->setVisible(false); ui->stat1_2->setVisible(false); ui->statnume->setVisible(false); ui->statnume_2->setVisible(false); ui->statnume_3->setVisible(false); ui->statwins->setVisible(false); ui->statwins_2->setVisible(false); ui->statwins_3->setVisible(false); ui->butback->setVisible(false); ui->line_2->setVisible(false); ui->catanim->setVisible(false); ui->cataleat->setVisible(false); ui->cataut->setVisible(false); ui->catfruct->setVisible(false); ui->catjud->setVisible(false); ui->catpict->setVisible(false); ui->catplant->setVisible(false); ui->cattari->setVisible(false); ui->label_3->setVisible(false); ui->lineEdit_3->setVisible(false); ui->label_4->setVisible(false); ui->img1->setVisible(false); ui->img1_2->setVisible(false); ui->img1_3->setVisible(false); ui->img1_4->setVisible(false); ui->img1_5->setVisible(false); ui->img1_6->setVisible(false); ui->label_3->setText("Introduceti litere:"); ui->label_3->setStyleSheet("text-decoration: none; color: #666; position: absolute; font-size: 24px"); i=0; //reinitializam variabila in care se inregistreaza greselile cuvm=" "; //reinitializam cuvantul de ghicit ui->lineEdit_3->setText(" "); ui->label_2->setText("Salut, "+user+"!"); //reinitializam meniul principal ui->label_2->setStyleSheet("text-decoration: none; color: #666; position: absolute; font-size: 24px"); ui->groupBox->setVisible(false); if(isAdmin(user)) ui->butadmin->setVisible(true); }
void delete_user_from_channel(int descriptor,Channel* channel){ int ret; if(channel==NULL){ printf("Utente in nessun canale.Connessione chiusa.\n"); return; } ret= sem_wait(&channels_sem); ERROR_HELPER(ret,"error on sem_wait to channels_sem"); if(isAdmin(descriptor,channel) && channel->sub_num>1){ char buffer[BUFFER_SIZE]; int descriptor= channel->subscribers[1]->socket; channel->admin= descriptor; memset(buffer,0, sizeof(buffer)); snprintf(buffer,sizeof(buffer),"%s","You're the new admin of the chat.\n"); send_message(descriptor,buffer,strlen(buffer)); } int i; for(i=0; i<channel->sub_num; i++){ if(channel->subscribers[i]->socket==descriptor){ free(channel->subscribers[i]); for(;i<channel->sub_num-1; i++){ channel->subscribers[i]= channel->subscribers[i+1]; } break; } } channel->sub_num-=1; if(channel->sub_num==0) delete_channel_by_server(channel); ret= sem_post(&channels_sem); ERROR_HELPER(ret,"error on sem_post to channels_sem"); printf("E' stato eseguito un delete_user\n\n"); print_stats_channels(); }
void Mind::run() { int i, raw; activityMonitor monitor; struct epoll_event *e = NULL; std::string buf; ircEvent event; User user; std::string tmp; moduleMap::const_iterator it; _irc = new irc(); if (!_irc->connect(_conf.get("server"), atoi(_conf.get("port").c_str()))) throw Exception("Cannot connect to server... aborting"); _irc->setNick(_conf.get("nick")); _irc->setIdent(_conf.get("ident")); _irc->setRealname(_conf.get("realname")); if ((tmp = _conf.get("oper")) == "true") { _irc->setOper(true); _irc->setOperNick(_conf.get("operUsername")); _irc->setOperPass(_conf.get("operPassword")); } _irc->auth(); if (_conf.exists("auth")) _irc->setNsPass(_conf.get("auth")); _irc->identify(); if (_irc->isOper()) _irc->oper(); if (_conf.exists("autojoin")) { tmp = _conf.get("autojoin"); _irc->join(tmp); } monitor.setFd(_irc->getSock()->getFd()); monitor.setEvents(EPOLLIN | EPOLLERR | EPOLLHUP); if (!monitor.init()) { *_logger << "Unable to init the activity monitor"; return; } while (_run) if (monitor.checkActivity()) { if (!(e = monitor.getActivity())) { _irc->end(); return; } for (i = 0; i < monitor.getNb(); ++i) { if (e[i].events & EPOLLHUP || e[i].events & EPOLLERR) { _irc->end(); return; } if (e[i].events & EPOLLIN) { _irc->run(); buf = _irc->getBuf(); event = _irc->getEvent(); try { user = irc::makeUser(buf); } catch (Exception &e) { event = UNKNOWN; } if (isAdmin(user.getNick())) execAdmin(event, buf); if (isRaw(buf)) // the message is not an 'IRC event' { raw = atoi(Utils::getToken(buf, " ", 2).c_str()); /* broadcast to every module */ for (it = _mod.begin(); raw != -1 && it != _mod.end(); ++it) if (it->second->isEventable()) it->second->onRaw(raw, buf); } /* broadcast irc event to every module */ for (it = _mod.begin(); event != UNKNOWN && it != _mod.end(); ++it) if (it->second->isEventable()) it->second->execEvent(event, user, buf); event = UNKNOWN; } } } _irc->end(); *_logger << "Connection closed."; return; }
// show element IResponse *GroupsService::show(IRequest *req, uint id) { QSqlQuery query; QString user_id = m_proxyConnection->session()->value("logged").toString(); if(!m_proxyConnection->session()->isLoggedIn() || !isMember(user_id.toUInt(),id) ) req->response(IResponse::UNAUTHORIZED); query.prepare("SELECT * FROM groups WHERE id = :id"); query.bindValue(":id",id); if( !query.exec()) return req->response(IResponse::INTERNAL_SERVER_ERROR); QVariantMap group; if(query.first()){ group.insert("id", query.value(query.record().indexOf("id"))); group.insert("name", query.value(query.record().indexOf("name"))); group.insert("description", query.value(query.record().indexOf("description"))); group.insert("has_password", query.value(query.record().indexOf("has_password"))); group.insert("has_approvement", query.value(query.record().indexOf("has_approvement"))); if(isAdmin(user_id.toUInt(), id)) group.insert("admin","1"); else group.insert("admin","0"); if(isMember(user_id.toUInt(), id)) group.insert("member","1"); else group.insert("member","0"); QSqlQuery q_type; q_type.prepare("SELECT name FROM group_types WHERE _id = :id"); q_type.bindValue(":id",query.value(query.record().indexOf("group_type_id"))); if(!q_type.exec()){ return req->response(IResponse::INTERNAL_SERVER_ERROR); } q_type.first(); group.insert("group_type_name", q_type.value(q_type.record().indexOf("name"))); // QSqlQuery q_inner_groups; // q_inner_groups.prepare("SELECT * FROM groups WHERE parent = :id"); // q_inner_groups.bindValue(":id",id); // if(!q_inner_groups.exec()){ // return req->response(IResponse::INTERNAL_SERVER_ERROR); // } // groupDetail.append(group); // while(q_inner_groups.next()){ // QVariantMap innerGroup; // innerGroup.insert("name",q_inner_groups.value(q_inner_groups.record().indexOf("name"))); // innerGroup.insert("id",q_inner_groups.value(q_inner_groups.record().indexOf("id"))); // groupDetail.append(innerGroup); // } return req->response(QVariant(group), IResponse::OK); } QVariantMap error; error.insert("group","does not exist"); return req->response(QVariant(error),IResponse::BAD_REQUEST); }
int cmd_check(char* buffer,User* user){ int ret; int descriptor= user->socket; if(strcmp(buffer,QUIT_COMMAND)==0){ if(user->user_channel==NULL){ char buffer[BUFFER_SIZE]; snprintf(buffer,sizeof(buffer),"%s",QUIT_CLIENT); send_message(user->socket,buffer,strlen(buffer)); return QUIT_RET; } Channel* desc_channel= user->user_channel; if(num_channels>0){ if(isAdmin(descriptor,desc_channel)){ if(desc_channel->sub_num>1){ char buffer[BUFFER_SIZE]; snprintf(buffer,sizeof(buffer),"%s","Do you want to close the channel? (y/n)"); do{ ret= send_message(descriptor,buffer,strlen(buffer)); ret= receive_message(descriptor,buffer); if(strlen(buffer)==1){ if(buffer[0]=='y'){ delete_channel(desc_channel,descriptor); printf("Client disconnesso\n"); return QUIT_RET; } else if(buffer[0]=='n') break; } memset(buffer,0,sizeof(buffer)); snprintf(buffer,sizeof(buffer),"%s","Invalid input: choose between y or n!\n"); }while(1); } else { char buffer[BUFFER_SIZE]; snprintf(buffer,sizeof(buffer),"%s","You're the last active member. If you leave, the chat will be closed.\nDo you want to exit anyway? (y/n)\n"); do{ ret= send_message(descriptor,buffer,strlen(buffer)); ret= receive_message(descriptor,buffer); if(strlen(buffer)==1){ if(buffer[0]=='y'){ delete_channel(desc_channel,descriptor); return QUIT_RET; } else if(buffer[0]=='n'){ snprintf(buffer,sizeof(buffer),"%s","You're still in the chat.\n"); send_message(descriptor,buffer,strlen(buffer)); return 0; } } snprintf(buffer,sizeof(buffer),"%s","Invalid input: choose between y or n!\n"); }while(1); } } delete_user_from_channel(descriptor,desc_channel); char buff_leave[BUFFER_SIZE]; snprintf(buff_leave,sizeof(buff_leave),"%s","leave the chat"); send_all(desc_channel,user,buff_leave); } send_message(descriptor,QUIT_CLIENT,strlen(QUIT_CLIENT)); printf("Client disconnesso\n"); return QUIT_RET; } return -1; }
IResponse *GroupsService::index(IRequest *req) { int page; QSqlQuery query; if(!m_proxyConnection->session()->isLoggedIn()) req->response(IResponse::UNAUTHORIZED); QString user_id = m_proxyConnection->session()->value("logged").toString(); if ( req->hasParameter("page") ) { page= req->parameterValue("page").toInt(); query.prepare("SELECT * FROM groups ORDER BY name LIMIT :limit OFFSET :offset"); query.bindValue(":limit",PER_PAGE); query.bindValue(":offset", (page-1)* PER_PAGE); } else query.prepare("SELECT * FROM groups ORDER BY name"); if( query.exec()){ QVariantList groups; while(query.next()) { QVariantMap group; QString group_id = query.value(query.record().indexOf("id")).toString(); group.insert("id", query.value(query.record().indexOf("id"))); group.insert("name", query.value(query.record().indexOf("name"))); group.insert("description", query.value(query.record().indexOf("description"))); group.insert("has_password", query.value(query.record().indexOf("has_password"))); group.insert("has_approvement", query.value(query.record().indexOf("has_approvement"))); group.insert("date_created", query.value(query.record().indexOf("date_created"))); if(isAdmin(user_id.toUInt(), group_id.toUInt())) group.insert("admin","1"); else group.insert("admin","0"); //Check group membership QSqlQuery q_check; q_check.prepare("SELECT status FROM group_users WHERE user_id = :user_id AND group_id = :group_id"); q_check.bindValue(":user_id",user_id); q_check.bindValue(":group_id",group_id); q_check.exec(); if(!q_check.first()) group.insert("member","0"); else{ if(q_check.value(q_check.record().indexOf("status")).toString() == "1") group.insert("member","1"); else group.insert("member","awaiting"); } groups.append(group); } return req->response(QVariant(groups), IResponse::OK); } else return req->response(IResponse::INTERNAL_SERVER_ERROR); }
/** * \brief Function to add a new VISHNU user * \fn int add(UMS_Data::User*& user, int vishnuId) * \param user The user data structure * \param vishnuId The identifier of the vishnu instance * \param sendmailScriptPath The path to the script for sending emails * \return raises an exception on error */ int UserServer::add(UMS_Data::User*& user, int vishnuId, std::string sendmailScriptPath) { std::string pwd; std::string sqlUpdate = "update users set "; std::string idUserGenerated; std::string passwordCrypted; std::string formatiduser; if (exist()) { if (isAdmin()) { //Generation of password pwd = generatePassword(user->getLastname(), user->getFirstname()); user->setPassword(pwd.substr(0,PASSWORD_MAX_SIZE)); //Generation of userid idUserGenerated = vishnu::getObjectId(vishnuId, "formatiduser", USER, user->getLastname()); user->setUserId(idUserGenerated); //To get the password encrypted passwordCrypted = vishnu::cryptPassword(user->getUserId(), user->getPassword()); // If there only one field reserved by getObjectId if (getAttribut("where userid='"+user->getUserId()+"'","count(numuserid)") == "1") { //To active the user status user->setStatus(ACTIVE_STATUS); sqlUpdate+="vishnu_vishnuid="+convertToString(vishnuId)+", "; sqlUpdate+="pwd='"+passwordCrypted+"', "; sqlUpdate+="firstname='"+user->getFirstname()+"', "; sqlUpdate+="lastname='"+user->getLastname()+"', "; sqlUpdate+="privilege="+convertToString(user->getPrivilege())+", "; sqlUpdate+="email='"+user->getEmail()+"', "; sqlUpdate+="passwordstate=0, "; sqlUpdate+="status="+convertToString(user->getStatus())+" "; sqlUpdate+="where userid='"+user->getUserId()+"';"; mdatabaseVishnu->process(sqlUpdate); //Send email std::string emailBody = getMailContent(*user, true); sendMailToUser(*user, emailBody, "Vishnu message: user created", sendmailScriptPath); }// END If the user to add exists else { UMSVishnuException e (ERRCODE_USERID_EXISTING); throw e; } } //END if the user is an admin else { UMSVishnuException e (ERRCODE_NO_ADMIN); throw e; } } //END if the user exists else { UMSVishnuException e (ERRCODE_UNKNOWN_USER); throw e; } return 0; }//END: add(UMS_Data::User*& user)
IResponse * GroupsService::declineUser( IRequest *req) { bool ok = false; QVariantMap error; if(!m_proxyConnection->session()->isLoggedIn()) req->response(IResponse::UNAUTHORIZED); QString curUserId = m_proxyConnection->session()->value("logged").toString(); QVariantMap reqJson = req->postBodyFromJson(&ok).toMap(); if (!ok){ error.insert("parse_json","error"); return req->response(QVariant(error),IResponse::BAD_REQUEST); } QObject parent; bool missingValue = false; QString group_id = reqJson["group_id"].toString(); if(group_id == ""){ error.insert("group_id","required"); missingValue = true; } QString user_id = reqJson["user_id"].toString(); if(group_id == ""){ error.insert("user_id","required"); missingValue = true; } if(missingValue) return req->response(QVariant(error), IResponse::BAD_REQUEST); QSqlQuery q_check; q_check.prepare("SELECT status FROM group_users WHERE user_id = :user_id AND group_id = :group_id"); q_check.bindValue(":user_id",user_id); q_check.bindValue(":group_id",group_id); q_check.exec(); if(! (q_check.first() && q_check.value(q_check.record().indexOf("status")) == "0")){ error.insert("error", "group or user does not exist, or user is not awaiting for approvement"); return req->response(QVariant(error),IResponse::BAD_REQUEST); } if( isAdmin(curUserId.toUInt(), group_id.toUInt())) { IDatabaseUpdateQuery *q = m_proxyConnection->databaseUpdateQuery("group_users", &parent); q->setUpdateDates(true); // sam nastavi v tabulke datumy date_created a date_updated q->setType(IDatabaseUpdateQuery::Delete); IDatabaseSelectQueryWhereGroup *where = q->whereGroup(IDatabaseSelectQuery::And); where->where("user_id", user_id); where->where("group_id",group_id); if(!q->executeQuery()){ return req->response(IResponse::INTERNAL_SERVER_ERROR); } } else{ return req->response(IResponse::UNAUTHORIZED); } return req->response(IResponse::OK); }
/** * \brief Function to update user information * \fn int update(UMS_Data::User*& user) * \param user The user data structure * \return raises an exception on error */ int UserServer::update(UMS_Data::User *user) { std::string sqlCommand = ""; if (exist()) { if (isAdmin()) { //if the user whose information will be updated exists if (getAttribut("where userid='"+user->getUserId()+"'").size() != 0) { //if a new fisrtname has been defined if (user->getFirstname().size() != 0) { sqlCommand.append("UPDATE users SET firstname='"+user->getFirstname()+"'" " where userid='"+user->getUserId()+"';"); } //if a new lastname has been defined if (user->getLastname().size() != 0) { sqlCommand.append("UPDATE users SET lastname='"+user->getLastname()+"'" " where userid='"+user->getUserId()+"';"); } //if a new email has been defined if (user->getEmail().size() != 0) { sqlCommand.append("UPDATE users SET email='"+user->getEmail()+"'" " where userid='"+user->getUserId()+"';"); } //If a new status has been defined if (user->getStatus() != UNDEFINED_VALUE) { //if the user will be locked if (user->getStatus() == 0) { //if the user is not already locked if (convertToInt(getAttribut("where userid='"+user->getUserId()+"'", "status")) != 0) { sqlCommand.append("UPDATE users SET status="+convertToString(user->getStatus())+"" " where userid='"+user->getUserId()+"';"); } //End if the user is not already locked else { UMSVishnuException e (ERRCODE_USER_ALREADY_LOCKED); throw e; } } //End if the user will be locked else { sqlCommand.append("UPDATE users SET status="+convertToString(user->getStatus())+"" " where userid='"+user->getUserId()+"';"); } } // if the user whose privilege will be updated is not an admin if (convertToInt(getAttribut("where userid='"+user->getUserId()+"'", "privilege")) != 1) { sqlCommand.append("UPDATE users SET privilege="+convertToString(user->getPrivilege())+"" " where userid='"+user->getUserId()+"';"); } //If there is a change if (!sqlCommand.empty()) { mdatabaseVishnu->process(sqlCommand.c_str()); } } // End if the user whose information will be updated exists else { UMSVishnuException e (ERRCODE_UNKNOWN_USERID); throw e; } } //END if the user is an admin else { UMSVishnuException e (ERRCODE_NO_ADMIN); throw e; } } //END if the user exists else { UMSVishnuException e (ERRCODE_UNKNOWN_USER); throw e; } return 0; } //END: update(UMS_Data::User *user)
void KMessageClient::processMessage (const QByteArray &msg) { if (d->isLocked) { // must NOT happen, since we check in processIncomingMessage as well as in processFirstMessage d->delayedMessages.append(msg); return; } QBuffer in_buffer; in_buffer.setData(msg); in_buffer.open (QIODevice::ReadOnly); QDataStream in_stream (&in_buffer); bool unknown = false; quint32 messageID; in_stream >> messageID; switch (messageID) { case KMessageServer::MSG_BROADCAST: { quint32 clientID; in_stream >> clientID; emit broadcastReceived (in_buffer.readAll(), clientID); } break; case KMessageServer::MSG_FORWARD: { quint32 clientID; QList <quint32> receivers; in_stream >> clientID >> receivers; emit forwardReceived (in_buffer.readAll(), clientID, receivers); } break; case KMessageServer::ANS_CLIENT_ID: { bool old_admin = isAdmin(); quint32 clientID; in_stream >> clientID; d->connection->setId (clientID); if (old_admin != isAdmin()) emit adminStatusChanged (isAdmin()); } break; case KMessageServer::ANS_ADMIN_ID: { bool old_admin = isAdmin(); in_stream >> d->adminID; if (old_admin != isAdmin()) emit adminStatusChanged (isAdmin()); } break; case KMessageServer::ANS_CLIENT_LIST: { in_stream >> d->clientList; } break; case KMessageServer::EVNT_CLIENT_CONNECTED: { quint32 id; in_stream >> id; if (d->clientList.contains (id)) qCWarning(GAMES_PRIVATE_KGAME) << ": Adding a client that already existed!"; else d->clientList.append (id); emit eventClientConnected (id); } break; case KMessageServer::EVNT_CLIENT_DISCONNECTED: { quint32 id; qint8 broken; in_stream >> id >> broken; if (!d->clientList.contains (id)) qCWarning(GAMES_PRIVATE_KGAME) << ": Removing a client that doesn't exist!"; else d->clientList.removeAll (id); emit eventClientDisconnected (id, bool (broken)); } break; default: unknown = true; } if (!unknown && !in_buffer.atEnd()) qCWarning(GAMES_PRIVATE_KGAME) << ": Extra data received for message ID" << messageID; emit serverMessageReceived (msg, unknown); if (unknown) qCWarning(GAMES_PRIVATE_KGAME) << ": received unknown message ID" << messageID; }