Welcome to mirror list, hosted at ThFree Co, Russian Federation.

credentialstore.cpp « http « creds « src - github.com/owncloud/client.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 19229514b92cc0442269be4e11bc7a33ec5934c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*
 * Copyright (C) by Klaas Freitag <freitag@owncloud.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 */

#include <QtGui>
#include <QInputDialog>

#include "config.h"

#include "creds/http/credentialstore.h"
#include "creds/http/httpconfigfile.h"
#include "mirall/theme.h"

#ifdef WITH_QTKEYCHAIN
#include <qtkeychain/keychain.h>
using namespace QKeychain;
#endif

#define MAX_LOGIN_ATTEMPTS 3

namespace Mirall {

CredentialStore *CredentialStore::_instance=0;
CredentialStore::CredState CredentialStore::_state = NotFetched;
QString CredentialStore::_passwd   = QString::null;
QString CredentialStore::_user     = QString::null;
QString CredentialStore::_url      = QString::null;
QString CredentialStore::_errorMsg = QString::null;
#ifdef WITH_QTKEYCHAIN
CredentialStore::CredentialType CredentialStore::_type = KeyChain;
#else
CredentialStore::CredentialType CredentialStore::_type = Settings;
#endif

CredentialStore::CredentialStore(QObject *parent) :
    QObject(parent)
{
}

CredentialStore *CredentialStore::instance()
{
    if( !CredentialStore::_instance ) CredentialStore::_instance = new CredentialStore;
    return CredentialStore::_instance;
}

QString CredentialStore::password() const
{
    return _passwd;
}
QString CredentialStore::user() const
{
    return _user;
}

CredentialStore::CredState CredentialStore::state()
{
    return _state;
}

void CredentialStore::fetchCredentials()
{
    HttpConfigFile cfgFile;

    bool ok = false;
    QString pwd;
    _user = cfgFile.user();
    _url  = cfgFile.ownCloudUrl();

    QString key = keyChainKey(_url);

    if( key.isNull() ) {
        qDebug() << "Can not fetch credentials, url is zero!";
        _state = Error;
        emit( fetchCredentialsFinished(false) );
        return;
    }

    switch( _type ) {
    case CredentialStore::Settings: {
        /* Read from config file. */
        _state = Fetching;
        cfgFile.fixupOldPassword();
        if( cfgFile.passwordExists() ) {
            pwd = cfgFile.password();
            ok = true;
        } else {
            ok = false;
            _state = EntryNotFound;
        }
        break;
    }
    case CredentialStore::KeyChain: {
        // If the credentials are here already, return.
        if( _state == Ok || _state == AsyncWriting ) {
            emit(fetchCredentialsFinished(true));
            return;
        }
        // otherwise fetch asynchronious.
#ifdef WITH_QTKEYCHAIN
        _state = AsyncFetching;
        if( !_user.isEmpty() ) {
            ReadPasswordJob *job = new ReadPasswordJob(Theme::instance()->appName());
            job->setKey( key );

            connect( job, SIGNAL(finished(QKeychain::Job*)), this,
                     SLOT(slotKeyChainReadFinished(QKeychain::Job*)));
            job->start();
        }
#else
        qDebug() << "QtKeyChain: Not yet implemented!";
        _state = Error;
#endif
        break;
    }
    default: {
        break;
    }
    }

    if( _state == Fetching ) { // ...but not AsyncFetching
        if( ok ) {
            _passwd = pwd;
            _state = Ok;
        }
        if( !ok && _state == Fetching ) {
            _state = Error;
        }

        emit( fetchCredentialsFinished(ok) );
    } else {
        // in case of AsyncFetching nothing happens here. The finished-Slot
        // will emit the finish signal.
    }
}

void CredentialStore::reset()
{
    _state = NotFetched;
    _user   = QString::null;
    _passwd = QString::null;
}

QString CredentialStore::keyChainKey( const QString& url ) const
{
    QString u(url);
    if( u.isEmpty() ) {
        qDebug() << "Empty url in keyChain, error!";
        return QString::null;
    }
    if( _user.isEmpty() ) {
        qDebug() << "Error: User is emty!";
        return QString::null;
    }

    if( !u.endsWith(QChar('/')) ) {
        u.append(QChar('/'));
    }

    QString key = _user+QLatin1Char(':')+u;
    return key;
}

void CredentialStore::slotKeyChainReadFinished(QKeychain::Job* job)
{
#ifdef WITH_QTKEYCHAIN
    ReadPasswordJob *pwdJob = static_cast<ReadPasswordJob*>(job);
    if( pwdJob ) {
        switch( pwdJob->error() ) {
        case QKeychain::NoError:
            _passwd = pwdJob->textData();
#ifdef Q_OS_LINUX
            // Currently there is a bug in the keychain on linux that if no
            // entry is there, an empty password comes back, but no error.
            if( _passwd.isEmpty() ) {
                _state = EntryNotFound;
                _errorMsg = tr("No password entry found in keychain. Please reconfigure.");
            } else
#endif
            _state = Ok;
            break;
        case QKeychain::EntryNotFound:
            _state = EntryNotFound;
            break;
        case QKeychain::CouldNotDeleteEntry:
            _state = Error;
            break;
        case QKeychain::AccessDenied:
            _state = AccessDenied;
            break;
        case QKeychain::NoBackendAvailable:
            _state = NoKeychainBackend;
            break;
        case QKeychain::NotImplemented:
            _state = NoKeychainBackend;
            break;
        case QKeychain::OtherError:
        default:
            _state = Error;

        }
        /* In case there is no backend, tranparentely switch to Settings file. */
        if( _state == NoKeychainBackend ) {
            qDebug() << "No Storage Backend, falling back to Settings mode.";
            _type = CredentialStore::Settings;
            fetchCredentials();
            return;
        }

        if( _state == EntryNotFound ) {
            // try to migrate.
        }

        if( _state != Ok ) {
            qDebug() << "Error with keychain: " << pwdJob->errorString();
            if(_errorMsg.isEmpty()) _errorMsg = pwdJob->errorString();
        } else {
            _errorMsg = QString::null;
        }
    } else {
        _state = Error;
        qDebug() << "Error: KeyChain Read Password Job failed!";
    }
    emit(fetchCredentialsFinished(_state == Ok));
#else
    (void) job;
#endif
}

QString CredentialStore::errorMessage()
{
    return _errorMsg;
}

void CredentialStore::setCredentials( const QString& url, const QString& user,
                                      const QString& pwd )
{
    _passwd = pwd;
    _user = user;
#ifdef WITH_QTKEYCHAIN
     _type = KeyChain;
#else
     _type = Settings;
#endif
    _url  = url;
    _state = Ok;
}

void CredentialStore::saveCredentials( )
{
    HttpConfigFile cfgFile;
    QString key = keyChainKey(_url);
    if( key.isNull() ) {
        qDebug() << "Error: Can not save credentials, URL is zero!";
        return;
    }
#ifdef WITH_QTKEYCHAIN
#endif

    cfgFile.setUser(_user);
    switch( _type ) {
    case CredentialStore::KeyChain: {
#ifdef WITH_QTKEYCHAIN
        WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName());
        // Set password in KeyChain
        job->setKey( key );
        job->setTextData(_passwd);

        connect( job, SIGNAL(finished(QKeychain::Job*)), this,
                 SLOT(slotKeyChainWriteFinished(QKeychain::Job*)));
        _state = AsyncWriting;
        job->start();
#endif
        }
        break;
    case CredentialStore::Settings:
        cfgFile.setPassword( _passwd );
        reset();
        break;
    default:
        // unsupported.
        break;
    }
}

void CredentialStore::slotKeyChainWriteFinished( QKeychain::Job *job )
{
#ifdef WITH_QTKEYCHAIN
    WritePasswordJob *pwdJob = static_cast<WritePasswordJob*>(job);
    if( pwdJob ) {
        QKeychain::Error err = pwdJob->error();

        if( err != QKeychain::NoError ) {
            qDebug() << "Error with keychain: " << pwdJob->errorString();
            if( err == NoBackendAvailable || err == NotImplemented ||
                    pwdJob->errorString().contains(QLatin1String("Could not open wallet"))) {
                _state = NoKeychainBackend;
                _type = Settings;
                saveCredentials();
            } else {
                _state = Error;
            }
        } else {
            qDebug() << "Successfully stored password for user " << _user;
            // Try to remove password formerly stored in the config file.
            HttpConfigFile cfgFile;
            cfgFile.removePassword();
            _state = NotFetched;
        }
    } else {
        qDebug() << "Error: KeyChain Write Password Job failed!";
        _state = Error;
    }
#else
    (void) job;
#endif
}

// Called if a user chooses to not store the password locally.
void CredentialStore::deleteKeyChainCredential( const QString& key )
{
#ifdef WITH_QTKEYCHAIN
    // Start the remove job, do not care so much about the result.
    DeletePasswordJob *job = new DeletePasswordJob(Theme::instance()->appName());
    job->setKey( key );
    job->start();
#endif
}

}