summaryrefslogtreecommitdiff
path: root/src/leap/bitmask/gui/login.py
blob: 0e64bbcfe5ddfdc23642623b1384e63ea52ece6c (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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# -*- coding: utf-8 -*-
# login.py
# Copyright (C) 2013 LEAP
#
# 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, either version 3 of the License, or
# (at your option) any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Login widget implementation
"""
import logging

from collections import deque

from PySide import QtCore, QtGui
from ui_login import Ui_LoginWidget

from leap.bitmask.config import flags
from leap.bitmask.util import make_address
from leap.bitmask.util.credentials import USERNAME_REGEX
from leap.bitmask.util.keyring_helpers import has_keyring
from leap.bitmask.util.keyring_helpers import get_keyring
from leap.common.check import leap_assert_type

logger = logging.getLogger(__name__)


class LoginWidget(QtGui.QWidget):
    """
    Login widget that emits signals to display the wizard or to
    perform login.
    """
    # Emitted when the login button is clicked
    login = QtCore.Signal()
    logged_in_signal = QtCore.Signal()
    cancel_login = QtCore.Signal()
    logout = QtCore.Signal()

    # Emitted when the user changes the provider combobox index. The object
    # parameter is actually a boolean value that is True if "Other..." was
    # selected, False otherwse
    provider_changed = QtCore.Signal(object)

    MAX_STATUS_WIDTH = 40

    # Keyring
    KEYRING_KEY = "bitmask"

    def __init__(self, settings, parent=None):
        """
        Constructs the LoginWidget.

        :param settings: client wide settings
        :type settings: LeapSettings
        :param parent: The parent widget for this widget
        :type parent: QWidget or None
        """
        QtGui.QWidget.__init__(self, parent)

        self._settings = settings

        self._providers_indexes = deque(maxlen=2)  # previous and current
        self._providers_indexes.append(-1)

        self.ui = Ui_LoginWidget()
        self.ui.setupUi(self)

        self.ui.chkRemember.stateChanged.connect(
            self._remember_state_changed)
        self.ui.chkRemember.setEnabled(has_keyring())

        self.ui.lnPassword.setEchoMode(QtGui.QLineEdit.Password)

        self.ui.btnLogin.clicked.connect(self.login)
        self.ui.lnPassword.returnPressed.connect(self.login)

        self.ui.lnUser.returnPressed.connect(self._focus_password)

        self.ui.cmbProviders.currentIndexChanged.connect(
            self._current_provider_changed)

        self.ui.btnLogout.clicked.connect(
            self.logout)

        username_re = QtCore.QRegExp(USERNAME_REGEX)
        self.ui.lnUser.setValidator(
            QtGui.QRegExpValidator(username_re, self))

        self.logged_out()

        self.ui.btnLogout.clicked.connect(self.start_logout)

        self.ui.clblErrorMsg.hide()
        self.ui.clblErrorMsg.clicked.connect(self.ui.clblErrorMsg.hide)

        self.ui.lnUser.textEdited.connect(self.ui.clblErrorMsg.hide)
        self.ui.lnPassword.textEdited.connect(self.ui.clblErrorMsg.hide)

    def _remember_state_changed(self, state):
        """
        Saves the remember state in the LeapSettings

        :param state: possible stats can be Checked, Unchecked and
        PartiallyChecked
        :type state: QtCore.Qt.CheckState
        """
        enable = True if state == QtCore.Qt.Checked else False
        self._settings.set_remember(enable)

    def set_providers(self, provider_list):
        """
        Set the provider list to provider_list plus an "Other..." item
        that triggers the wizard

        :param provider_list: list of providers
        :type provider_list: list of str
        """
        self.ui.cmbProviders.blockSignals(True)
        self.ui.cmbProviders.clear()
        self.ui.cmbProviders.addItems(provider_list + [self.tr("Other...")])
        self.ui.cmbProviders.blockSignals(False)

    def select_provider_by_name(self, name):
        """
        Given a provider name/domain, it selects it in the combobox

        :param name: name or domain for the provider
        :type name: str
        """
        provider_index = self.ui.cmbProviders.findText(name)
        self._providers_indexes.append(provider_index)

        # block the signals during a combobox change since we don't want to
        # trigger the default signal that makes the UI ask the user for
        # confirmation
        self.ui.cmbProviders.blockSignals(True)
        self.ui.cmbProviders.setCurrentIndex(provider_index)
        self.ui.cmbProviders.blockSignals(False)

    def get_selected_provider(self):
        """
        Returns the selected provider in the combobox
        """
        return self.ui.cmbProviders.currentText()

    def set_remember(self, value):
        """
        Checks the remember user and password checkbox

        :param value: True to mark it checked, False otherwise
        :type value: bool
        """
        self.ui.chkRemember.setChecked(value)

    def get_remember(self):
        """
        Returns the remember checkbox state

        :rtype: bool
        """
        return self.ui.chkRemember.isChecked()

    def set_user(self, user):
        """
        Sets the user and focuses on the next field, password.

        :param user: user to set the field to
        :type user: str
        """
        self.ui.lnUser.setText(user)
        self._focus_password()

    def get_user(self):
        """
        Returns the user that appears in the widget.

        :rtype: unicode
        """
        return self.ui.lnUser.text()

    def set_password(self, password):
        """
        Sets the password for the widget

        :param password: password to set
        :type password: unicode
        """
        self.ui.lnPassword.setText(password)

    def get_password(self):
        """
        Returns the password that appears in the widget

        :rtype: unicode
        """
        return self.ui.lnPassword.text()

    def set_status(self, status, error=True):
        """
        Sets the status label at the login stage to status

        :param status: status message
        :type status: str
        """
        if len(status) > self.MAX_STATUS_WIDTH:
            status = status[:self.MAX_STATUS_WIDTH] + "..."
        if error:
            self.ui.clblErrorMsg.show()
            self.ui.clblErrorMsg.setText(status)
        else:
            self.ui.lblStatus.setText(status)

    def set_enabled(self, enabled=False):
        """
        Enables or disables all the login widgets

        :param enabled: wether they should be enabled or not
        :type enabled: bool
        """
        self.ui.lnUser.setEnabled(enabled)
        self.ui.lnPassword.setEnabled(enabled)
        self.ui.chkRemember.setEnabled(enabled and has_keyring())
        self.ui.cmbProviders.setEnabled(enabled)

        self._set_cancel(not enabled)

    def set_logout_btn_enabled(self, enabled):
        """
        Enables or disables the logout button.

        :param enabled: wether they should be enabled or not
        :type enabled: bool
        """
        self.ui.btnLogout.setEnabled(enabled)

    def _set_cancel(self, enabled=False):
        """
        Enables or disables the cancel action in the "log in" process.

        :param enabled: wether it should be enabled or not
        :type enabled: bool
        """
        text = self.tr("Cancel")
        login_or_cancel = self.cancel_login
        hide_remember = enabled

        if not enabled:
            text = self.tr("Log In")
            login_or_cancel = self.login

        self.ui.btnLogin.setText(text)

        self.ui.btnLogin.clicked.disconnect()
        self.ui.btnLogin.clicked.connect(login_or_cancel)
        self.ui.chkRemember.setVisible(not hide_remember)
        self.ui.lblStatus.setVisible(hide_remember)

    def _focus_password(self):
        """
        Focuses in the password lineedit
        """
        self.ui.lnPassword.setFocus()

    @QtCore.Slot(int)
    def _current_provider_changed(self, idx):
        """
        TRIGGERS:
            self.ui.cmbProviders.currentIndexChanged

        :param idx: the index of the new selected item
        :type idx: int
        """
        self._providers_indexes.append(idx)
        is_wizard = idx == (self.ui.cmbProviders.count() - 1)
        self.provider_changed.emit(is_wizard)
        if is_wizard:
            self.restore_previous_provider()

    def restore_previous_provider(self):
        """
        Set as selected provider the one that was selected previously.
        """
        prev_provider = self._providers_indexes.popleft()
        self._providers_indexes.append(prev_provider)
        self.ui.cmbProviders.blockSignals(True)
        self.ui.cmbProviders.setCurrentIndex(prev_provider)
        self.ui.cmbProviders.blockSignals(False)

    def start_login(self):
        """
        Setups the login widgets for actually performing the login and
        performs some basic checks.

        :returns: True if everything's good to go, False otherwise
        :rtype: bool
        """
        username = self.get_user()
        password = self.get_password()
        provider = self.get_selected_provider()

        self._enabled_services = self._settings.get_enabled_services(
            self.get_selected_provider())

        if len(provider) == 0:
            self.set_status(
                self.tr("Please select a valid provider"))
            return False

        if len(username) == 0:
            self.set_status(
                self.tr("Please provide a valid username"))
            return False

        if len(password) == 0:
            self.set_status(
                self.tr("Please provide a valid password"))
            return False

        self.set_status(self.tr("Logging in..."), error=False)
        self.set_enabled(False)
        self.ui.clblErrorMsg.hide()

        self._settings.set_provider(provider)
        if self.get_remember() and has_keyring():
            # in the keyring and in the settings
            # we store the value 'usename@provider'
            full_user_id = make_address(username, provider).encode("utf8")
            try:
                keyring = get_keyring()
                keyring.set_password(self.KEYRING_KEY,
                                     full_user_id,
                                     password.encode("utf8"))
                # Only save the username if it was saved correctly in
                # the keyring
                self._settings.set_user(full_user_id)
            except Exception as e:
                logger.exception("Problem saving data to keyring. %r"
                                 % (e,))
        return True

    def logged_in(self):
        """
        Sets the widgets to the logged in state
        """
        self.ui.login_widget.hide()
        self.ui.logged_widget.show()
        self.ui.lblUser.setText(make_address(
            self.get_user(), self.get_selected_provider()))

        if flags.OFFLINE is False:
            self.logged_in_signal.emit()

    def logged_out(self):
        """
        Sets the widgets to the logged out state
        """
        # TODO consider "logging out offline" too...
        # how that would be ???

        self.ui.login_widget.show()
        self.ui.logged_widget.hide()

        self.set_password("")
        self.set_enabled(True)
        self.set_status("", error=False)

    def start_logout(self):
        """
        Sets the widgets to the logging out state
        """
        self.ui.btnLogout.setText(self.tr("Logging out..."))
        self.ui.btnLogout.setEnabled(False)

    def done_logout(self):
        """
        Sets the widgets to the logged out state
        """
        self.ui.btnLogout.setText(self.tr("Logout"))
        self.ui.btnLogout.setEnabled(True)
        self.ui.clblErrorMsg.hide()

    def load_user_from_keyring(self, saved_user):
        """
        Tries to load a user from the keyring, returns True if it was
        loaded successfully, False otherwise.

        :param saved_user: String containing the saved username as
                           user@domain
        :type saved_user: unicode

        :rtype: bool
        """
        leap_assert_type(saved_user, unicode)

        try:
            username, domain = saved_user.split('@')
        except ValueError as e:
            # if the saved_user does not contain an '@'
            logger.error('Username@provider malformed. %r' % (e, ))
            return False

        self.set_user(username)

        self.set_remember(True)

        saved_password = None
        try:
            keyring = get_keyring()
            saved_password = keyring.get_password(self.KEYRING_KEY,
                                                  saved_user
                                                  .encode("utf8"))
        except ValueError as e:
            logger.debug("Incorrect Password. %r." % (e,))

        if saved_password is not None:
            self.set_password(saved_password)
            return True

        return False