summaryrefslogtreecommitdiff
path: root/src/leap/gui/firstrun/wizard.py
blob: 427f9df887aef5bb9f21b7307a8e89c0bd2d3faa (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
#!/usr/bin/env python
import logging

import sip
try:
    sip.setapi('QString', 2)
    sip.setapi('QVariant', 2)
except ValueError:
    pass

from PyQt4 import QtCore
from PyQt4 import QtGui

from leap.base import checks as basechecks
from leap.crypto import leapkeyring
from leap.eip import checks as eipchecks

from leap.gui import firstrun

from leap.gui import mainwindow_rc

try:
    from collections import OrderedDict
except ImportError:
    # We must be in 2.6
    from leap.util.dicts import OrderedDict

logger = logging.getLogger(__name__)

"""
~~~~~~~~~~~~~~~~~~~~~~~~~~
Work in progress!
~~~~~~~~~~~~~~~~~~~~~~~~~~
This wizard still needs to be refactored out.

TODO-ish:

[X] Break file in wizard / pages files (and its own folder).
[ ] Separate presentation from logic.
[ ] Have a "manager" class for connections, that can be
    dep-injected for testing.
[ ] Document signals used / expected.
[ ] Separate style from widgets.
[ ] Fix TOFU Widget for provider cert.
[X] Refactor widgets out.
[ ] Follow more MVC style.
[ ] Maybe separate "first run wizard" into different wizards
    that share some of the pages?
"""


def get_pages_dict():
    return OrderedDict((
        ('intro', firstrun.intro.IntroPage),
        ('providerselection',
            firstrun.providerselect.SelectProviderPage),
        ('login', firstrun.login.LogInPage),
        ('providerinfo', firstrun.providerinfo.ProviderInfoPage),
        ('providersetupvalidation',
            firstrun.providersetup.ProviderSetupValidationPage),
        ('signup', firstrun.register.RegisterUserPage),
        ('connect',
            firstrun.connect.ConnectionPage),
        ('lastpage', firstrun.last.LastPage)
    ))


class FirstRunWizard(QtGui.QWizard):

    def __init__(
            self,
            conductor_instance,
            parent=None,
            pages_dict=None,
            username=None,
            providers=None,
            success_cb=None, is_provider_setup=False,
            trusted_certs=None,
            netchecker=basechecks.LeapNetworkChecker,
            providercertchecker=eipchecks.ProviderCertChecker,
            eipconfigchecker=eipchecks.EIPConfigChecker,
            start_eipconnection_signal=None,
            eip_statuschange_signal=None,
            debug_server=None,
            quitcallback=None):
        super(FirstRunWizard, self).__init__(
            parent,
            QtCore.Qt.WindowStaysOnTopHint)

        # we keep a reference to the conductor
        # to be able to launch eip checks and connection
        # in the connection page, before the wizard has ended.
        self.conductor = conductor_instance

        self.username = username
        self.providers = providers

        # success callback
        self.success_cb = success_cb

        # is provider setup?
        self.is_provider_setup = is_provider_setup

        # a dict with trusted fingerprints
        # in the form {'nospacesfingerprint': ['host1', 'host2']}
        self.trusted_certs = trusted_certs

        # Checkers
        self.netchecker = netchecker
        self.providercertchecker = providercertchecker
        self.eipconfigchecker = eipconfigchecker

        # debug server
        self.debug_server = debug_server

        # Signals
        # will be emitted in connecting page
        self.start_eipconnection_signal = start_eipconnection_signal
        self.eip_statuschange_signal = eip_statuschange_signal

        if quitcallback is not None:
            self.button(
                QtGui.QWizard.CancelButton).clicked.connect(
                    quitcallback)

        self.providerconfig = None
        # previously registered
        # if True, jumps to LogIn page.
        # by setting 1st page??
        #self.is_previously_registered = is_previously_registered
        # XXX ??? ^v
        self.is_previously_registered = bool(self.username)
        self.from_login = False

        pages_dict = pages_dict or get_pages_dict()
        self.add_pages_from_dict(pages_dict)

        self.validation_errors = {}

        self.setPixmap(
            QtGui.QWizard.BannerPixmap,
            QtGui.QPixmap(':/images/banner.png'))
        self.setPixmap(
            QtGui.QWizard.BackgroundPixmap,
            QtGui.QPixmap(':/images/background.png'))

        # set options
        self.setOption(QtGui.QWizard.IndependentPages, on=False)
        self.setOption(QtGui.QWizard.NoBackButtonOnStartPage, on=True)

        self.setWindowTitle("First Run Wizard")

        # TODO: set style for MAC / windows ...
        #self.setWizardStyle()

    #
    # setup pages in wizard
    #

    def add_pages_from_dict(self, pages_dict):
        """
        @param pages_dict: the dictionary with pages, where
            values are a tuple of InstanceofWizardPage, kwargs.
        @type pages_dict: dict
        """
        for name, page in pages_dict.items():
            # XXX check for is_previously registered
            # and skip adding the signup branch if so
            self.addPage(page())
        self.pages_dict = pages_dict

    def get_page_index(self, page_name):
        """
        returns the index of the given page
        @param page_name: the name of the desired page
        @type page_name: str
        @rparam: index of page in wizard
        @rtype: int
        """
        return self.pages_dict.keys().index(page_name)

    #
    # validation errors
    #

    def set_validation_error(self, pagename, error):
        self.validation_errors[pagename] = error

    def clean_validation_error(self, pagename):
        vald = self.validation_errors
        if pagename in vald:
            del vald[pagename]

    def get_validation_error(self, pagename):
        return self.validation_errors.get(pagename, None)

    def accept(self):
        """
        final step in the wizard.
        gather the info, update settings
        and call the success callback if any has been passed.
        """
        super(FirstRunWizard, self).accept()

        # username and password are in different fields
        # if they were stored in log_in or sign_up pages.
        from_login = self.from_login
        unamek_base = 'userName'
        passwk_base = 'userPassword'
        unamek = 'login_%s' % unamek_base if from_login else unamek_base
        passwk = 'login_%s' % passwk_base if from_login else passwk_base

        username = self.field(unamek)
        password = self.field(passwk)
        provider = self.field('provider_domain')
        remember_pass = self.field('rememberPassword')

        logger.debug('chosen provider: %s', provider)
        logger.debug('username: %s', username)
        logger.debug('remember password: %s', remember_pass)

        # we are assuming here that we only remember one username
        # in the form username@provider.domain
        # We probably could extend this to support some form of
        # profiles.

        settings = QtCore.QSettings()

        settings.setValue("FirstRunWizardDone", True)
        settings.setValue("provider_domain", provider)
        full_username = "%s@%s" % (username, provider)

        settings.setValue("remember_user_and_pass", remember_pass)

        if remember_pass:
            settings.setValue("username", full_username)
            seed = self.get_random_str(10)
            settings.setValue("%s_seed" % provider, seed)

            # XXX #744: comment out for 0.2.0 release
            # if we need to have a version of python-keyring < 0.9
            leapkeyring.leap_set_password(
                full_username, password, seed=seed)

        logger.debug('First Run Wizard Done.')
        cb = self.success_cb
        if cb and callable(cb):
            self.success_cb()

    # misc helpers

    def get_random_str(self, n):
        """
        returns a random string
        :param n: the length of the desired string
        :rvalue: str
        """
        from string import (ascii_uppercase, ascii_lowercase, digits)
        from random import choice
        return ''.join(choice(
            ascii_uppercase +
            ascii_lowercase +
            digits) for x in range(n))

    def set_providerconfig(self, providerconfig):
        """
        sets a providerconfig attribute
        used when we fetch and parse a json configuration
        """
        self.providerconfig = providerconfig

    def get_provider_by_index(self):  # pragma: no cover
        """
        returns the value of a provider given its index.
        this was used in the select provider page,
        in the case where we were preseeding providers in a combobox
        """
        # Leaving it here for the moment when we go back at the
        # option of preseeding with known provider values.
        provider = self.field('provider_index')
        return self.providers[provider]


if __name__ == '__main__':
    # standalone test
    # it can be (somehow) run against
    # gui/tests/integration/fake_user_signup.py

    import sys
    import logging
    logging.basicConfig()
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    app = QtGui.QApplication(sys.argv)
    server = sys.argv[1] if len(sys.argv) > 1 else None

    trusted_certs = {
        "3DF83F316BFA0186"
        "0A11A5C9C7FC24B9"
        "18C62B941192CC1A"
        "49AE62218B2A4B7C": ['springbok']}

    wizard = FirstRunWizard(
        None, trusted_certs=trusted_certs,
        debug_server=server)
    wizard.show()
    sys.exit(app.exec_())