Ejemplo n.º 1
0
    def save(self):
        server = self.cleaned_data['server']

        if "://" not in server:
            # urlparse doesn't properly handle URLs without a scheme. It
            # believes the domain is actually the path. So we apply a prefix.
            server = "http://" + server

        url_parts = urlparse.urlparse(server)
        domain_method = url_parts[0]
        domain_name = url_parts[1]

        if domain_name.endswith("/"):
            domain_name = domain_name[:-1]

        site = Site.objects.get_current()
        site.domain = domain_name
        site.save()

        self.siteconfig.set("site_domain_method", domain_method)

        super(GeneralSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
Ejemplo n.º 2
0
def set_siteconfig_settings(settings):
    """A context manager to toggle site configuration settings.

    Args:
        settings (dict):
            The new site configuration settings.
    """
    siteconfig = SiteConfiguration.objects.get_current()

    old_settings = {}

    for setting, value in six.iteritems(settings):
        old_settings[setting] = siteconfig.get(setting)
        siteconfig.set(setting, value)

    siteconfig.save()
    load_site_config()

    try:
        yield
    finally:
        for setting, value in six.iteritems(old_settings):
            siteconfig.set(setting, value)

        siteconfig.save()
        load_site_config()
Ejemplo n.º 3
0
def set_siteconfig_settings(settings):
    """A context manager to toggle site configuration settings.

    Args:
        settings (dict):
            The new site configuration settings.
    """
    siteconfig = SiteConfiguration.objects.get_current()

    old_settings = {}

    for setting, value in six.iteritems(settings):
        old_settings[setting] = siteconfig.get(setting)
        siteconfig.set(setting, value)

    siteconfig.save()
    load_site_config()

    try:
        yield
    finally:
        for setting, value in six.iteritems(old_settings):
            siteconfig.set(setting, value)

        siteconfig.save()
        load_site_config()
Ejemplo n.º 4
0
    def save(self):
        server = self.cleaned_data['server']

        if "://" not in server:
            # urlparse doesn't properly handle URLs without a scheme. It
            # believes the domain is actually the path. So we apply a prefix.
            server = "http://" + server

        url_parts = urlparse.urlparse(server)
        domain_method = url_parts[0]
        domain_name = url_parts[1]

        if domain_name.endswith("/"):
            domain_name = domain_name[:-1]

        site = Site.objects.get_current()
        site.domain = domain_name
        site.save()

        self.siteconfig.set("site_domain_method", domain_method)

        super(GeneralSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
Ejemplo n.º 5
0
    def save(self):
        """Save the form."""
        super(EMailSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()

        if self.cleaned_data['send_test_mail']:
            site = Site.objects.get_current()
            siteconfig = SiteConfiguration.objects.get_current()

            site_url = '%s://%s' % (siteconfig.get('site_domain_method'),
                                    site.domain)

            if self.request and self.request.user.is_authenticated():
                to_user = self.request.user.email
            else:
                to_user = siteconfig.get('site_admin_email')

            try:
                send_mail(ugettext('E-mail settings test'),
                          ugettext('This is a test of the e-mail settings '
                                   'for the Review Board server at %s.') %
                          site_url,
                          siteconfig.get('mail_default_from'), [to_user],
                          fail_silently=False)
            except:
                messages.error(self.request,
                               ugettext('Failed to send test e-mail.'))
                logging.exception('Failed to send test e-mail.')
Ejemplo n.º 6
0
    def test_with_site_domain_method_https(self):
        """Testing load_site_config with site_domain_method=https"""
        self.siteconfig.set('site_domain_method', 'https')
        self.siteconfig.save()
        load_site_config()

        self.assertEqual(str(os.environ.get(str('HTTPS'))), str('on'))
        self.assertTrue(getattr(settings, 'CSRF_COOKIE_SECURE', None))

        # Ensure that CSRF cookie flags are set correctly.
        login_url = reverse('login')

        self.create_user(username='******', password='******')

        response = self.client.get(login_url, secure=True)
        csrf_cookie = response.cookies.get(settings.CSRF_COOKIE_NAME)
        self.assertIsNotNone(csrf_cookie)
        self.assertTrue(csrf_cookie['secure'])

        # Ensure that session cookie flags are set correctly.
        response = self.client.post(login_url, {
            'username': '******',
            'password': '******',
        },
                                    secure=True)

        session_cookie = response.cookies.get(settings.SESSION_COOKIE_NAME)
        self.assertIsNotNone(session_cookie)
        self.assertTrue(session_cookie['secure'])
Ejemplo n.º 7
0
    def test_review_close_with_email(self):
        """Tests e-mail is generated when a review is closed and e-mail setting
        is True
        """
        siteconfig = SiteConfiguration.objects.get_current()
        siteconfig.set("mail_send_review_close_mail", True)
        siteconfig.save()
        load_site_config()

        review_request = self.create_review_request()
        review_request.publish(review_request.submitter)

        # Clear the outbox.
        mail.outbox = []

        review_request.close(ReviewRequest.SUBMITTED, review_request.submitter)

        self.assertEqual(len(mail.outbox), 1)
        message = mail.outbox[0].message()
        self.assertTrue("This change has been marked as submitted"
                        in message.as_string())

        # Reset settings for review close requests
        siteconfig.set("mail_send_review_close_mail", False)
        siteconfig.save()
        load_site_config()
Ejemplo n.º 8
0
    def test_review_close_with_email(self):
        """Tests email is generated when a review is closed and email setting
        is True
        """
        siteconfig = SiteConfiguration.objects.get_current()
        siteconfig.set("mail_send_review_close_mail", True)
        siteconfig.save()
        load_site_config()

        review_request = self.create_review_request()
        review_request.publish(review_request.submitter)

        # Clear the outbox.
        mail.outbox = []

        review_request.close(ReviewRequest.SUBMITTED, review_request.submitter)

        self.assertEqual(len(mail.outbox), 1)
        message = mail.outbox[0].message()
        self.assertTrue("This change has been marked as submitted"
                        in message.as_string())

        # Reset settings for review close requests
        siteconfig.set("mail_send_review_close_mail", False)
        siteconfig.save()
        load_site_config()
Ejemplo n.º 9
0
    def test_review_close_with_email(self):
        """Tests email is generated when a review is closed and email setting is True"""
        siteconfig = SiteConfiguration.objects.get_current()
        siteconfig.set("mail_send_review_close_mail", True)
        siteconfig.save()
        load_site_config()

        user1 = User.objects.get(username="******")
        review_request = ReviewRequest.objects.create(user1, None)
        review_request.summary = "Test email notification on close"
        review_request.publish(user1)

        # Clear the outbox.
        mail.outbox = []

        review_request.close(ReviewRequest.SUBMITTED, user1)

        self.assertEqual(len(mail.outbox), 1)
        message = mail.outbox[0].message()
        self.assertTrue("This change has been marked as submitted"
                        in message.as_string())

        # Reset settings for review close requests
        siteconfig.set("mail_send_review_close_mail", False)
        siteconfig.save()
        load_site_config()
Ejemplo n.º 10
0
    def middleware(request):
        """Ensure that the latest siteconfig is loaded.

        Args:
            request (django.http.HttpRequest):
                The HTTP request from the client.

        Returns:
            django.http.HttpResponse:
            The response object.
        """
        try:
            siteconfig = SiteConfiguration.objects.get_current()
        except Exception as e:
            logger.critical('Unable to load SiteConfiguration: %s',
                            e,
                            exc_info=1)
            return

        # This will be unset if the SiteConfiguration expired, since we'll
        # have a new one in the cache.
        if not hasattr(siteconfig, '_rb_settings_loaded'):
            # Load all site settings.
            load_site_config(full_reload=True)
            siteconfig._rb_settings_loaded = True

        if siteconfig.settings.get('site_domain_method', 'http') == 'https':
            request.META['wsgi.url_scheme'] = 'https'

        return get_response(request)
Ejemplo n.º 11
0
def search_enabled(on_the_fly_indexing=False):
    """Temporarily enable indexed search.

    Args:
        on_the_fly_indexing (bool, optional):
            Whether or not to enable on-the-fly indexing.
    """
    siteconfig = SiteConfiguration.objects.get_current()

    if on_the_fly_indexing:
        siteconfig.set('search_on_the_fly_indexing', True)

    siteconfig.set('search_enable', True)
    siteconfig.save()
    load_site_config()

    try:
        yield
    finally:
        if on_the_fly_indexing:
            siteconfig.set('search_on_the_fly_indexing', False)

        siteconfig.set('search_enable', False)
        siteconfig.save()

        load_site_config()
Ejemplo n.º 12
0
    def save(self):
        """Save the form."""
        super(EMailSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()

        if self.cleaned_data['send_test_mail']:
            site = Site.objects.get_current()
            siteconfig = SiteConfiguration.objects.get_current()

            site_url = '%s://%s' % (siteconfig.get('site_domain_method'),
                                    site.domain)

            if self.request and self.request.user.is_authenticated():
                to_user = self.request.user.email
            else:
                to_user = siteconfig.get('site_admin_email')

            send_mail(_('E-mail settings test'),
                      _('This is a test of the e-mail settings for the Review '
                        'Board server at %s.') % site_url,
                      siteconfig.get('mail_default_from'),
                      [to_user],
                      fail_silently=True)
Ejemplo n.º 13
0
    def tearDownClass(cls):
        super(SearchTests, cls).tearDownClass()

        siteconfig = SiteConfiguration.objects.get_current()
        siteconfig.set('search_enable', False)
        siteconfig.save()

        load_site_config()
Ejemplo n.º 14
0
    def tearDownClass(cls):
        super(SearchTests, cls).tearDownClass()

        siteconfig = SiteConfiguration.objects.get_current()
        siteconfig.set('search_enable', False)
        siteconfig.save()

        load_site_config()
Ejemplo n.º 15
0
    def save(self):
        self.siteconfig.set("auth_require_sitewide_login", not self.cleaned_data["auth_anonymous_access"])

        self.siteconfig.set("auth_custom_backends", re.split(r",\s*", self.cleaned_data["custom_backends"]))

        super(AuthenticationSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
Ejemplo n.º 16
0
    def save(self):
        """Save the form.

        This will write the new configuration to the database. It will then
        force a site configuration reload.
        """
        super(StorageSettingsForm, self).save()

        load_site_config()
Ejemplo n.º 17
0
def initialize():
    """Begins initialization of Review Board.

    This sets up the logging, generates cache serial numbers, and then
    fires an initializing signal that other parts of the codebase can
    connect to. This must be called for such features as e-mail notification
    to work.
    """
    import logging
    import os

    import settings_local

    # Set RBSITE_PYTHON_PATH to the path we need for any RB-bundled
    # scripts we may call.
    os.environ['RBSITE_PYTHONPATH'] = \
        os.path.dirname(settings_local.__file__)

    from django.conf import settings
    from django.db import DatabaseError
    from djblets import log
    from djblets.cache.serials import generate_ajax_serial

    from reviewboard import signals
    from reviewboard.admin.siteconfig import load_site_config
    from reviewboard.extensions.base import get_extension_manager

    # This overrides a default django templatetag (url), and we want to make
    # sure it will always get loaded in every python instance.
    import reviewboard.site.templatetags

    is_running_test = getattr(settings, 'RUNNING_TEST', False)

    if not is_running_test:
        # Set up logging.
        log.init_logging()

    load_site_config()

    if not is_running_test:
        if settings.DEBUG:
            logging.debug("Log file for Review Board v%s (PID %s)" %
                          (get_version_string(), os.getpid()))

        # Generate the AJAX serial, used for AJAX request caching.
        generate_ajax_serial()

        # Load all extensions
        try:
            get_extension_manager().load()
        except DatabaseError:
            # This database is from a time before extensions, so don't attempt
            # to load any extensions yet.
            pass

    signals.initializing.send(sender=None)
Ejemplo n.º 18
0
def initialize():
    """Begins initialization of Review Board.

    This sets up the logging, generates cache serial numbers, and then
    fires an initializing signal that other parts of the codebase can
    connect to. This must be called for such features as e-mail notification
    to work.
    """
    import logging
    import os

    import settings_local

    # Set RBSITE_PYTHON_PATH to the path we need for any RB-bundled
    # scripts we may call.
    os.environ['RBSITE_PYTHONPATH'] = \
        os.path.dirname(settings_local.__file__)

    from django.conf import settings
    from django.db import DatabaseError
    from djblets import log
    from djblets.cache.serials import generate_ajax_serial

    from reviewboard import signals
    from reviewboard.admin.siteconfig import load_site_config
    from reviewboard.extensions.base import get_extension_manager

    # This overrides a default django templatetag (url), and we want to make
    # sure it will always get loaded in every python instance.
    import reviewboard.site.templatetags

    is_running_test = getattr(settings, 'RUNNING_TEST', False)

    if not is_running_test:
        # Set up logging.
        log.init_logging()

    load_site_config()

    if not is_running_test:
        if settings.DEBUG:
            logging.debug("Log file for Review Board v%s (PID %s)" %
                          (get_version_string(), os.getpid()))

        # Generate the AJAX serial, used for AJAX request caching.
        generate_ajax_serial()

        # Load all extensions
        try:
            get_extension_manager().load()
        except DatabaseError:
            # This database is from a time before extensions, so don't attempt
            # to load any extensions yet.
            pass

    signals.initializing.send(sender=None)
Ejemplo n.º 19
0
    def save(self):
        """Save the form.

        This will write the new configuration to the database. It will then
        force a site configuration reload.
        """
        super(LoggingSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
Ejemplo n.º 20
0
    def setUp(self):
        super(UserEmailTests, self).setUp()

        mail.outbox = []
        self.sender = '*****@*****.**'

        siteconfig = SiteConfiguration.objects.get_current()
        siteconfig.set("mail_send_new_user_mail", True)
        siteconfig.save()
        load_site_config()
Ejemplo n.º 21
0
    def setUp(self):
        initialize()

        mail.outbox = []
        self.sender = "*****@*****.**"

        siteconfig = SiteConfiguration.objects.get_current()
        siteconfig.set("mail_send_new_user_mail", True)
        siteconfig.save()
        load_site_config()
Ejemplo n.º 22
0
    def setUp(self):
        super(UserEmailTests, self).setUp()

        mail.outbox = []
        self.sender = '*****@*****.**'

        siteconfig = SiteConfiguration.objects.get_current()
        siteconfig.set("mail_send_new_user_mail", True)
        siteconfig.save()
        load_site_config()
Ejemplo n.º 23
0
    def save(self):
        """Save the form.

        This will write the new configuration to the database. It will then
        force a site configuration reload.
        """
        server = self.cleaned_data['server']

        if '://' not in server:
            # urlparse doesn't properly handle URLs without a scheme. It
            # believes the domain is actually the path. So we apply a prefix.
            server = 'http://' + server

        url_parts = urlparse(server)
        domain_method = url_parts[0]
        domain_name = url_parts[1]

        if domain_name.endswith('/'):
            domain_name = domain_name[:-1]

        site = Site.objects.get_current()

        if site.domain != domain_name:
            site.domain = domain_name
            site.save(update_fields=['domain'])

        self.siteconfig.set('site_domain_method', domain_method)

        cache_type = self.cleaned_data['cache_type']

        if cache_type != 'custom':
            if cache_type == 'locmem':
                # We want to specify a "reviewboard" location to keep items
                # separate from those in other caches.
                location = 'reviewboard'
            else:
                location_field = self.CACHE_LOCATION_FIELD_MAP[cache_type]
                location = self.cleaned_data[location_field]

                if cache_type == 'memcached':
                    # memcached allows a list of servers, rather than just a
                    # string representing one.
                    location = location.split(';')

            self.siteconfig.set('cache_backend', {
                DEFAULT_FORWARD_CACHE_ALIAS: {
                    'BACKEND': self.CACHE_BACKENDS_MAP[cache_type],
                    'LOCATION': location,
                }
            })

        super(GeneralSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
Ejemplo n.º 24
0
    def save(self):
        """Save the form.

        This will write the new configuration to the database. It will then
        force a site configuration reload.
        """
        super(EMailSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()

        if self.cleaned_data['send_test_mail']:
            site = Site.objects.get_current()
            siteconfig = SiteConfiguration.objects.get_current()
            product_name = settings.PRODUCT_NAME
            request = self.request

            site_url = '%s://%s' % (siteconfig.get('site_domain_method'),
                                    site.domain)

            if request and request.user.is_authenticated():
                to_user = request.user.email
            else:
                to_user = siteconfig.get('site_admin_email')

            try:
                send_mail(
                    subject=(
                        ugettext('%s e-mail settings test')
                        % product_name
                    ),
                    message=(
                        ugettext("This is a test of the e-mail settings "
                                 "for the %(product)s server at %(url)s. "
                                 "If you got this, you're all set!")
                        % {
                            'product': product_name,
                            'url': site_url,
                        }
                    ),
                    from_email=siteconfig.get('mail_default_from'),
                    recipient_list=[to_user],
                    fail_silently=False)
            except Exception as e:
                error = six.text_type(e)

                if request is not None:
                    messages.error(
                        request,
                        ugettext('Failed to send the test e-mail: "%s". Check '
                                 'the server logs for additional details.')
                        % error)

                logger.exception('Failed to send test e-mail to %s: %s',
                                 to_user, error)
Ejemplo n.º 25
0
    def setUpClass(cls):
        """Set some initial state for all search-related tests.

        This will enable search and reset Haystack's configuration based
        on that, allowing the search tests to run.
        """
        siteconfig = SiteConfiguration.objects.get_current()
        siteconfig.set('search_enable', True)
        siteconfig.save()

        load_site_config()
Ejemplo n.º 26
0
    def setUpClass(cls):
        """Set some initial state for all search-related tests.

        This will enable search and reset Haystack's configuration based
        on that, allowing the search tests to run.
        """
        siteconfig = SiteConfiguration.objects.get_current()
        siteconfig.set('search_enable', True)
        siteconfig.save()

        load_site_config()
Ejemplo n.º 27
0
    def setUp(self):
        super(ReviewRequestEmailTests, self).setUp()

        mail.outbox = []
        self.sender = '*****@*****.**'

        siteconfig = SiteConfiguration.objects.get_current()
        siteconfig.set("mail_send_review_mail", True)
        siteconfig.set("mail_default_from", self.sender)
        siteconfig.save()
        load_site_config()
Ejemplo n.º 28
0
    def setUp(self):
        super(ReviewRequestEmailTests, self).setUp()

        mail.outbox = []
        self.sender = '*****@*****.**'

        siteconfig = SiteConfiguration.objects.get_current()
        siteconfig.set("mail_send_review_mail", True)
        siteconfig.set("mail_default_from", self.sender)
        siteconfig.save()
        load_site_config()
Ejemplo n.º 29
0
    def save(self):
        self.siteconfig.set("auth_require_sitewide_login", not self.cleaned_data["auth_anonymous_access"])

        auth_backend = self.cleaned_data["auth_backend"]

        if auth_backend in self.auth_backend_forms:
            self.auth_backend_forms[auth_backend].save()

        super(AuthenticationSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
Ejemplo n.º 30
0
    def test_auth(self):
        """Testing OAuth2 authentication to the Web API with a valid token"""
        application = self.create_oauth_application(user=self.owner)
        token = self.create_oauth_token(application, self.user, 'session:read')

        with override_feature_check(oauth2_service_feature.feature_id, True):
            load_site_config()
            rsp = self.api_get(get_session_url(),
                               HTTP_AUTHORIZATION='Bearer %s' % token.token,
                               expected_mimetype=session_mimetype)

        self.assertIn('stat', rsp)
        self.assertEqual(rsp['stat'], 'ok')
Ejemplo n.º 31
0
    def save(self):
        self.siteconfig.set("auth_require_sitewide_login",
                            not self.cleaned_data['auth_anonymous_access'])

        auth_backend = self.cleaned_data['auth_backend']

        if auth_backend in self.auth_backend_forms:
            self.auth_backend_forms[auth_backend].save()

        super(AuthenticationSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
Ejemplo n.º 32
0
    def save(self):
        """Save the form."""
        server = self.cleaned_data['server']

        if "://" not in server:
            # urlparse doesn't properly handle URLs without a scheme. It
            # believes the domain is actually the path. So we apply a prefix.
            server = "http://" + server

        url_parts = urlparse(server)
        domain_method = url_parts[0]
        domain_name = url_parts[1]

        if domain_name.endswith("/"):
            domain_name = domain_name[:-1]

        site = Site.objects.get_current()

        if site.domain != domain_name:
            site.domain = domain_name
            site.save(update_fields=['domain'])

        self.siteconfig.set("site_domain_method", domain_method)

        cache_type = self.cleaned_data['cache_type']

        if cache_type != 'custom':
            if cache_type == 'locmem':
                # We want to specify a "reviewboard" location to keep items
                # separate from those in other caches.
                location = 'reviewboard'
            else:
                location_field = self.CACHE_LOCATION_FIELD_MAP[cache_type]
                location = self.cleaned_data[location_field]

                if cache_type == 'memcached':
                    # memcached allows a list of servers, rather than just a
                    # string representing one.
                    location = location.split(';')

            self.siteconfig.set('cache_backend', {
                DEFAULT_FORWARD_CACHE_ALIAS: {
                    'BACKEND': self.CACHE_BACKENDS_MAP[cache_type],
                    'LOCATION': location,
                }
            })

        super(GeneralSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
Ejemplo n.º 33
0
    def test_auth_invalid_scope(self):
        """Testing OAuth2 authentication to the Web API with a token missing
        scopes"""
        application = self.create_oauth_application(user=self.owner)
        token = self.create_oauth_token(application, self.user)

        with override_feature_check(oauth2_service_feature.feature_id, True):
            load_site_config()
            rsp = self.api_get(get_session_url(),
                               HTTP_AUTHORIZATION='Bearer %s' % token.token,
                               expected_status=403)

        self.assertIn('stat', rsp)
        self.assertEqual(rsp['stat'], 'fail')
Ejemplo n.º 34
0
    def save(self):
        """Save the form.

        This will write the new configuration to the database. It will then
        force a site configuration reload.
        """
        super(StorageSettingsForm, self).save()

        backend_id = self.cleaned_data['storage_backend_id']

        if backend_id in self.storage_backend_forms:
            backend_form = self.storage_backend_forms[backend_id]
            backend_form.save()

        load_site_config()
Ejemplo n.º 35
0
    def test_auth_expired(self):
        """Testing OAuth2 authentication to the Web API with an expired token
        """
        application = self.create_oauth_application(user=self.owner)
        token = self.create_oauth_token(application, self.user, 'session:read',
                                        expires=timedelta(hours=-1))

        with override_feature_check(oauth2_service_feature.feature_id, True):
            load_site_config()
            rsp = self.api_get(get_session_url(),
                               HTTP_AUTHORIZATION='Bearer %s' % token.token,
                               expected_status=401)

        self.assertIn('stat', rsp)
        self.assertEqual(rsp['stat'], 'fail')
Ejemplo n.º 36
0
    def save(self):
        """Save the form and sub-form for the selected search backend.

        This forces a site configuration reload.
        """
        search_backend_id = self.cleaned_data['search_backend_id']
        backend_form = self.search_backend_forms[search_backend_id]
        backend = search_backend_registry.get_search_backend(search_backend_id)

        backend.configuration = backend.get_configuration_from_form_data(
            backend_form.cleaned_data)

        super(SearchSettingsForm, self).save()

        # Reload any import changes to the Django settings.
        load_site_config()
Ejemplo n.º 37
0
    def process_request(self, request):
        # Load all site settings.
        siteconfig = load_site_config()

        if (siteconfig and siteconfig.settings.get('site_domain_method',
                                                   'http') == 'https'):
            request.META['wsgi.url_scheme'] = 'https'
Ejemplo n.º 38
0
    def save(self):
        """Save the form and sub-form for the selected search backend.

        This forces a site configuration reload.
        """
        search_backend_id = self.cleaned_data['search_backend_id']
        backend_form = self.search_backend_forms[search_backend_id]
        backend = search_backend_registry.get_search_backend(search_backend_id)

        backend.configuration = backend.get_configuration_from_form_data(
            backend_form.cleaned_data)

        super(SearchSettingsForm, self).save()

        # Reload any import changes to the Django settings.
        load_site_config()
Ejemplo n.º 39
0
    def process_request(self, request):
        # Load all site settings.
        siteconfig = load_site_config()

        if (siteconfig and
            siteconfig.settings.get('site_domain_method', 'http') == 'https'):
            request.META['wsgi.url_scheme'] = 'https'
Ejemplo n.º 40
0
    def save(self):
        """Save the form.

        This will write the new configuration to the database. It will then
        force a site configuration reload.
        """
        server = self.cleaned_data['server']

        if '://' not in server:
            # urlparse doesn't properly handle URLs without a scheme. It
            # believes the domain is actually the path. So we apply a prefix.
            server = 'http://' + server

        url_parts = urlparse(server)
        domain_method = url_parts[0]
        domain_name = url_parts[1]

        if domain_name.endswith('/'):
            domain_name = domain_name[:-1]

        site = Site.objects.get_current()

        if site.domain != domain_name:
            site.domain = domain_name
            site.save(update_fields=['domain'])

        self.siteconfig.set('site_domain_method', domain_method)

        cache_type = self.cleaned_data['cache_type']

        if cache_type != 'custom':
            cache_backend_info = self._cache_backends[cache_type]
            cache_form = self.cache_backend_forms[cache_type]
            cache_backend_settings = cache_form.build_cache_backend_settings()

            self.siteconfig.set(
                'cache_backend', {
                    DEFAULT_FORWARD_CACHE_ALIAS:
                    dict({
                        'BACKEND': cache_backend_info['backend_cls_path'],
                    }, **cache_backend_settings),
                })

        super(GeneralSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
Ejemplo n.º 41
0
    def test_auth_no_local_site(self):
        """Testing OAuth2 authentication to the Web API of a Local Site with an
        application not on that Local Site
        """
        local_site = LocalSite.objects.get(pk=1)
        local_site.users.add(self.user)
        application = self.create_oauth_application(user=self.owner)
        token = self.create_oauth_token(application, self.user, 'session:read')

        with override_feature_check(oauth2_service_feature.feature_id, True):
            load_site_config()
            rsp = self.api_get(get_session_url(local_site.name),
                               HTTP_AUTHORIZATION='Bearer %s' % token.token,
                               expected_status=401)

        self.assertIn('stat', rsp)
        self.assertEqual(rsp['stat'], 'fail')
Ejemplo n.º 42
0
    def save(self):
        server = self.cleaned_data["server"]

        if "://" not in server:
            # urlparse doesn't properly handle URLs without a scheme. It
            # believes the domain is actually the path. So we apply a prefix.
            server = "http://" + server

        url_parts = urlparse.urlparse(server)
        domain_method = url_parts[0]
        domain_name = url_parts[1]

        if domain_name.endswith("/"):
            domain_name = domain_name[:-1]

        site = Site.objects.get_current()
        site.domain = domain_name
        site.save()

        self.siteconfig.set("site_domain_method", domain_method)

        cache_type = self.cleaned_data["cache_type"]

        if cache_type != "custom":
            if cache_type == "locmem":
                # We want to specify a "reviewboard" location to keep items
                # separate from those in other caches.
                location = "reviewboard"
            else:
                location_field = self.CACHE_LOCATION_FIELD_MAP[cache_type]
                location = self.cleaned_data[location_field]

                if cache_type == "memcached":
                    # memcached allows a list of servers, rather than just a
                    # string representing one.
                    location = location.split(";")

            self.siteconfig.set(
                "cache_backend",
                {DEFAULT_CACHE_ALIAS: {"BACKEND": self.CACHE_BACKENDS_MAP[cache_type], "LOCATION": location}},
            )

        super(GeneralSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
Ejemplo n.º 43
0
    def process_request(self, request):
        try:
            siteconfig = SiteConfiguration.objects.get_current()
        except Exception as e:
            logging.critical('Unable to load SiteConfiguration: %s',
                             e, exc_info=1)
            return

        # This will be unset if the SiteConfiguration expired, since we'll
        # have a new one in the cache.
        if not hasattr(siteconfig, '_rb_settings_loaded'):
            # Load all site settings.
            load_site_config(full_reload=True)
            siteconfig._rb_settings_loaded = True

        if siteconfig.settings.get('site_domain_method', 'http') == 'https':
            request.META['wsgi.url_scheme'] = 'https'
Ejemplo n.º 44
0
    def process_request(self, request):
        try:
            siteconfig = SiteConfiguration.objects.get_current()
        except Exception as e:
            logging.critical('Unable to load SiteConfiguration: %s',
                             e,
                             exc_info=1)
            return

        # This will be unset if the SiteConfiguration expired, since we'll
        # have a new one in the cache.
        if not hasattr(siteconfig, '_rb_settings_loaded'):
            # Load all site settings.
            load_site_config(full_reload=True)
            siteconfig._rb_settings_loaded = True

        if siteconfig.settings.get('site_domain_method', 'http') == 'https':
            request.META['wsgi.url_scheme'] = 'https'
Ejemplo n.º 45
0
    def save(self):
        """Save the form.

        This will write the new configuration to the database. It will then
        force a site configuration reload.
        """
        self.siteconfig.set('auth_require_sitewide_login',
                            not self.cleaned_data['auth_anonymous_access'])

        auth_backend = self.cleaned_data['auth_backend']

        if auth_backend in self.auth_backend_forms:
            self.auth_backend_forms[auth_backend].save()

        super(AuthenticationSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
Ejemplo n.º 46
0
    def setUpClass(cls):
        """Set some initial state for all search-related tests.

        This will enable search and reset Haystack's configuration based
        on that, allowing the search tests to run.
        """
        super(SearchTests, cls).setUpClass()

        siteconfig = SiteConfiguration.objects.get_current()
        cls._old_search_enabled = siteconfig.get('search_enable')

        siteconfig.set('search_enable', True)
        siteconfig.save()

        load_site_config()

        app = apps.get_app_config('haystack')
        cls.signal_processor = app.signal_processor
Ejemplo n.º 47
0
    def test_auth_local_site_member(self):
        """Testing OAuth2 authentication to the Web API of a Local Site with
        with an application on a that Local Site as a member
        """
        local_site = LocalSite.objects.get(pk=1)
        local_site.users.add(self.user)
        local_site.save(update_fields=('public',))

        self.assertTrue(local_site.is_accessible_by(self.user))

        application = self.create_oauth_application(user=self.owner,
                                                    local_site=local_site)
        token = self.create_oauth_token(application, self.user, 'session:read')

        with override_feature_check(oauth2_service_feature.feature_id, True):
            load_site_config()
            rsp = self.api_get(get_session_url(local_site.name),
                               HTTP_AUTHORIZATION='Bearer %s' % token.token,
                               expected_mimetype=session_mimetype)

        self.assertIn('stat', rsp)
        self.assertEqual(rsp['stat'], 'ok')
Ejemplo n.º 48
0
    def save(self):
        super(EMailSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()

        if self.cleaned_data['send_test_mail']:
            site = Site.objects.get_current()
            siteconfig = SiteConfiguration.objects.get_current()

            site_url = '%s://%s' % (siteconfig.get('site_domain_method'),
                                    site.domain)

            if self.request and self.request.user.is_authenticated():
                to_user = self.request.user.email
            else:
                to_user = siteconfig.get('site_admin_email')

            send_mail(_('E-mail settings test'),
                      _('This is a test of the e-mail settings for the Review '
                        'Board server at %s.') % site_url,
                      siteconfig.get('mail_default_from'), [to_user],
                      fail_silently=True)
Ejemplo n.º 49
0
    def siteconfig_settings(self, settings, reload_settings=True):
        """Temporarily sets siteconfig settings for a test.

        Args:
            settings (dict):
                The new siteconfig settings to set.

            reload_settings (bool, optional):
                Whether to reload and recompute all settings, applying them
                to Django and other objects.

        Context:
            The current site configuration will contain the new settings for
            this test.
        """
        try:
            with super(TestCase, self).siteconfig_settings(settings):
                if reload_settings:
                    load_site_config()

                yield
        finally:
            if reload_settings:
                load_site_config()
Ejemplo n.º 50
0
 def save(self):
     super(StorageSettingsForm, self).save()
     load_site_config()
Ejemplo n.º 51
0
    def save(self):
        super(LoggingSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
        restart_logging()
Ejemplo n.º 52
0
    def save(self):
        super(EMailSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()
Ejemplo n.º 53
0
 def process_request(self, request):
     # Load all site settings.
     load_site_config()
Ejemplo n.º 54
0
def initialize():
    """Begin initialization of Review Board.

    This sets up the logging, generates cache serial numbers, loads extensions,
    and sets up other aspects of Review Board. Once it has finished, it will
    fire the :py:data:`reviewboard.signals.initializing` signal.

    This must be called at some point before most features will work, but it
    will be called automatically in a standard install. If you are writing
    an extension or management command, you do not need to call this yourself.
    """
    import logging
    import os

    import settings_local

    # Set RBSITE_PYTHON_PATH to the path we need for any RB-bundled
    # scripts we may call.
    os.environ[b'RBSITE_PYTHONPATH'] = \
        os.path.dirname(settings_local.__file__)

    from Crypto import Random
    from django.conf import settings
    from django.db import DatabaseError
    from djblets import log
    from djblets.cache.serials import generate_ajax_serial

    from reviewboard import signals
    from reviewboard.admin.siteconfig import load_site_config
    from reviewboard.extensions.base import get_extension_manager

    # This overrides a default django templatetag (url), and we want to make
    # sure it will always get loaded in every python instance.
    import reviewboard.site.templatetags

    is_running_test = getattr(settings, 'RUNNING_TEST', False)

    if not is_running_test:
        # Force PyCrypto to re-initialize the random number generator.
        Random.atfork()

        # Set up logging.
        log.init_logging()

    load_site_config()

    if not is_running_test:
        if settings.DEBUG:
            logging.debug("Log file for Review Board v%s (PID %s)" %
                          (get_version_string(), os.getpid()))

        # Generate the AJAX serial, used for AJAX request caching.
        generate_ajax_serial()

        # Store the AJAX serial as a template serial, so we have a reference
        # to the real serial last modified timestamp of our templates. This
        # is useful since the extension manager will be modifying AJAX_SERIAL
        # to prevent stale caches for templates using hooks. Not all templates
        # use hooks, and may want to base cache keys off TEMPLATE_SERIAL
        # instead.
        #
        # We only want to do this once, so we don't end up replacing it
        # later with a modified AJAX_SERIAL later.
        if not getattr(settings, 'TEMPLATE_SERIAL', None):
            settings.TEMPLATE_SERIAL = settings.AJAX_SERIAL

    try:
        # Django >= 1.7
        from django import setup
        setup()
    except ImportError:
        # Django < 1.7
        pass

    if not is_running_test:
        # Load all extensions
        try:
            get_extension_manager().load()
        except DatabaseError:
            # This database is from a time before extensions, so don't attempt
            # to load any extensions yet.
            pass

    signals.initializing.send(sender=None)