void OwncloudShibbolethCredsPage::setupBrowser()
{
    if (!_browser.isNull()) {
        return;
    }
    OwncloudWizard *ocWizard = qobject_cast<OwncloudWizard *>(wizard());
    AccountPtr account = ocWizard->account();

    // we need to reset the cookie jar to drop temporary cookies (like the shib cookie)
    // i.e. if someone presses "back"
    QNetworkAccessManager *qnam = account->networkAccessManager();
    CookieJar *jar = new CookieJar;
    jar->restore(account->cookieJarPath());
    // Implicitly deletes the old cookie jar, and reparents the jar
    qnam->setCookieJar(jar);

    _browser = new ShibbolethWebView(account);
    connect(_browser.data(), &ShibbolethWebView::shibbolethCookieReceived,
        this, &OwncloudShibbolethCredsPage::slotShibbolethCookieReceived, Qt::QueuedConnection);
    connect(_browser.data(), &ShibbolethWebView::rejected,
        this, &OwncloudShibbolethCredsPage::slotBrowserRejected);

    _browser->move(ocWizard->x(), ocWizard->y());
    _browser->show();
    _browser->setFocus();
}
Esempio n. 2
0
void fetchPrivateLinkUrl(AccountPtr account, const QString &remotePath,
    const QByteArray &numericFileId, QObject *target,
    std::function<void(const QString &url)> targetFun)
{
    QString oldUrl;
    if (!numericFileId.isEmpty())
        oldUrl = account->deprecatedPrivateLinkUrl(numericFileId).toString(QUrl::FullyEncoded);

    // Retrieve the new link by PROPFIND
    PropfindJob *job = new PropfindJob(account, remotePath, target);
    job->setProperties(
        QList<QByteArray>()
        << "http://owncloud.org/ns:fileid" // numeric file id for fallback private link generation
        << "http://owncloud.org/ns:privatelink");
    job->setTimeout(10 * 1000);
    QObject::connect(job, &PropfindJob::result, target, [=](const QVariantMap &result) {
        auto privateLinkUrl = result["privatelink"].toString();
        auto numericFileId = result["fileid"].toByteArray();
        if (!privateLinkUrl.isEmpty()) {
            targetFun(privateLinkUrl);
        } else if (!numericFileId.isEmpty()) {
            targetFun(account->deprecatedPrivateLinkUrl(numericFileId).toString(QUrl::FullyEncoded));
        } else {
            targetFun(oldUrl);
        }
    });
    QObject::connect(job, &PropfindJob::finishedWithError, target, [=](QNetworkReply *) {
        targetFun(oldUrl);
    });
    job->start();
}
//called during the validation of the client certificate.
void OwncloudSetupPage::slotCertificateAccepted()
{
    QSslCertificate sslCertificate;

    resultP12ToPem certif = p12ToPem(addCertDial->getCertificatePath().toStdString() , addCertDial->getCertificatePasswd().toStdString());
    if(certif.ReturnCode){
        QString s = QString::fromStdString(certif.Certificate);
        QByteArray ba = s.toLocal8Bit();

        QList<QSslCertificate> sslCertificateList = QSslCertificate::fromData(ba, QSsl::Pem);
        sslCertificate = sslCertificateList.takeAt(0);

        _ocWizard->ownCloudCertificate = ba;
        _ocWizard->ownCloudPrivateKey = certif.PrivateKey.c_str();
        _ocWizard->ownCloudCertificatePath = addCertDial->getCertificatePath();
        _ocWizard->ownCloudCertificatePasswd = addCertDial->getCertificatePasswd();

        AccountPtr acc = _ocWizard->account();
        acc->setCertificate(_ocWizard->ownCloudCertificate, _ocWizard->ownCloudPrivateKey);
        addCertDial->reinit();
        validatePage();
    } else {
        QString message;
        message = certif.Comment.c_str();
        addCertDial->showErrorMessage(message);
        addCertDial->show();
    }
}
Esempio n. 4
0
void
Opal::Bank::on_mwi_event (std::string aor,
			  std::string info)
{
  AccountPtr account = find_account (aor);

  if (account)
    account->handle_message_waiting_information (info);
}
Esempio n. 5
0
AvatarJob::AvatarJob(AccountPtr account, const QString &userId, int size, QObject *parent)
    : AbstractNetworkJob(account, QString(), parent)
{
    if (account->serverVersionInt() >= Account::makeServerVersion(10, 0, 0)) {
        _avatarUrl = Utility::concatUrlPath(account->url(), QString("remote.php/dav/avatars/%1/%2.png").arg(userId, QString::number(size)));
    } else {
        _avatarUrl = Utility::concatUrlPath(account->url(), QString("index.php/avatar/%1/%2").arg(userId, QString::number(size)));
    }
}
void AbstractCredentialsWizardPage::cleanupPage()
{
    // Reset the credentials when the 'Back' button is used.

    AccountPtr account = static_cast<OwncloudWizard *>(wizard())->account();
    AbstractCredentials *creds = account->credentials();
    if (creds && !qobject_cast<DummyCredentials *>(creds)) {
        account->setCredentials(new DummyCredentials);
    }
}
Esempio n. 7
0
void
Opal::Bank::on_registration_event (std::string aor,
				   Opal::Account::RegistrationState state,
				   std::string msg)
{
  AccountPtr account = find_account (aor);

  if (account)
    account->handle_registration_event (state, msg);
}
Esempio n. 8
0
bool QuotaInfo::canGetQuota() const
{
    if (! _accountState || !_active) {
        return false;
    }
    AccountPtr account = _accountState->account();
    return _accountState->isConnected()
        && account->credentials()
        && account->credentials()->ready();
}
Esempio n. 9
0
void Application::slotCleanup()
{
    // explicitly close windows. This is somewhat of a hack to ensure
    // that saving the geometries happens ASAP during a OS shutdown
    AccountPtr account = AccountManager::instance()->account();
    if (account) {
        account->save();
    }
    FolderMan::instance()->unloadAndDeleteAllFolders();

    _gui->slotShutdown();
    _gui->deleteLater();
}
Esempio n. 10
0
std::string Trace::ShowShort()
{
	std::string editedby = "unknown";
	
	try {
		AccountPtr account = mud::AccountManager::Get()->GetByKey(getAccount());
		editedby = account->getName();
	} catch(RowNotFoundException& e) {
		
	}
	
	return Global::Get()->sprintf("%s (%ld): %s\n", 
			editedby.c_str(),
			getTime(),
			getDescription().c_str());
}
Esempio n. 11
0
void Application::slotLogout()
{
    AccountState* ai = AccountStateManager::instance()->accountState();
    if (ai) {
        AccountPtr a = ai->account();
        // invalidate & forget token/password
        a->credentials()->invalidateToken();
        // terminate all syncs and unload folders
        FolderMan *folderMan = FolderMan::instance();
        folderMan->setSyncEnabled(false);
        folderMan->terminateSyncProcess();
        ai->setSignedOut(true);
        // show result
        _gui->slotComputeOverallSyncStatus();
    }
}
/**
 * Construct a new PendingChannelRequest object that always fails.
 *
 * \param account Account to use.
 * \param errorName The name of a D-Bus error.
 * \param errorMessage The error message.
 */
PendingChannelRequest::PendingChannelRequest(const AccountPtr &account,
        const QString &errorName, const QString &errorMessage)
    : PendingOperation(ConnectionPtr()),
      mPriv(new Private(account->dbusConnection()))
{
    setFinishedWithError(errorName, errorMessage);
}
Esempio n. 13
0
AccountState::AccountState(AccountPtr account)
    : QObject(account.data())
    , _account(account)
    , _quotaInfo(0)
    , _state(AccountState::Disconnected)
    , _connectionStatus(ConnectionValidator::Undefined)
    , _waitingForNewCredentials(false)
{
    qRegisterMetaType<AccountState*>("AccountState*");

    _quotaInfo = new QuotaInfo(this); // Need to be initialized when 'this' is fully initialized

    connect(account.data(), SIGNAL(invalidCredentials()),
            SLOT(slotInvalidCredentials()));
    connect(account.data(), SIGNAL(credentialsFetched(AbstractCredentials*)),
            SLOT(slotCredentialsFetched(AbstractCredentials*)));
}
Esempio n. 14
0
void AbstractCredentialsWizardPage::cleanupPage()
{
    // Reset the credentials when the 'Back' button is used.

    // Unfortunately this code is also run when the Wizard finishes
    // prematurely with 'Skip Folder Configuration'. Therefore we need to
    // avoid resetting credentials on active accounts.
    AccountPtr account = static_cast<OwncloudWizard*>(wizard())->account();
    if (account == AccountManager::instance()->account())
        return;

    AbstractCredentials *creds = account->credentials();
    if (creds) {
        if (!creds->inherits("DummyCredentials")) {
            account->setCredentials(CredentialsFactory::create("dummy"));
        }
    }
}
Esempio n. 15
0
std::vector<std::string> Trace::Show()
{
	std::vector<std::string> result;
	std::string editedby = "unknown";
	
	try {
		AccountPtr account = mud::AccountManager::Get()->GetByKey(getAccount());
		editedby = account->getName();
	} catch(RowNotFoundException& e) {
		
	}
	
	result.push_back(Global::Get()->sprintf("Account: '%s'.", editedby.c_str()));
	result.push_back(Global::Get()->sprintf("Description: '%s'.", getDescription().c_str()));
	result.push_back(Global::Get()->sprintf("Diff: %s.", getDiff().c_str()));
	result.push_back(Global::Get()->sprintf("Time: %ld.", getTime()));
	
	return result;
}
Esempio n. 16
0
AccountListener::AccountListener(AccountPtr ptr) : m_accPtr(ptr) {
    QObject::connect(ptr.data()->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), this, SLOT(accountReady(Tp::PendingOperation *)));

    QObject::connect(m_accPtr.data(), SIGNAL(statusChanged(Tp::ConnectionStatus,
                                                                Tp::ConnectionStatusReason,
                                                                const QString &, const QVariantMap &)),
                     this, SLOT(statusChanged(Tp::ConnectionStatus,
                                              Tp::ConnectionStatusReason,
                                              const QString &, const QVariantMap &)));
}
Esempio n. 17
0
ShibbolethWebView::ShibbolethWebView(AccountPtr account, QWidget* parent)
    : QWebView(parent)
    , _account(account)
    , _accepted(false)
    , _cursorOverriden(false)
{
    // no minimize
    setWindowFlags(Qt::Dialog);
    setAttribute(Qt::WA_DeleteOnClose);

    QWebPage* page = new QWebPage(this);
    connect(page, SIGNAL(loadStarted()),
            this, SLOT(slotLoadStarted()));
    connect(page, SIGNAL(loadFinished(bool)),
            this, SLOT(slotLoadFinished(bool)));

    // Make sure to accept the same SSL certificate issues as the regular QNAM we use for syncing
    QObject::connect(page->networkAccessManager(), SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
            _account.data(), SLOT(slotHandleSslErrors(QNetworkReply*,QList<QSslError>)));

    // The Account keeps ownership of the cookie jar, it must outlive this webview.
    account->lendCookieJarTo(page->networkAccessManager());
    connect(page->networkAccessManager()->cookieJar(),
            SIGNAL(newCookiesForUrl (QList<QNetworkCookie>, QUrl)),
            this, SLOT(onNewCookiesForUrl (QList<QNetworkCookie>, QUrl)));
    page->mainFrame()->load(account->url());
    this->setPage(page);
    setWindowTitle(tr("%1 - Authenticate").arg(Theme::instance()->appNameGUI()));

    // If we have a valid cookie, it's most likely expired. We can use this as
    // as a criteria to tell the user why the browser window pops up
    QNetworkCookie shibCookie = ShibbolethCredentials::findShibCookie(_account.data(), ShibbolethCredentials::accountCookies(_account.data()));
    if (shibCookie != QNetworkCookie()) {
        Logger::instance()->postOptionalGuiLog(tr("Reauthentication required"), tr("Your session has expired. You need to re-login to continue to use the client."));
    }

    ConfigFile config;
    QSettings settings(config.configFile());
    resize(900, 700); // only effective the first time, later overridden by restoreGeometry
    restoreGeometry(settings.value(ShibbolethWebViewGeometryC).toByteArray());
}
Esempio n. 18
0
    AccountInterfacePtr AccountManager::newAccount_( const WString& _accountID )
    {
        String utf8_path;
        if( Helper::unicodeToUtf8( m_serviceProvider, _accountID, utf8_path ) == false )
        {
            LOGGER_ERROR(m_serviceProvider)("AccountManager::newAccount_ can't convert accountID '%ls' to utf8"
                , _accountID.c_str() 
                );

            return nullptr;
        }

        ConstString folder = Helper::stringizeString( m_serviceProvider, utf8_path );

        if( FILE_SERVICE(m_serviceProvider)
            ->existDirectory( CONST_STRING(m_serviceProvider, user), folder ) == false )
        {
            if( FILE_SERVICE(m_serviceProvider)
                ->createDirectory( CONST_STRING(m_serviceProvider, user), folder ) == false )
            {
                LOGGER_ERROR(m_serviceProvider)("AccountManager::createAccount_: Account '%ls' failed create directory '%s'"
                    , _accountID.c_str() 
                    , folder.c_str()
                    );

                return nullptr;
            }
        }

        AccountPtr newAccount = m_factoryAccounts.createObject();

		uint32_t projectVersion = APPLICATION_SERVICE( m_serviceProvider )
			->getProjectVersion();
		
		if( newAccount->initialize( m_serviceProvider, _accountID, folder, projectVersion ) == false )
		{
			return nullptr;				 
		}

        return newAccount;
    }
Esempio n. 19
0
void OwncloudSetupWizard::startWizard()
{
    FolderMan *folderMan = FolderMan::instance();
    AccountPtr account = Account::create();
    account->setCredentials(CredentialsFactory::create("dummy"));
    account->setSslErrorHandler(new SslDialogErrorHandler);
    _ocWizard->setAccount(account);
    _ocWizard->setOCUrl(account->url().toString());

    _remoteFolder = Theme::instance()->defaultServerFolder();
    // remoteFolder may be empty, which means /
    QString localFolder = Theme::instance()->defaultClientFolder();

    // if its a relative path, prepend with users home dir, otherwise use as absolute path

    if( !QDir(localFolder).isAbsolute() ) {
        localFolder = QDir::homePath() + QDir::separator() + localFolder;
    }

    _ocWizard->setProperty("oldLocalFolder", localFolder);
    _ocWizard->setProperty("localFolder", localFolder);

    // remember the local folder to compare later if it changed, but clean first
    QString lf = QDir::fromNativeSeparators(localFolder);
    if( !lf.endsWith(QLatin1Char('/'))) {
        lf.append(QLatin1Char('/'));
    }

    _initLocalFolder = lf;

    _ocWizard->setRemoteFolder(_remoteFolder);

    _ocWizard->setStartId(WizardCommon::Page_ServerSetup);

    _ocWizard->restart();

    _ocWizard->open();
    _ocWizard->raise();
}
Esempio n. 20
0
// also checks if an installation is valid and determines auth type in a second step
void OwncloudSetupWizard::slotDetermineAuthType(const QString &urlString)
{
    QString fixedUrl = urlString;
    QUrl url = QUrl::fromUserInput(fixedUrl);
    // fromUserInput defaults to http, not http if no scheme is specified
    if (!fixedUrl.startsWith("http://") && !fixedUrl.startsWith("https://")) {
        url.setScheme("https");
    }
    AccountPtr account = _ocWizard->account();
    account->setUrl(url);
    // Reset the proxy which might had been determined previously in ConnectionValidator::checkServerAndAuth()
    // when there was a previous account.
    account->networkAccessManager()->setProxy(QNetworkProxy(QNetworkProxy::DefaultProxy));
    // Set fake credentials beforfe we check what credential it actually is.
    account->setCredentials(CredentialsFactory::create("dummy"));
    CheckServerJob *job = new CheckServerJob(_ocWizard->account(), this);
    job->setIgnoreCredentialFailure(true);
    connect(job, SIGNAL(instanceFound(QUrl,QVariantMap)), SLOT(slotOwnCloudFoundAuth(QUrl,QVariantMap)));
    connect(job, SIGNAL(instanceNotFound(QNetworkReply*)), SLOT(slotNoOwnCloudFoundAuth(QNetworkReply*)));
    connect(job, SIGNAL(timeout(const QUrl&)), SLOT(slotNoOwnCloudFoundAuthTimeout(const QUrl&)));
    job->setTimeout(10*1000);
    job->start();
}
Esempio n. 21
0
int main()
{
	cout << "Connecting to database..." << endl;
	ActiveRecordManager::GetInstance()->Initialize( "host=localhost;user=root;password=123456;db=test_ar" );
	ActiveRecordManager::GetInstance()->AddTable<Account>();
	ActiveRecordManager::GetInstance()->AddTable<Player>();

	cout << "Updating database schemas..." << endl;
	try
	{
		ActiveRecordManager::GetInstance()->UpdateTableSchemas();
	}
	catch( const Exception & e )
	{
		cout << e.displayText() << endl;
	}
	cout << "Update completed." << endl;

	Account account;
	account.Username = "******";
	account.Password = "******";
	
	account.Save();

	vector<AccountPtr> result;
	Account::FindAll( result, DbField( &Account::Id ) >= 20 && DbField( &Account::Id ) < 25, DbOrderBy<Account>( &Account::Username ), 2 );

	for( vector<AccountPtr>::const_iterator it = result.begin(); it != result.end(); ++it )
	{
		AccountPtr account = *it;
		cout << account->ToString() << endl;
	}

	system( "PAUSE" );
	return 0;
}
Esempio n. 22
0
void PopClient::SetAccount(AccountPtr account)
{
	MojLogTrace(s_log);

	if (account.get()) {
		m_account = account;
		m_session->SetAccount(account);
		m_builderFactory->SetAccountId(m_account->GetAccountId());

		if (m_account->IsDeleted()) {
			MojLogInfo(s_log, "Account %s is being deleted", AsJsonString(m_account->GetAccountId()).c_str());
		} else if (m_state == State_LoadingAccount || m_state == State_NeedAccount || m_state == State_None) {
			m_state = State_OkToRunCommands;
		}
		CheckQueue();
	} else {
		MojLogCritical(s_log, "failed to find account in database");
	}
}
Esempio n. 23
0
void Account::setSharedThis(AccountPtr sharedThis)
{
    _sharedThis = sharedThis.toWeakRef();
}
Esempio n. 24
0
AccountPtr Account::create()
{
    AccountPtr acc = AccountPtr(new Account);
    acc->setSharedThis(acc);
    return acc;
}
/**
 * Construct a new PendingChannelRequest object.
 *
 * \param account Account to use.
 * \param requestedProperties A dictionary containing the desirable properties.
 * \param userActionTime The time at which user action occurred, or QDateTime()
 *                       if this channel request is for some reason not
 *                       involving user action.
 * \param preferredHandler Either the well-known bus name (starting with
 *                         org.freedesktop.Telepathy.Client.) of the preferred
 *                         handler for this channel, or an empty string to
 *                         indicate that any handler would be acceptable.
 * \param create Whether createChannel or ensureChannel should be called.
 * \param account The account the request was made through.
 */
PendingChannelRequest::PendingChannelRequest(const AccountPtr &account,
        const QVariantMap &requestedProperties, const QDateTime &userActionTime,
        const QString &preferredHandler, bool create, const ChannelRequestHints &hints)
    : PendingOperation(account),
      mPriv(new Private(account->dbusConnection()))
{
    QString channelDispatcherObjectPath =
        QString(QLatin1String("/%1")).arg(TP_QT_IFACE_CHANNEL_DISPATCHER);
    channelDispatcherObjectPath.replace(QLatin1String("."), QLatin1String("/"));
    Client::ChannelDispatcherInterface *channelDispatcherInterface =
        account->dispatcherInterface();

    QDBusPendingCallWatcher *watcher = 0;
    if (create) {
        if (hints.isValid()) {
            if (account->supportsRequestHints()) {
                watcher = new QDBusPendingCallWatcher(
                    channelDispatcherInterface->CreateChannelWithHints(
                        QDBusObjectPath(account->objectPath()),
                        requestedProperties,
                        userActionTime.isNull() ? 0 : userActionTime.toTime_t(),
                        preferredHandler, hints.allHints()), this);
            } else {
                warning() << "Hints passed to channel request won't have an effect"
                    << "because the Channel Dispatcher service in use is too old";
            }
        }

        if (!watcher) {
            watcher = new QDBusPendingCallWatcher(
                    channelDispatcherInterface->CreateChannel(
                        QDBusObjectPath(account->objectPath()),
                        requestedProperties,
                        userActionTime.isNull() ? 0 : userActionTime.toTime_t(),
                        preferredHandler), this);
        }
    } else {
        if (hints.isValid()) {
            if (account->supportsRequestHints()) {
                watcher = new QDBusPendingCallWatcher(
                    channelDispatcherInterface->EnsureChannelWithHints(
                        QDBusObjectPath(account->objectPath()),
                        requestedProperties,
                        userActionTime.isNull() ? 0 : userActionTime.toTime_t(),
                        preferredHandler, hints.allHints()), this);
            } else {
                warning() << "Hints passed to channel request won't have an effect"
                    << "because the Channel Dispatcher service in use is too old";
            }
        }

        if (!watcher) {
            watcher = new QDBusPendingCallWatcher(
                    channelDispatcherInterface->EnsureChannel(
                        QDBusObjectPath(account->objectPath()),
                        requestedProperties,
                        userActionTime.isNull() ? 0 : userActionTime.toTime_t(),
                        preferredHandler), this);
        }
    }

    // TODO: This is a Qt bug fixed upstream, should be in the next Qt release.
    //       We should not need to check watcher->isFinished() here, remove the
    //       check when we depend on the fixed Qt version.
    if (watcher->isFinished()) {
        onWatcherFinished(watcher);
    } else {
        connect(watcher,
                SIGNAL(finished(QDBusPendingCallWatcher*)),
                SLOT(onWatcherFinished(QDBusPendingCallWatcher*)));
    }
}