void handle_user(int newfd) { current_user_t* loggedInUser = userLogin(newfd); int loggedIn = loggedInUser->loggedIn; if (loggedIn == 1) { userpw_t* User = loggedInUser->user; int option; do { option = receive_number(newfd); switch(option) { case 1: play_hangman(newfd, User); break; case 2: sendLeaderboard(newfd); break; default: option = 3; break; } // do things } while (option != 3); loggedIn = 0; } else { perror("User not logged in"); //exit(1); // user login failed } //return void; }
void MusicUserDialog::secondStatckWidget() { ui->registerUserLine->setStyleSheet(MusicUIObject::MLineEditStyle01); ui->registerMailLine->setStyleSheet(MusicUIObject::MLineEditStyle01); ui->registerPwdLine->setStyleSheet(MusicUIObject::MLineEditStyle01); ui->registerPwdCLine->setStyleSheet(MusicUIObject::MLineEditStyle01); ui->confirmButton->setStyleSheet(MusicUIObject::MPushButtonStyle08); ui->cancelButton->setStyleSheet(MusicUIObject::MPushButtonStyle08); ui->agreementButton->setStyleSheet(MusicUIObject::MPushButtonStyle09); ui->confirmButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->cancelButton->setCursor(QCursor(Qt::PointingHandCursor)); connect(ui->confirmButton, SIGNAL(clicked()), SLOT(checkRegisterUser())); connect(ui->cancelButton, SIGNAL(clicked()), SLOT(userLogin())); QRegExp userRx("[^\u4E00-\u9FA5]+$"); QRegExpValidator *valid = new QRegExpValidator(userRx, this); ui->registerUserLine->setValidator(valid); ui->registerMailLine->setValidator(valid); ui->registerPwdLine->setValidator(valid); ui->registerPwdCLine->setValidator(valid); ui->registerUserLine->setLabel(MusicUserLineEdit::User, ui->registerUserLineR, ui->labelRight); ui->registerMailLine->setLabel(MusicUserLineEdit::Mail, ui->registerMailLineR, ui->labelRigh_2); ui->registerPwdLine->setLabel(MusicUserLineEdit::Passwd, ui->registerPwdLineR, ui->labelRigh_3); ui->registerPwdCLine->setLabel(MusicUserLineEdit::PwdConfirm, ui->registerPwdCLineR, ui->labelRigh_4); }
char* parseClientUserLogin(int sock,void* buf,int serverid,char* drivceId,int* outResult){ uint16_t length = ntohs(*(uint16_t*)buf); buf += sizeof(uint16_t); char *txt = malloc(length); memcpy(txt,buf,length); buf += length; cJSON* json = cJSON_Parse(txt); if(!json){ free(txt); return NULL; } char* str = cJSON_GetObjectItem(json,"username")->valuestring; char* username = malloc(strlen(str)+1); strncpy(username,str,strlen(str)); #ifndef CLIENTMAKE user_info_t* clientinfo=NULL; user_info_t* uinfo = userLogin(username,drivceId,&clientinfo);//regUser(username,userid); int isSucess = 0; if(uinfo != NULL) isSucess = 1; *outResult = createServerUserLogin(sock,serverid,isSucess,username); //freeClientInfo(clientinfo); freeUserInfo(clientinfo); #endif free(txt); cJSON_Delete(json); return username; }
void clientMessageHandle(int client_sock,string message){ vector<string> choppedString; stringChopper(message,choppedString); if (choppedString[0].compare("LIN") == 0){ userLogin(client_sock,choppedString); } else if (choppedString[0].compare("LOU") == 0){ userLogout(client_sock,choppedString); } else if (choppedString[0].compare("REG") == 0){ userRegister(client_sock,choppedString); } else if (choppedString[0].compare("MSG") == 0){ sendMessage(client_sock,choppedString); } else if (choppedString[0].compare("CGR") == 0){ createGroup(client_sock,choppedString); } else if (choppedString[0].compare("JGR") == 0){ joinGroup(client_sock,choppedString); } else if (choppedString[0].compare("LGR") == 0){ leaveGroup(client_sock,choppedString); } else{ errorReply(client_sock,"000","Protocol error!"); } }
void SessionController::login() { if (httpRequest().method() != Tf::Post) { return; } QString password_md5; QByteArray bb; QString username = httpRequest().formItemValue("username"); QString password = httpRequest().formItemValue("password"); bb = QCryptographicHash::hash ( password.toLocal8Bit(), QCryptographicHash::Md5 ); password_md5.append(bb.toHex()); Admin admin = Admin::authenticate(username, password_md5); if(!admin.isNull()) { userLogin(&admin); redirect(QUrl("/admin/dashboard")); } else { QString message = "Login failed"; texport(message); redirect(url("session", "form")); } }
void MusicUserDialog::checkRegisterUser() { if( ui->registerUserLine->getStrStatus() && ui->registerMailLine->getMailStatus() && ui->registerPwdLine->getStrStatus() && ui->registerPwdCLine->getStrStatus() ) { if( ui->registerPwdLine->text() != ui->registerPwdCLine->text() ) { MusicMessageBox message; message.setText(tr("The two passwords do not match")); message.exec(); return; } if( !ui->agreementCheckBox->isChecked() ) { MusicMessageBox message; message.setText(tr("The agreement does not tick")); message.exec(); return; } if( !m_userModel->addUser(ui->registerUserLine->text(), ui->registerPwdLine->text(), ui->registerMailLine->text()) ) { MusicMessageBox message; message.setText(tr("The username is existed")); message.exec(); return; } MusicMessageBox message; message.setText(tr("The register successfully")); message.exec(); userLogin(); } else { MusicMessageBox message; message.setText(tr("You entered is incorrect")); message.exec(); } }
/* * 结构 : qint8(四种类型) + 数据 */ void MyServer::slotReadData(QByteArray data) { QDataStream out(&data,QIODevice::ReadOnly); out.setVersion(QDataStream::Qt_5_0); qint8 type; out>>type; data.remove(0,sizeof(qint8)); qDebug()<<"slotReadData = "<<type; if (type == queryType::login) { userLogin(data); } else if (type == queryType::registe) { userRegister(data); } else if (type == queryType::recommend) { userRecommend(data); } else if (type == queryType::groupsize) { DataFormat_login info = DataFormat::getGroupSize(data); QVector<groupInfo> groups = model.friendGroup(info.account); sendGroupSize(groups, clients[ hx[info.account] ]); } else if (type == queryType::friendGroup) { DataFormat_login info = DataFormat::getGroupSize(data); QVector<groupInfo> groups = model.friendGroup(info.account); sendFriendGroup(groups,clients[ hx[info.account] ]); } else if (type == queryType::addFriend) { userAddFriend(data); } else if (type == queryType::findPerson) { userFindPerson(data); } else if (type == queryType::chat) { userChat(data); } else if (type == queryType::offlineMes) { sendOfflineMes(data); } else if (type == queryType::history) { userHistoryChat(data); } }
// 运行客户端 void run(char* ip, char* pt) { int sockfd = connectToHost(ip, pt); if (getReplyCode(sockfd) != SERVICE_READY) errorReport("Service Connect Error!"); while (userLogin(sockfd) != 0) // 调用登录函数userLogin printf("Please try again.\n"); int isQuit = 0; char buf[BUF_SIZE]; while (!isQuit) { printf("[Client command] "); fgets(buf, sizeof(buf), stdin); switch (cmdToNum(buf)) { case GET: cmd_get(sockfd, buf); break; case PUT: cmd_put(sockfd, buf); break; case PWD: cmd_pwd(sockfd); break; case DIR: cmd_dir(sockfd); break; case CD: cmd_cd(sockfd, buf); break; case HELP: cmd_help(); break; case QUIT: cmd_quit(sockfd); isQuit = 1; break; default: cmd_help(); break; } } close(sockfd); }
void MusicUserDialog::checkUserForgotPasswd() { QString user = ui->userLineEdit->text(); QString mail = ui->mailLineEdit->text(); if( user.trimmed().isEmpty() || mail.trimmed().isEmpty() ) { MusicMessageBox message; message.setText(tr("You entered is incorrect")); message.exec(); return; } if( !m_userModel->mailCheck(user,mail) ) { MusicMessageBox message; message.setText(tr("You mail is incorrect or user is not exist")); message.exec(); return; } if( !ui->pwdLineEdit->getStrStatus() ) { MusicMessageBox message; message.setText(tr("You passwd is incorrect")); message.exec(); return; } if( ui->verificationCode->text() != ui->verificationCodeEdit->text().trimmed() ) { MusicMessageBox message; message.setText(tr("You verificationCode is incorrect")); message.exec(); return; } if( m_userModel->updateUser(user, ui->pwdLineEdit->text(), mail, QString(), QString())) { MusicMessageBox message; message.setText(tr("Change password successfully")); message.exec(); } userLogin(); }
void Auth::init() { QSqlDatabase db = QSqlDatabase::database ( m_db ); if ( !db.isOpen() ) return; QSqlQuery query = db.exec ( "SELECT Value from Config where Name='ZM_OPT_USE_AUTH'" ); query.next(); m_needAuth = query.value ( 0 ).toBool(); query.clear(); query = db.exec ( "SELECT Value from Config where Name='ZM_AUTH_RELAY'" ); query.next(); QString StringType = query.value ( 0 ).toString(); query.clear(); if ( StringType.toLower() == "hashed" ) m_AuthType = HASHED; else if ( StringType.toLower() == "plain" ) m_AuthType = PLAIN; else m_AuthType = NONE; loadSettings(); userLogin ( m_userName , m_password ); }
int main(int argc, char const *argv[]){ initSocket(); pthread_mutex_init(&mutexRefresh,NULL); pthread_mutex_init(&mutexLogout,NULL); sprintf(chatLog,""); userLogin(); printf("\nuser logged\n"); pthread_create(&thread_writer, &pthread_custom_attr, sendMessageToServer, (void*)0); pthread_create(&thread_reader, &pthread_custom_attr, readServerMessage, (void*)0); pthread_join(thread_writer, NULL); pthread_join(thread_reader, NULL); system("clear"); fprintf(stderr,"You are now offline!\n"); return 0; }
void MusicUserDialog::thirdStatckWidget() { ui->userLineEdit->setStyleSheet(MusicUIObject::MLineEditStyle01); ui->pwdLineEdit->setStyleSheet(MusicUIObject::MLineEditStyle01); ui->mailLineEdit->setStyleSheet(MusicUIObject::MLineEditStyle01); ui->verificationCodeEdit->setStyleSheet(MusicUIObject::MLineEditStyle01); ui->confirmButton_2->setStyleSheet(MusicUIObject::MPushButtonStyle08); ui->cancelButton_2->setStyleSheet(MusicUIObject::MPushButtonStyle08); ui->confirmButton_2->setCursor(QCursor(Qt::PointingHandCursor)); ui->cancelButton_2->setCursor(QCursor(Qt::PointingHandCursor)); connect(ui->confirmButton_2, SIGNAL(clicked()), SLOT(checkUserForgotPasswd())); connect(ui->cancelButton_2, SIGNAL(clicked()), SLOT(userLogin())); QRegExp userRx("[^\u4E00-\u9FA5]+$"); QRegExpValidator *valid = new QRegExpValidator(userRx, this); ui->userLineEdit->setValidator(valid); ui->pwdLineEdit->setValidator(valid); ui->mailLineEdit->setValidator(valid); ui->pwdLineEdit->setLabel(MusicUserLineEdit::Passwd, ui->pwdLineEditR, ui->labelRigh_5); ui->verificationCode->setStyleSheet(MusicUIObject::MPushButtonStyle10); connect(ui->verificationCode, SIGNAL(clicked()), SLOT(changeVerificationCode())); }
int main() { consoleTitleSet("Hafrans Flex LMS Alpha"); if (init()) { printf("程序出现错误,正在退出..."); Sleep(1500); return -255; } #ifdef DEBUG currentPer = 9; currentUsr = "******"; puts("/********************这是调试模式****************/"); #else while (currentUsr == NULL) { while (currentUsr == NULL) { char buf[__BUFFSIZE__] = { '\0' }; loginPageViewer(); printf("请输入选项: "); gets_s(buf, __BUFFSIZE__); if (strcmp(buf, "1") == 0) { userLogin(); } else if (strcmp(buf, "2") == 0) { userRegister(); flushUSER(0); } else if (strcmp(buf, "3") == 0) { printf("将要退出程序。。\n"); Sleep(1500); puts("正在退出..."); Sleep(1500); flushBOOK(0); flushUSER(0); return 0; } } mainLayoutViewer(); consoleWaitinCMD(); } #endif /*bookDetails(head); Sleep(1520); userDetails(uhead); puts("已到达函数底"); getchar();*/ #ifdef DEBUG /* 程序设置文档请写在此处。 */ pUSER *p = userSelect("2",1,1); currentBody = *p; puts("已到达程序底部"); getchar(); #endif /*冲刷数据*/ flushBOOK(0); flushUSER(0); //Sleep(1000); return 0; }
// Permite la ejecución de hilos void *worker_routine (void *arg) { std::string replyServer; Json::Value mensajeCliente; Json::Reader readerJson; // Para relizar conversiones de string a objeto Json std::string tipoObjeto; // Almacena el tipo de obejto std::string data; // std::string tipoObjetoRespuesta; // Se indica el tipo de respuesta que va a dar el servidor bool mensajeRecibido = false; std::string usuariosConectadosJson; // String para contener la posiciones de los usuarios time_t ahora,despues; // Control de actualización de juagdores conectados double tiempoSeg = 1000; // Tiempo entre actualizaciones en segundos double totalSeg; Login log("lixander","123434"); time(&ahora); // Toma la primera marca de tiempo struct recurso_t* contenedor_recursos = (struct recurso_t*) arg; zmq::context_t *context = contenedor_recursos->contex; zmq::socket_t socket (*context, ZMQ_REP); socket.connect ("inproc://workers"); while (true) { // Variable para almacenar el mensaje entrante zmq::message_t request; // Espera por algún mensaje de los usuarios socket.recv (&request); // Conversión de message_t a string std::string preJson = std::string(static_cast<char*>(request.data()), request.size()); std::cout << preJson << std::endl; // Se verifica que se realice correctamente la conversion de Json a Objeto Json if(!readerJson.parse(preJson,mensajeCliente)) { std::cout << "Error en la conversión de documento Json a Objeto Json\n" << readerJson.getFormattedErrorMessages(); // replyServer = "Error formato Json"; }else { // idObjeto contiene la indentificación de qué objeto debemos tratar tipoObjeto = mensajeCliente.get("idObjeto", "Not Found" ).asString(); // se obtiene el valor en la clave 'idObjeto' data = mensajeCliente.get("data", "Not Found" ).asString(); // se obtiene el valor en la clave 'data' if( tipoObjeto == "usuario"){ Usuario* user = new Usuario(&data); //Se crear el conjeto a partir del Json en formato String std::cout << "Usuario " << data << std::endl; if(!contenedor_recursos->manejador_juego->conectar(user)) { replyServer = "Sorry Full server"; }else{ // contenedor_recursos->manejador_juego->getUsuarioById(2); replyServer = "Conexión Exitosa"; } tipoObjetoRespuesta = "usuario"; }else if (tipoObjeto == "ataque"){ // contenedor_recursos->manejador_juego->atacarUsuario(); std::cout << "Ataque " << data << std::endl; Ataque atac(&data); contenedor_recursos->manejador_juego->atacarUsuario(&atac); std::cout << "Atacado ..." <<contenedor_recursos->manejador_juego->getUsuarioByIdJson(atac.getIdAtacado()) << std::endl; tipoObjetoRespuesta = "ataque"; }else if (tipoObjeto == "posUsuario"){ // Cuando el usuario envia su posición se le retorna las posiciones de los demás jugadores en formato Json // se crea objeto PosicionUsuario a partir del Json en formato string PosicionUsuario posUser(&data); // Se actuliza la posición del jugador que envia su posición contenedor_recursos->manejador_juego->actualizarPosicionUsuario(&posUser); // Se obtiene la lista de jugadores conectados en formato Json contenedor_recursos->manejador_juego->getUsuariosConectadosJson(&usuariosConectadosJson,posUser.getIdUsuario()); // La respueta del servidor al usuario que hizo la petición replyServer = usuariosConectadosJson; tipoObjetoRespuesta = "posiciones"; }else if (tipoObjeto == "login"){ Login logueandose(&data); tipoObjetoRespuesta = "login"; std::string respuestaLogin; std::cout << "login " << logueandose.getLoginJson() << std::endl; // Consumo de la API Rest CURL *curl; CURLcode res; std::string correo = logueandose.getCorreo(); std::string contrasena = logueandose.getContrasena(); std::string str = "email="+correo+"&password="******"email="+correo+"&password="******"https://jobboard-emmanuelhcpk.c9.io/api/v1/sessions"); /* Now specify the POST data */ std::cout << "Send post" << c << std::endl; curl_easy_setopt(curl, CURLOPT_POSTFIELDS, c); // std::cout << "------------1-----------" << std::endl; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); // std::cout << "------------2-----------" << std::endl; /* Check for errors */ if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); /* always cleanup */ curl_easy_cleanup(curl); } curl_global_cleanup(); respuestaLogin = response.str(); std::cout << "Get post..." << respuestaLogin << std::endl; std::string dato = logueandose.confirmarConexion(&respuestaLogin); if(dato == "NULL") { replyServer == "Error Login"; }else{ Usuario userLogin(&dato); std::cout << "Usuario conectado se " << std::endl; if(!contenedor_recursos->manejador_juego->conectar(&userLogin)) { replyServer = "Sorry Full server"; }else{ // contenedor_recursos->manejador_juego->getUsuarioById(2); userLogin.usuarioToJson(&replyServer); } } }else{ std::cout << "Json sin identificacion de Objeto "<< std::endl; tipoObjetoRespuesta = "error"; // replyServer = log.getLoginJson(); // std::cout << " log" << replyServer << std::endl; } } // Encapsula el mensaje en 'idObjeto'='','data'='todos los que se quiere enviar' enviarObjetoCliente(&socket, tipoObjetoRespuesta, &replyServer); std::cout << "Total Conectados: " << contenedor_recursos->manejador_juego->getTotalConectados()<< std::endl; // std::cout << "Total Conectados: " << contenedor_recursos->manejador_juego->maximoConectados<< std::endl; } return (NULL); }