示例#1
0
    // this method is called when REST response is received for request to get user information:
    void handleMe(boost::system::error_code err, const Http::Message& response)
    {
#ifndef WT_TARGET_JAVA
      WApplication::instance()->resumeRendering();
#endif

      if (!err && response.status() == 200) {
#ifndef WT_TARGET_JAVA
        Json::ParseError e;
        Json::Object me;
        bool ok = Json::parse(response.body(), me, e);
#else
        Json::Object me;
        try {
	         me = (Json::Object)Json::Parser().parse(response.body());
        } 
        catch (Json::ParseError pe) {
        }
        bool ok = me.isNull();
#endif

        if (!ok) {
	        LOG_ERROR("could not parse JSON: '" << response.body() << "'");
	        setError(ERROR_MSG("badjson"));
	        authenticated().emit(Identity::Invalid);
        } 
        else {
	        std::string id = me.get("id");
          std::string email = me.get("emailAddress");
          
          if (getUserProfileAsJson)
          {
            // In the Identity's name field more complete user info is passed in JSON format as returned from LinkedIn, see details at:
            // https://developer.linkedin.com/docs/fields/basic-profile
            authenticated().emit(Identity(service().name(), id, response.body(), email, true));
          }
          else
          {
            std::string name = me.get("firstName");
            name += std::string(" ");
            name += std::string(me.get("lastName"));
            authenticated().emit(Identity(service().name(), id, name, email, true));
          }
        }
      } 
      else {
        if (!err) {
	        LOG_ERROR("user info request returned: " << response.status());
	        LOG_ERROR("with: " << response.body());
        } 
        else {
          LOG_ERROR("handleMe(): " << err.message());
        }
        setError(ERROR_MSG("badresponse"));
        authenticated().emit(Identity::Invalid);
      }
    }
示例#2
0
文件: main.c 项目: allewwaly/exploits
static void	auth_global()
{
	if (!authenticated()) {
		if (sk_auth(getpassw(SKPROMPT))) {
			eprintf("Go away with that, poor boy!\n");
			exit(1);
		}
	}
	eprintf("%s", BANNER);
	eprintf("Kernel side version: %s\n", authenticated());
}
示例#3
0
void LastFm::authenticationResponse(QByteArray bytes) {
    QXmlStreamReader xml(bytes);

    while(!xml.atEnd() && !xml.hasError()) {
        QXmlStreamReader::TokenType token = xml.readNext();

        if(token == QXmlStreamReader::StartElement && xml.name() == "session") {
            while (xml.readNextStartElement()) {
                if (xml.name() == "name") {
                    username = xml.readElementText();
                } else if (xml.name() == "key") {
                    sessionKey = xml.readElementText();
                }
            }
        }

    }

    if(xml.hasError()) {
        qWarning() << xml.errorString();
        emit error(xml.errorString());
    }

    if (!sessionKey.isEmpty()) {
        QSettings settings;
        settings.setValue("lastFmSessionKey", sessionKey);
        emit authenticated();
    } else qDebug() << "Missing sessionKey";

}
void AuthenticationDialog::urlChanged(const QUrl &url)
{
    qDebug() << "Navigating to" << url;
    if (url.host() == QStringLiteral("oauth.vk.com") && url.path() == QStringLiteral("/blank.html"))
    {
        const QUrlQuery query(url);

        d->error = query.queryItemValue(QStringLiteral("error"));
        d->errorDescription = query.queryItemValue(QStringLiteral("error_description")).replace(QLatin1Char('+'), QLatin1Char(' '));
        if (!d->error.isEmpty() || !d->errorDescription.isEmpty())
        {
            QTimer::singleShot(0, this, SLOT(showErrorDialog()));
            return;
        }

        // The URL comes in the form "bla#access_token=bla&expires_in=foo", we need to convert from
        // # to ?
        const QUrl fixedURL = QUrl::fromUserInput(url.toString().replace(QLatin1Char('#'), QLatin1Char('?')));
        const QUrlQuery fixedQuery(fixedURL);
        const QString accessToken = fixedQuery.queryItemValue(QStringLiteral("access_token"));
        const QString tokenExpiresIn = fixedQuery.queryItemValue(QStringLiteral("expires_in")); // TODO: use this for something?
        if (!accessToken.isEmpty())
        {
            emit authenticated(accessToken);
            QTimer::singleShot(0, this, SLOT(close()));
        }
    }
}
示例#5
0
	ClientTest(const QString &_host, int _port, const QString &_proto, const QString &_authzid, const QString &_realm, const QString &_user, const QString &_pass, bool _no_authzid, bool _no_realm) :
		host(_host),
		proto(_proto),
		authzid(_authzid),
		realm(_realm),
		user(_user),
		pass(_pass),
		port(_port),
		no_authzid(_no_authzid),
		no_realm(_no_realm),
		sock_done(false),
		waitCycles(0)
	{
		sock = new QTcpSocket(this);
		connect(sock, SIGNAL(connected()), SLOT(sock_connected()));
		connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
		connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(sock_error(QAbstractSocket::SocketError)));

		sasl = new QCA::SASL(this);
		connect(sasl, SIGNAL(clientStarted(bool, const QByteArray &)), SLOT(sasl_clientFirstStep(bool, const QByteArray &)));
		connect(sasl, SIGNAL(nextStep(const QByteArray &)), SLOT(sasl_nextStep(const QByteArray &)));
		connect(sasl, SIGNAL(needParams(const QCA::SASL::Params &)), SLOT(sasl_needParams(const QCA::SASL::Params &)));
		connect(sasl, SIGNAL(authenticated()), SLOT(sasl_authenticated()));
		connect(sasl, SIGNAL(readyRead()), SLOT(sasl_readyRead()));
		connect(sasl, SIGNAL(readyReadOutgoing()), SLOT(sasl_readyReadOutgoing()));
		connect(sasl, SIGNAL(error()), SLOT(sasl_error()));
	}
示例#6
0
 Mail::Mail()
     : CodeClass()
 {
     connect(&mSmtp, SIGNAL(connected()), this, SLOT(connected()));
     connect(&mSmtp, SIGNAL(connectionFailed(QByteArray)), this, SLOT(connectionFailed(QByteArray)));
     connect(&mSmtp, SIGNAL(encrypted()), this, SLOT(encrypted()));
     connect(&mSmtp, SIGNAL(encryptionFailed(QByteArray)), this, SLOT(encryptionFailed(QByteArray)));
     connect(&mSmtp, SIGNAL(authenticated()), this, SLOT(authenticated()));
     connect(&mSmtp, SIGNAL(authenticationFailed(QByteArray)), this, SLOT(authenticationFailed(QByteArray)));
     connect(&mSmtp, SIGNAL(senderRejected(int,QString,QByteArray)), this, SLOT(senderRejected(int,QString,QByteArray)));
     connect(&mSmtp, SIGNAL(recipientRejected(int,QString,QByteArray)), this, SLOT(recipientRejected(int,QString,QByteArray)));
     connect(&mSmtp, SIGNAL(mailFailed(int,int,QByteArray)), this, SLOT(mailFailed(int,int,QByteArray)));
     connect(&mSmtp, SIGNAL(mailSent(int)), this, SLOT(mailSent(int)));
     connect(&mSmtp, SIGNAL(finished()), this, SLOT(finished()));
     connect(&mSmtp, SIGNAL(disconnected()), this, SLOT(disconnected()));
 }
示例#7
0
    QScriptValue Mail::waitForAuthenticated(int waitTime)
    {
        QxtSignalWaiter waiter(&mSmtp, SIGNAL(authenticated()));
        if(!waiter.wait(waitTime))
            throwError("AuthenticationError", tr("Cannot authenticate to the server"));

        return thisObject();
    }
示例#8
0
  void handleMe(boost::system::error_code err, const Http::Message& response)
  {
#ifndef WT_TARGET_JAVA
    WApplication::instance()->resumeRendering();
#endif

    if (!err && response.status() == 200) {
#ifndef WT_TARGET_JAVA
      Json::ParseError e;
      Json::Object me;
      bool ok = Json::parse(response.body(), me, e);
#else
      Json::Object me;
      try {
	me = (Json::Object)Json::Parser().parse(response.body());
      } catch (Json::ParseError pe) {
      }
      bool ok = me.isNull();
#endif

      if (!ok) {
	LOG_ERROR("could not parse Json: '" << response.body() << "'");
	setError(ERROR_MSG("badjson"));
	authenticated().emit(Identity::Invalid);
      } else {
	std::string id = me.get("id");
	WT_USTRING userName = me.get("name");
	std::string email = me.get("email").orIfNull("");
        bool emailVerified = !me.get("email").isNull();

	authenticated().emit(Identity(service().name(), id, userName,
				      email, emailVerified));
      }
    } else {
      if (!err) {
	LOG_ERROR("user info request returned: " << response.status());
	LOG_ERROR("with: " << response.body());
      } else
	LOG_ERROR("handleMe(): " << err.message());

      setError(ERROR_MSG("badresponse"));

      authenticated().emit(Identity::Invalid);
    }
  }
	PendingRecommendedArtists::PendingRecommendedArtists (Authenticator *auth,
			QNetworkAccessManager *nam, int num, QObject *obj)
	: BaseSimilarArtists (QString (), num, obj)
	, NAM_ (nam)
	{
		if (auth->IsAuthenticated ())
			request ();
		else
			connect (auth,
					SIGNAL (authenticated ()),
					this,
					SLOT (request ()));
	}
示例#10
0
	RecEventsFetcher::RecEventsFetcher (Authenticator *auth, QNetworkAccessManager *nam, Type type, QObject *parent)
	: QObject (parent)
	, NAM_ (nam)
	, Type_ (type)
	{
		if (auth->IsAuthenticated ())
			request ();
		else
			connect (auth,
					SIGNAL (authenticated ()),
					this,
					SLOT (request ()));
	}
示例#11
0
void UBAbstractPublisher::processAuthenticationTokenResponse(bool success, const QByteArray& payload)
{
    if (mTokenRequest)
        mTokenRequest->deleteLater();

    if (success)
    {
        /*
          <publishing-token>
            ...
            <token>iFzZIXhPxHTLhJeHWFF9BDVblMDWU546rpzoEEfxMSLrftMq444w4BuoisnNtRAjm6ht3hKUIHmMKA3xGN2Hlaof8tbYNLHmzf2R1dO439vnXFiHMPLBi7nFpSEPtBNJ</token>
            <uuid>26fea4c0-1319-012d-d0fc-001f5b3d920c</uuid>
            ...
          </publishing-token>
        */

        QDomDocument doc("publishing-token");
        doc.setContent(payload, false);

        QDomElement root = doc.documentElement();

        const QString token = root.firstChildElement("token").text();
        const QString uuid = root.firstChildElement("uuid").text();

        if (token.length() > 0 && uuid.length() > 0)
        {
            const QByteArray encrypted = encrypt(token);
            QString encryptedBase64 = QString::fromAscii(encrypted.toBase64());

            UBApplication::showMessage(tr("Found %1").arg(UBSettings::settings()->uniboardWebUrl->get().toString()), false);

            emit authenticated(QUuid(uuid), encryptedBase64);
        }
        else
        {
            qWarning() << "Authentication failed" << QString::fromUtf8(payload);

            emit authenticationFailure();

            UBApplication::showMessage(tr("Cannot Authenticate with %1").arg(UBSettings::settings()->uniboardWebUrl->get().toString()));
        }
    }
    else
    {
        qWarning() << "Authentication failed" << QString::fromUtf8(payload);

        emit authenticationFailure();

        UBApplication::showMessage(tr("Cannot Authenticate with %1").arg(UBSettings::settings()->uniboardWebUrl->get().toString()));
    }
}
示例#12
0
    void HelperApp::doAuth() {
        SafeDataStream str(m_socket);
        str << Msg::HELLO << m_id;
        str.send();
        if (str.status() != QDataStream::Ok)
            qCritical() << "Couldn't write initial message:" << str.status();

        if (!m_backend->start(m_user)) {
            authenticated(QString(""));
            exit(Auth::HELPER_AUTH_ERROR);
            return;
        }

        if (!m_backend->authenticate()) {
            authenticated(QString(""));
            exit(Auth::HELPER_AUTH_ERROR);
            return;
        }

        m_user = m_backend->userName();
        QProcessEnvironment env = authenticated(m_user);

        if (!m_session->path().isEmpty()) {
            env.insert(m_session->processEnvironment());
            m_session->setProcessEnvironment(env);

            if (!m_backend->openSession()) {
                sessionOpened(false);
                exit(Auth::HELPER_SESSION_ERROR);
                return;
            }

            sessionOpened(true);
        }
        else
            exit(Auth::HELPER_SUCCESS);
        return;
    }
示例#13
0
NXClientLib::NXClientLib(QObject *parent) : QObject(parent)
{
	isFinished = false;
	proxyData.encrypted = false;
	password = false;
	
	connect(&session, SIGNAL(authenticated()), this, SLOT(doneAuth()));
	connect(&session, SIGNAL(loginFailed()), this, SLOT(failedLogin()));
	connect(&session, SIGNAL(finished()), this, SLOT(finished()));
	connect(&session, SIGNAL(sessionsSignal(QList<NXResumeData>)), this, SLOT(suspendedSessions(QList<NXResumeData>)));
	connect(&session, SIGNAL(noSessions()), this, SLOT(noSuspendedSessions()));
	
	connect(&nxproxyProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(reset()));
}
示例#14
0
bool CreateGameHandler::handle(CMSGCreateGame *p)
{
  auto client = std::dynamic_pointer_cast<Client > (p->source());
  if (!client)
    {
      WARN("NO SOURCE TO CREATE GAME");
      return true;
    }
  auto response = std::make_shared<SMSGCreateGame > (p->source());

  if (!client->authenticated())
    {
      response->data_.set_success(false);
      response->data_.set_errormsg("You are not authenticated so you cannot create a new game.");
      client->pushPacket(response);
      return true;
    }

  if (p->data_.gamename() == "")
    {
      response->data_.set_success(false);
      response->data_.set_errormsg("Name cannot be empty;");
    }

  for (auto game : Server::instance().games())
    {
      if (game->name() == p->data_.gamename())
        {
          WARN("Game with is name already exists, not creating");
          response->data_.set_success(false);
          response->data_.set_errormsg("Name already taken.");
          p->source()->pushPacket(response);
          return true;
        }
    }

  std::string sceneName;
  if (p->data_.has_scenename())
    sceneName = p->data_.scenename();
  else
    sceneName = "Test Level";
  
  std::shared_ptr<Game> g(new Game(sceneName));
  g->name(p->data_.gamename());
  response->data_.set_success(true);
  response->data_.set_gameuuid(g->uuid());
  p->source()->pushPacket(response);
  Server::instance().addGame(g);
  return true;
}
示例#15
0
Rotor::Rotor(QSettings *settings, RotorButtons *buttons,QWidget *parent)
    : QWidget(parent)
{
	this->settings = settings;
	this->buttons = buttons;

	// Update timer
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(fetchStatus()));
    timer->start(1000*settings->value("System/statusInterval",300).toInt());

    dir = -1;
    aim = -1;

	// Buttons init
	connect(buttons,SIGNAL(goButtonPressed(int)),this,SLOT(goAntenna(int)));
	connect(buttons,SIGNAL(gotoButtonPressed(int)),this,SLOT(aimAntenna(int)));
	connect(buttons,SIGNAL(stopButtonPressed()),this,SLOT(stopAntenna()));

	// MMQ Init
    mmq = new MMQ(this);
    connect(mmq, SIGNAL(connected()),this, SLOT(connected()));
    connect(mmq, SIGNAL(authenticated()),this, SLOT(authenticated()));
    connect(mmq, SIGNAL(packet(QString,QJsonValue)),this, SLOT(packet(QString,QJsonValue)));
    connect(mmq, SIGNAL(disconnected()),this, SLOT(disconnected()));
    connect(mmq, SIGNAL(error(qint64)),this, SLOT(error(qint64)));

    mmq->setKey(settings->value("System/password").toString());
    mmq->doConnect(
			settings->value("System/hostname",QString("localhost")).toString(),
			settings->value("System/port",4343).toInt());
 
	// Load rotor Image
    rotorImg = QImage(settings->value("System/backgroundImage",QString("rotor.png")).toString());
    Q_ASSERT(!img.isNull());
}
示例#16
0
文件: main.c 项目: allewwaly/exploits
static	void	auth_local()
{
	if (!authenticated()) {
		char	*p;
		uchar	h[20];
		p = getpassw(SKPROMPT);
		sha1_asm(h, p, strlen(p));
		if (memcmp(cfg.hashpass, h, 20)) {
			eprintf("Go away with that, poor boy!\n");
			exit(1);
		}
		eprintf("%s", BANNER);
		sk_auth(p);
	}
}
示例#17
0
/**
 * @brief libmicrohttpd_cb called when the client do a request to this server
 * @param cls unused
 * @param connection - client connection
 * @param url - which url was called
 * @param method - POST / GET / ...
 * @param version http 1.0 or 1.1
 * @param upload_data - unused
 * @param upload_data_size - unused
 * @param ptr - unused
 * @return
 */
int
libmicrohttpd_cb(void *cls,
				 struct MHD_Connection *connection,
				 const char *url,
				 const char *method,
				 const char *version,
				 const char *upload_data, size_t *upload_data_size, void **ptr)
{

	t_client *client;
	char *ip_addr;
	char *mac;
	int ret;

	debug(LOG_DEBUG, "access: %s %s", method, url);

	/* only allow get */
	if(0 != strcmp(method, "GET")) {
		debug(LOG_DEBUG, "Unsupported http method %s", method);
		return send_error(connection, 503);
	}

	/* switch between preauth, authenticated */
	/* - always - set caching headers
	 * a) possible implementation - redirect first and serve them using a tempo redirect
	 * b) serve direct
	 * should all requests redirected? even those to .css, .js, ... or respond with 404/503/...
	 */

	ip_addr = get_ip(connection);
	mac = arp_get(ip_addr);

	client = client_list_find(ip_addr, mac);
	if(client) {
		if(client->fw_connection_state == FW_MARK_AUTHENTICATED ||
				client->fw_connection_state == FW_MARK_TRUSTED) {
			/* client already authed - dangerous!!! This should never happen */
			ret = authenticated(connection, ip_addr, mac, url, client);
			free(mac);
			free(ip_addr);
			return ret;
		}
	}
	ret = preauthenticated(connection, ip_addr, mac, url, client);
	free(mac);
	free(ip_addr);
	return ret;
}
示例#18
0
void AMGithubManager::onAuthenicatedRequestReturned(){
	QJson::Parser parser;
	QVariant githubFullReply = parser.parse(authenticateReply_->readAll());
	authenticated_ = false;
	if(githubFullReply.canConvert(QVariant::Map)){
		QVariantMap jsonMap = githubFullReply.toMap();
		QMap<QString, QVariant>::const_iterator i = jsonMap.constBegin();
		if(i.key() == "message" && i.value().toString() == "Bad credentials")
			authenticated_ = false;
		else
			authenticated_ = true;
	}
	disconnect(authenticateReply_, 0);
	authenticateReply_->deleteLater();
	authenticateReply_ = 0;
	emit authenticated(authenticated_);
}
示例#19
0
	void Plugin::Init (ICoreProxy_ptr proxy)
	{
		Util::InstallTranslator ("lastfmscrobble");

		Proxy_ = proxy;
		XmlSettingsDialog_.reset (new Util::XmlSettingsDialog ());
		XmlSettingsDialog_->RegisterObject (&XmlSettingsManager::Instance (),
				"lastfmscrobblesettings.xml");

		Auth_ = new Authenticator (proxy->GetNetworkAccessManager (), proxy, this);

		LFSubmitter_ = new LastFMSubmitter (Proxy_->GetNetworkAccessManager (), this);

		connect (Auth_,
				SIGNAL (authenticated ()),
				LFSubmitter_,
				SLOT (handleAuthenticated ()));

		RadioRoot_ = new QStandardItem ("Last.FM");
		RadioRoot_->setEditable (false);
		RadioRoot_->setIcon (QIcon (":/resources/images/lastfm.png"));
		auto addPredefined = [this] (const QString& name, const QString& id, const QIcon& icon) -> QStandardItem*
		{
			auto item = new QStandardItem (name);
			item->setData (Media::RadioType::Predefined, Media::RadioItemRole::ItemType);
			item->setData (id, Media::RadioItemRole::RadioID);
			item->setEditable (false);
			item->setIcon (icon);
			RadioRoot_->appendRow (item);
			return item;
		};
		addPredefined (tr ("Library"), "library", QIcon (":/resources/images/personal.png"));
		addPredefined (tr ("Recommendations"), "recommendations", QIcon (":/resources/images/recs.png"));
		addPredefined (tr ("Loved"), "loved", QIcon (":/resources/images/loved.png"));
		addPredefined (tr ("Neighbourhood"), "neighbourhood", QIcon (":/resources/images/neighbours.png"));

		auto similarItem = addPredefined (tr ("Similar artists"),
				QString (), QIcon (":/resources/images/radio.png"));
		similarItem->setData (Media::RadioType::SimilarArtists, Media::RadioItemRole::ItemType);
		auto globalItem = addPredefined (tr ("Global tag"),
				QString (), QIcon (":/resources/images/tag.png"));
		globalItem->setData (Media::RadioType::GlobalTag, Media::RadioItemRole::ItemType);;

		RadioModel_ = new QStandardItemModel;
		RadioModel_->appendRow (RadioRoot_);
	}
示例#20
0
void GoogleSession::authResult(bool errorFlag)
{
    if (errorFlag)
    {
      qDebug() << "Auth http error" << http->errorString();
      setState(Invalid);
      emit error(AuthenticationFailed, http->errorString());
    }
    else
    {
      QString resp = http->readAll(); 
      //qDebug() << resp;
      QStringList keys = resp.split("\n");
      QHash<QString, QString> keyMap;
      for (QStringList::iterator it = keys.begin(); it!=keys.end(); it++)
      {
        int sep = it->indexOf('=');
        QString key = it->left(sep);
        QString value = it->right(it->length()-sep-1);
        keyMap[key] = value;
        //qDebug() << key << value;
      }
      if (http->lastResponse().statusCode()==200) // OK
      {
        if (keyMap.contains("Auth"))
        {
          authKey = keyMap["Auth"];
          qDebug() << "Authenticated" << authKey;
          setState(Authenticated);
          emit authenticated();
        }
        else
        {
          setState(Invalid);
          emit error(AuthenticationFailed, "No Auth key");
        }
      }
      else
      {
        qDebug() << "ERROR Response header:" << http->lastResponse().statusCode() << http->lastResponse().reasonPhrase();
        qDebug() << "ERROR reason" << keyMap["Error"];
        setState(Invalid);
        emit error(AuthenticationFailed, keyMap["Error"]);
      }
    }
}
示例#21
0
QxtSmtp::QxtSmtp(QObject* parent) : QObject(parent)
{
    QXT_INIT_PRIVATE(QxtSmtp);
    qxt_d().state = QxtSmtpPrivate::Disconnected;
    qxt_d().nextID = 0;
#ifndef QT_NO_OPENSSL
    qxt_d().socket = new QSslSocket(this);
    QObject::connect(socket(), SIGNAL(encrypted()), this, SIGNAL(encrypted()));
    //QObject::connect(socket(), SIGNAL(encrypted()), &qxt_d(), SLOT(ehlo()));
#else
    qxt_d().socket = new QTcpSocket(this);
#endif
    QObject::connect(socket(), SIGNAL(connected()), this, SIGNAL(connected()));
    QObject::connect(socket(), SIGNAL(disconnected()), this, SIGNAL(disconnected()));
    QObject::connect(socket(), SIGNAL(error(QAbstractSocket::SocketError)), &qxt_d(), SLOT(socketError(QAbstractSocket::SocketError)));
    QObject::connect(this, SIGNAL(authenticated()), &qxt_d(), SLOT(sendNext()));
    QObject::connect(socket(), SIGNAL(readyRead()), &qxt_d(), SLOT(socketRead()));
}
void SmppClient::handleBindTransiverResp(const QByteArray &pdu)
{
    Smpp::BindTransceiverResp bindTransceiverResp;
    try {
        bindTransceiverResp.decode((const Smpp::Uint8 *) pdu.data());
    } catch (Smpp::Error e) {
        printErrorAndDisconnect(e);
        return;
    }
    if (bindTransceiverResp.command_status() != 0) {
        m_needInformAbountDisconnect = false;
        onDisconnectHelper();
        emit disconnected(AuthenticationProblem);
        logMsg("Authentication problem");
    } else {
        logMsg("Authentication on smpp server passed");
        emit authenticated();
        m_timerForEnquireLink->start();
    }
}
void LYGithubManager::onAuthenicatedRequestReturned(){
	QJson::Parser parser;
	QVariant githubFullReply = parser.parse(authenticateReply_->readAll());
	authenticated_ = false;
	if(githubFullReply.canConvert(QVariant::Map)){
		QVariantMap jsonMap = githubFullReply.toMap();
		QMap<QString, QVariant>::const_iterator i = jsonMap.constBegin();
		if(i.key() == "message" && i.value().toString() == "Bad credentials")
			authenticated_ = false;
		else
			authenticated_ = true;
	}

	LYGithubProductBacklogStatusLog::statusLog()->appendStatusMessage(QString("Received authentication request return as %1").arg(authenticated_));

	disconnect(authenticateReply_, 0);
	authenticateReply_->deleteLater();
	authenticateReply_ = 0;
	emit authenticated(authenticated_);
}
示例#24
0
	void Authenticator::getSessionKey ()
	{
		QNetworkReply *reply = qobject_cast<QNetworkReply*> (sender ());
		if (!reply)
			return;

		reply->deleteLater ();
		QDomDocument doc;
		doc.setContent (QString::fromUtf8 (reply->readAll ()));
		if (CheckError (doc))
			return;

		const auto& domList = doc.documentElement ().elementsByTagName ("key");
		if (!domList.size ())
			return;

		IsAuthenticated_ = true;

		lastfm::ws::SessionKey = domList.at (0).toElement ().text ();
		emit authenticated ();
	}
示例#25
0
void YouTubeProvider::parserFinished(Joschy::AbstractJob *job)
{

    JOSCHY_DEBUG() << "parser finsihed....";

    Joschy::ResponseParser *parser = static_cast<Joschy::ResponseParser*>(job);
    const QString id = parser->id();
    const ResponseParser::Type type = m_actions.take(id);
    const QString errorString = parser->errorString();
    const Plugin::ErrorType errorType = parser->errorType();
    const bool hasError = parser->error();


    if (hasError) {
        emit error(id, errorType, errorString);
    } else {
        switch (type) {
        case ResponseParser::AuthenticationType: {
                m_tokens.insert(parser->login(), parser->token());
                emit authenticated(id);
                break;
            }
        case ResponseParser::UploadType: {
                emit uploadFinished(id, parser->getVideo());
                break;
            }
        case ResponseParser::SearchType: {
                QList<Joschy::Video> videos = parser->getVideos();
                emit searchFinished(id, videos);
                break;
            }
        case ResponseParser::UpdateThumbnailType: {
                const QString thumbnail = m_thumbnails.take(id);

                QFile file(thumbnail);
                if (!file.open(QIODevice::WriteOnly)) {
                    JOSCHY_DEBUG() << "open failed:" << thumbnail << file.errorString();
                    emit error(id, Plugin::CannotOpenError, file.errorString());
                } else {
                    if (file.write(parser->image()) == -1) {
                        file.close();
                        JOSCHY_DEBUG() << file.error() << file.errorString();
                        emit error(id, Plugin::UnknownError, file.errorString());
                    } else {
                        file.close();
                        emit thumbnailUpdated(id);
                    }
                }
                break;
            }
        case ResponseParser::UpdateCategorysType: {
                m_categorys = parser->getCategorys();

                QHash<QString, QVariant> hash;
                QHashIterator<QString, QString> it(m_categorys);
                while (it.hasNext()) {
                    it.next();
                    hash[it.key()] = it.value();
                }

                save("YouTube-Categorys", QVariant(hash));
                save("YouTube-CategoryDate", QVariant(QDateTime::currentDateTime()));

                emit categorysChanged(categorys());
                break;
            }
        default: break;
        }
    }
    m_parser.removeAll(parser);
    delete parser;
    layer()->freeId(id);

}
示例#26
0
void CloudAuthenticator::replyFinished(QNetworkReply *reply)
{
    int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    // token request
    if (m_tokenRequests.contains(reply)) {

        QByteArray data = reply->readAll();
        m_tokenRequests.removeAll(reply);

        if (reply->error() != QNetworkReply::NoError) {
            qCWarning(dcCloud()) << "Authenticator: Request token reply error:" << status << reply->errorString();            
            m_error = Cloud::CloudErrorIdentityServerNotReachable;
            setAuthenticated(false);
            reply->deleteLater();
            return;
        }

        // check HTTP status code
        if (status != 200) {
            qCWarning(dcCloud()) << "Authenticator: Request token reply HTTP error:" << status << reply->errorString();
            qCWarning(dcCloud()) << data;
            m_error = Cloud::CloudErrorAuthenticationFailed;
            setAuthenticated(false);
            reply->deleteLater();
            return;
        }

        // check JSON
        QJsonParseError error;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);
        if (error.error != QJsonParseError::NoError) {
            qCWarning(dcCloud()) << "Authenticator: Request token reply JSON error:" << error.errorString();
            m_error = Cloud::CloudErrorAuthenticationFailed;
            setAuthenticated(false);
            reply->deleteLater();
            return;
        }

        if (!jsonDoc.toVariant().toMap().contains("access_token")) {
            qCWarning(dcCloud()) << "Authenticator: Could not get access token" << jsonDoc.toJson();
            m_error = Cloud::CloudErrorAuthenticationFailed;
            setAuthenticated(false);
            reply->deleteLater();
            return;
        }

        m_error = Cloud::CloudErrorNoError;
        setToken(jsonDoc.toVariant().toMap().value("access_token").toString());
        setAuthenticated(true);

        // Save the username
        GuhSettings settings(GuhSettings::SettingsRoleDevices);
        settings.beginGroup("Cloud");
        settings.setValue("userName", m_username);
        settings.endGroup();

        if (jsonDoc.toVariant().toMap().contains("expires_in") && jsonDoc.toVariant().toMap().contains("refresh_token")) {
            int expireTime = jsonDoc.toVariant().toMap().value("expires_in").toInt();
            setRefreshToken(jsonDoc.toVariant().toMap().value("refresh_token").toString());
            qCDebug(dcCloud()) << "Authenticator: Token will be refreshed in" << expireTime << "[s]";
            m_timer->start((expireTime - 20) * 1000);
        }

    } else if (m_refreshTokenRequests.contains(reply)) {

        QByteArray data = reply->readAll();
        m_refreshTokenRequests.removeAll(reply);

        if (reply->error() != QNetworkReply::NoError) {
            qCWarning(dcCloud()) << "Authenticator: Request token reply error:" << status << reply->errorString();
            m_error = Cloud::CloudErrorIdentityServerNotReachable;
            setAuthenticated(false);
            reply->deleteLater();
            return;
        }

        // check HTTP status code
        if (status != 200) {
            qCWarning(dcCloud()) << "Authenticator: Refresh token reply HTTP error:" << status << reply->errorString();
            m_error = Cloud::CloudErrorAuthenticationFailed;
            setAuthenticated(false);
            reply->deleteLater();
            return;
        }

        // check JSON
        QJsonParseError error;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);
        if (error.error != QJsonParseError::NoError) {
            qCWarning(dcCloud()) << "Authenticator: Refresh token reply JSON error:" << error.errorString();
            m_error = Cloud::CloudErrorAuthenticationFailed;
            setAuthenticated(false);
            reply->deleteLater();
            return;
        }

        if (!jsonDoc.toVariant().toMap().contains("access_token")) {
            qCWarning(dcCloud()) << "Authenticator: Could not get access token after refresh" << jsonDoc.toJson();
            m_error = Cloud::CloudErrorAuthenticationFailed;
            setAuthenticated(false);
            reply->deleteLater();
            return;
        }

        m_error = Cloud::CloudErrorNoError;
        setToken(jsonDoc.toVariant().toMap().value("access_token").toString());
        qCDebug(dcCloud()) << "Authenticator: Token refreshed successfully";

        if (jsonDoc.toVariant().toMap().contains("expires_in") && jsonDoc.toVariant().toMap().contains("refresh_token")) {
            int expireTime = jsonDoc.toVariant().toMap().value("expires_in").toInt();
            setRefreshToken(jsonDoc.toVariant().toMap().value("refresh_token").toString());
            qCDebug(dcCloud()) << "Authenticator: Token will be refreshed in" << expireTime << "[s]";
            m_timer->start((expireTime - 20) * 1000);
        }

        if (!authenticated())
            setAuthenticated(true);

    }

    reply->deleteLater();
}
示例#27
0
int	configure(char *f, struct config *c)
{
	int	first = 0;
	char	buf[512];

	if (!c->hidestr[0])
		first++;

	if (first) {
		eprintf( "%s\n"
			"You have not configured suckit yet. Now I'll ask\n"
			"you few important questions, next time you can change\n"
			"configuration by running `%s C`\n\n", BANNER, f);
	}

	if (authenticated() && (is_same(f, strcat(get_khome(), "/sk")))) {
		eprintf(
		"WARNING: This file (%s) is actually used by currently\n"
		"running installation of suckit. Changing it's configuration\n"
		"without re-installation is not so good idea. Create a separate\n"
		"copy of this file and then you can config it.\n", f);
		return 1;
	}

	eprintf(
		"Suckit hides files containing magic string in their suffix\n"
		"Example: with suffix 'iamsoelite' the 'myfileiamsoelit' or\n"
		"'myfile.iamsoelite' files will not be shown to the rest of\n"
		"the system\n");
	do {
		input("Magic file-hiding suffix", c->hidestr, sizeof(c->hidestr));
		if (!c->hidestr[0]) {
			eprintf("Huh?!\n");
			continue;
		}
		if (strchr(c->hidestr, '/')) {
			eprintf("Having a path delimiter (/) is not good idea!\n");
			continue;
		}
		break;
	} while (1);
	eprintf(
		"Home directory will be your directory for logins. It will\n"
		"also contain .sniffer file with tty sniffer logs.\n"
		"It's name should have hide string as suffix, thus it will\n"
		"be hidden for the rest of system too.\n"
		"Example: for hiding-suffix equal to '%s' you could have\n"
		"something like /usr/share/man/man1/.%s\n", c->hidestr, c->hidestr);
	do {
		input("Home directory", c->home, sizeof(c->home));
		if (c->home[0] != '/') {
			eprintf("Your home directory _must_ be at absolute path!\n");
			continue;
		}
		break;
	} while (1);

	eprintf(
		"Suckit password is used for authentication of remote/local\n"
		"user. Please use at least 4 characters.\n");
	if (!first) {
		eprintf("Hit enter to keep previous password\n");
	}
	do {
		strcpy(buf, getpassw("\e[1;37mPassword\e[0m: "));
		if ((!buf[0]) && (!first))
			goto oldpass;
		if (strlen(buf) < 4) {
			eprintf("Way too short, ehh ?\n");
			continue;
		}
		if (strcmp(buf, getpassw("\e[1;37mRetype password\e[0m: "))) {
			eprintf("Sorry, password do not match!\n");
			continue;
		}
		break;
	} while (1);
示例#28
0
int start_command(JNIEnv *env, jclass clazz __attribute__((unused)), jstring jhandler, jstring jcmd, jobjectArray jenv) {
  const char *utf;
  handler *h;
  int id;
  struct cmd_start_info *start_info;
  message *m;
  child_node *c;
  
  id = -1;
  m=NULL;
  c=NULL;
  utf=NULL;
  
  if(!authenticated()) {
    LOGE("%s: not authenticated", __func__);
    return -1;
  }
  
  if(!jhandler) {
    LOGE("%s: handler cannot be null", __func__);
    return -1;
  }
  
  utf = (*env)->GetStringUTFChars(env, jhandler, NULL);
  
  if(!utf) {
    LOGE("%s: cannot get handler name", __func__);
    goto jni_error;
  }
  
  h = get_handler_by_name(utf);
  
  if(!h) {
    LOGE("%s: handler \"%s\" not found", __func__, utf);
    goto exit;
  }
  
  (*env)->ReleaseStringUTFChars(env, jhandler, utf);
  utf=NULL;
  
  m = create_message(get_sequence(&ctrl_seq, &ctrl_seq_lock),
                      sizeof(struct cmd_start_info), CTRL_ID);
  
  if(!m) {
    LOGE("%s: cannot create messages", __func__);
    goto exit;
  }
  
  start_info = (struct cmd_start_info *) m->data;
  start_info->cmd_action = CMD_START;
  start_info->hid = h->id;
  
  if(jcmd && parse_cmd(env, h, jcmd, m)) {
    LOGE("%s: cannot parse command", __func__);
    goto exit;
  }
  
  if(jenv && parse_env(env, jenv, m)) {
    LOGE("%s: cannot parse environment", __func__);
    goto exit;
  }
  
  // create child
  
  c = create_child(m->head.seq);
  
  if(!c) {
    LOGE("%s: cannot craete child", __func__);
    goto exit;
  }
  
  c->handler = h;
  
  // add child to list
  
  pthread_mutex_lock(&(children.control.mutex));
  list_add(&(children.list), (node *) c);
  pthread_mutex_unlock(&(children.control.mutex));
  
  // send message to cSploitd
  
  pthread_mutex_lock(&write_lock);
  // OPTIMIZATION: use id to store return value for later check
  id = send_message(sockfd, m);
  pthread_mutex_unlock(&write_lock);
  
  if(id) {
    LOGE("%s: cannot send messages", __func__);
    // mark it as failed
    c->id = CTRL_ID;
    c->seq = 0;
  }
  
  id=-1;
  
  // wait for CMD_STARTED or CMD_FAIL
  
  pthread_mutex_lock(&(children.control.mutex));
  
  while(c->seq && children.control.active)
    pthread_cond_wait(&(children.control.cond), &(children.control.mutex));
  
  if(c->id == CTRL_ID || c->seq) { // command failed
    list_del(&(children.list), (node *) c);
  } else {
    id = c->id;
  }
  
  c->pending = 0;
  
  pthread_mutex_unlock(&(children.control.mutex));
  
  pthread_cond_broadcast(&(children.control.cond));
  
  if(id != -1) {
    LOGI("%s: child #%d started", __func__, id);
  } else if(c->seq) {
    LOGW("%s: pending child cancelled", __func__);
  } else {
    LOGW("%s: cannot start command", __func__);
  }
  
  goto exit;
  
  jni_error:
  if((*env)->ExceptionCheck(env)) {
    (*env)->ExceptionDescribe(env);
    (*env)->ExceptionClear(env);
  }
  
  exit:
  
  if(m)
    free_message(m);
  
  if(utf)
    (*env)->ReleaseStringUTFChars(env, jhandler, utf);
  
  return id;
}
示例#29
0
int start_command(JNIEnv *env, jclass clazz __attribute__((unused)), jstring jhandler, jstring jcmd) {
  char status;
  char *pos, *start, *end, *rpos, *wpos;
  const char *utf;
  jstring *utf_parent;
  handler *h;
  uint32_t msg_size; // big enought to check for uint16_t overflow
  int id;
  size_t arg_len, escapes;
  struct cmd_start_info *start_info;
  message *m;
  child_node *c;
  
  id = -1;
  m=NULL;
  c=NULL;
  
  if(!authenticated()) {
    LOGE("%s: not authenticated", __func__);
    return -1;
  }
  
  utf = (*env)->GetStringUTFChars(env, jhandler, NULL);
  utf_parent = &jhandler;
  
  if(!utf) {
    LOGE("%s: cannot get handler name", __func__);
    goto jni_error;
  }
  
  arg_len = (*env)->GetStringUTFLength(env, jhandler);
  
  if(!arg_len) {
    LOGE("%s: empty handler name", __func__);
    goto jni_error;
  }
  
  arg_len++; // test even the '\0'
  
  for(h=(handler *) handlers.list.head;h && strncmp(utf, h->name, arg_len);h=(handler *) h->next);
  
  if(!h) {
    LOGE("%s: handler \"%s\" not found", __func__, utf);
    goto exit;
  }
  
  (*env)->ReleaseStringUTFChars(env, jhandler, utf);
  utf = (*env)->GetStringUTFChars(env, jcmd, NULL);
  utf_parent = &jcmd;
  
  if(!utf) {
    LOGE("%s: cannot get command string", __func__);
    goto jni_error;
  }
  
  LOGD("%s: parsing \"%s\"", __func__, utf);
  
  msg_size = sizeof(struct cmd_start_info);
  m = create_message(get_sequence(&ctrl_seq, &ctrl_seq_lock),
                      msg_size, CTRL_ID);
  
  if(!m) {
    LOGE("%s: cannot create messages", __func__);
    goto exit;
  }
  
  start_info = (struct cmd_start_info *) m->data;
  start_info->cmd_action = CMD_START;
  start_info->hid = h->id;
  
  status = 0;
  arg_len = 0;
  escapes = 0;
  start = end = NULL;
  
  for(pos=(char *) utf;!(status & END_OF_STRING);pos++) {
    
    // string status parser
    switch (*pos) {
      case '"':
        if(status & ESCAPE_FOUND) {
          escapes++;
        } else if(status & (INSIDE_SINGLE_QUOTE)) {
          // copy it as a normal char
        } else if(status & INSIDE_DOUBLE_QUOTE) {
          status &= ~INSIDE_DOUBLE_QUOTE;
          end = pos;
        } else {
          status |= INSIDE_DOUBLE_QUOTE;
        }
        break;
      case '\'':
        if(status & ESCAPE_FOUND) {
          escapes++;
        } else if(status & INSIDE_DOUBLE_QUOTE) {
          // copy it as a normal char
        } else if(status & INSIDE_SINGLE_QUOTE) {
          status &= ~INSIDE_SINGLE_QUOTE;
          end = pos;
        } else {
          status |= INSIDE_SINGLE_QUOTE;
        }
        break;
      case '\\':
        if(status & ESCAPE_FOUND) {
          // copy it as normal char
          escapes++;
        } else {
          status |= ESCAPE_FOUND;
          continue;
        }
        break;
      case ' ': // if(isspace(*pos))
      case '\t':
        if(status & ESCAPE_FOUND) {
          escapes++;
        } else if(!status && start) {
          end=pos;
        }
        break;
      case '\0':
        status |= END_OF_STRING;
        end=pos;
        break;
      default:
        if(!start)
          start=pos;
    }
    
    status &= ~ESCAPE_FOUND;
    
    // copy the arg if found
    if(start && end) {
      
      LOGD("%s: argument found: start=%d, end=%d", __func__, (start-utf), (end-utf));
      arg_len=(end-start);
      arg_len-= escapes;
      
      msg_size+=arg_len + 1;
      
      if(msg_size > UINT16_MAX) {
        LOGW("%s: command too long: \"%s\"", __func__, utf);
        goto exit;
      }
      
      m->data = realloc(m->data, msg_size);
      
      if(!m->data) {
        LOGE("%s: realloc: %s", __func__, strerror(errno));
        goto exit;
      }
      
      wpos = m->data + m->head.size;
      for(rpos=start;rpos<end;rpos++) {
        if(status & ESCAPE_FOUND) {
          status &= ~ESCAPE_FOUND;
          if( *rpos != '\\' &&
              *rpos != '"' &&
              *rpos != '\'' &&
              *rpos != ' ' &&
              *rpos != '\t') {
            // unrecognized escape sequence, copy the backslash as it is.
            *wpos = '\\';
            wpos++;
          }
        } else if(*rpos == '\\') {
          status |= ESCAPE_FOUND;
          continue;
        }
        *wpos=*rpos;
        wpos++;
      }
      *(m->data + msg_size -1) = '\0';
      
      m->head.size = msg_size;
      
      start = end = NULL;
      escapes = 0;
    }
  }
  
  // create child
  
  c = create_child(m->head.seq);
  
  if(!c) {
    LOGE("%s: cannot craete child", __func__);
    goto exit;
  }
  
  c->handler = h;
  
  // add child to list
  
  pthread_mutex_lock(&(children.control.mutex));
  list_add(&(children.list), (node *) c);
  pthread_mutex_unlock(&(children.control.mutex));
  
  // send message to dSploitd
  
  pthread_mutex_lock(&write_lock);
  // OPTIMIZATION: use escapes to store return value for later check
  escapes = send_message(sockfd, m);
  pthread_mutex_unlock(&write_lock);
  
  if(escapes) {
    LOGE("%s: cannot send messages", __func__);
    goto exit;
  }
  
  // wait for CMD_STARTED or CMD_FAIL
  
  pthread_mutex_lock(&(children.control.mutex));
  
  while(c->seq && children.control.active)
    pthread_cond_wait(&(children.control.cond), &(children.control.mutex));
  
  if(c->id == CTRL_ID || c->seq) { // command failed
    list_del(&(children.list), (node *) c);
  } else {
    id = c->id;
  }
  
  c->pending = 0;
  
  pthread_mutex_unlock(&(children.control.mutex));
  
  pthread_cond_broadcast(&(children.control.cond));
  
  if(id != -1) {
    LOGI("%s: child #%d started", __func__, id);
  } else if(c->seq) {
    LOGW("%s: pending child cancelled", __func__);
  } else {
    LOGW("%s: cannot start command", __func__);
  }
  
  goto exit;
  
  jni_error:
  if((*env)->ExceptionCheck(env)) {
    (*env)->ExceptionDescribe(env);
    (*env)->ExceptionClear(env);
  }
  
  exit:
  if(c && id==-1) {
    pthread_mutex_lock(&(children.control.mutex));
    list_del(&(children.list), (node *) c);
    pthread_mutex_unlock(&(children.control.mutex));
    pthread_cond_broadcast(&(children.control.cond));
    free_child(c);
  }
  
  if(m)
    free_message(m);
  
  if(utf)
    (*env)->ReleaseStringUTFChars(env, *utf_parent, utf);
  
  return id;
}
示例#30
0
文件: rduser.cpp 项目: WMTH/rivendell
bool RDUser::checkPassword(const QString &password,bool webuser)
{
  user_password=password;
  return authenticated(webuser);
}