def decorator(request, *args, **kwargs):
        if (request.user.is_authenticated() and
                (request.session[BACKEND_SESSION_KEY] == "two_factor_light.backends.TwoFactorBackend" or
                    not request.user.two_factor_required
                 )):
            return view_func(request, *args, **kwargs)

        if not request.user.is_authenticated():
            # If user isn't authenticated, do the same as login_required - redirect to login
            resolved_redirect_url = resolve_url(login_url or settings.LOGIN_URL)
        elif request.user.two_factor_enabled:
            # If the user has two factor auth, redirect to two factor login url
            resolved_redirect_url = resolve_url(two_factor_login_url or TWO_FACTOR_LOGIN_URL)
        else:
            # The user hasn't setup two factor auth yet, so redirect to setup url
            resolved_redirect_url = resolve_url(two_factor_setup_url or TWO_FACTOR_SETUP_URL)

        path = request.build_absolute_uri()
        redirect_scheme, redirect_netloc = urlparse(resolved_redirect_url)[:2]
        current_scheme, current_netloc = urlparse(path)[:2]
        if ((not redirect_scheme or redirect_scheme == current_scheme) and
                (not redirect_netloc or redirect_netloc == current_netloc)):
            path = request.get_full_path()
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(
            path, resolved_redirect_url, redirect_field_name
        )
Ejemplo n.º 2
0
    def process_request(self, request):
        url = resolve(request.path_info)
        url_namespace = url.namespace
        url_name = url.url_name
        if url_namespace != 'control' or url_name in self.EXCEPTIONS:
            return
        if not request.user.is_authenticated():
            # Taken from django/contrib/auth/decorators.py
            path = request.build_absolute_uri()
            # urlparse chokes on lazy objects in Python 3, force to str
            resolved_login_url = force_str(
                resolve_url(settings.LOGIN_URL_CONTROL))
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, REDIRECT_FIELD_NAME)

        request.user.events_cache = request.user.events.order_by(
            "organizer", "date_from").prefetch_related("organizer")
        if 'event.' in url_name and 'event' in url.kwargs:
            try:
                request.event = Event.objects.get(
                    slug=url.kwargs['event'],
                    permitted__id__exact=request.user.id,
                    organizer__slug=url.kwargs['organizer'],
                )
            except Event.DoesNotExist:
                return HttpResponseNotFound(_("The selected event was not found or you have no permission to administrate it."))
Ejemplo n.º 3
0
    def load_prereqs(self, requester, storage):
        """Request the document, and process the redirects and response."""
        response = requester.request(self.source_path(),
                                     raise_for_status=False)
        if response.status_code not in (200, 301, 302):
            raise self.SourceError('status_code %s', response.status_code)
        data = {}

        # Is this a redirect?
        if response.history:
            redirect_from = urlparse(response.history[0].url).path
            redirect_to = urlparse(response.url).path
            if redirect_to != redirect_from:
                data['redirect_to'] = self.decode_href(redirect_to)

        # Is this a zone root?
        parsed = pq(response.content)
        body = parsed('body')
        if body.has_class('zone-landing'):
            data['is_zone_root'] = True

            # Find the zone stylesheet
            links = parsed('head link')
            for link in links:
                rel = link.attrib.get('rel')
                href = self.decode_href(link.attrib.get('href'))
                if rel == 'stylesheet' and href:
                    match = self.re_custom_href.match(href)
                    if match:
                        data['zone_css_slug'] = match.group('slug')

        return True, data
Ejemplo n.º 4
0
    def test_owner_or_mod_required_passes_url_parameters(self):
        @owner_or_moderator_required
        def mock_view(request, user, context):
            return None

        request = Mock(spec=('path', 'REQUEST', 'user'))
        request.user = AnonymousUser()
        request.REQUEST = {'abra': 'cadabra', 'foo': 'bar'}
        request.path = '/some/path/'
        user = self.create_user('user')
        response = mock_view(request, user, {})
        self.assertEqual(isinstance(response, HttpResponseRedirect), True)

        url = response['location']
        parsed_url = urlparse(url)

        self.assertEqual(parsed_url.path, reverse('user_signin'))

        next = dict(parse_qsl(parsed_url.query))['next']
        next_url = unquote(next)
        parsed_url = urlparse(next_url)

        self.assertEqual(parsed_url.path, request.path)

        query = dict(parse_qsl(parsed_url.query))
        self.assertEqual(set(query.keys()), set(['foo', 'abra']))
        self.assertEqual(set(query.values()), set(['bar', 'cadabra']))
        self.assertEqual(query['abra'], 'cadabra')
Ejemplo n.º 5
0
    def wrapped_view(request, *args, **kwargs):
        if request.user.is_authenticated:
            return view(request, *args, **kwargs)

        now = datetime.datetime.now()
        if 'AUTO_LOGIN_ATTEMPT' in request.session:
            auto_login_attempt = datetime.datetime.strptime(
                request.session['AUTO_LOGIN_ATTEMPT'], ISO_8601_format)
            if auto_login_attempt >= (now - RETRY_AFTER):
                return view(request, *args, **kwargs)

        # datetime needs to be JSON serializable:
        request.session['AUTO_LOGIN_ATTEMPT'] = now.isoformat()

        path = request.build_absolute_uri()
        attempt_only_login_url = (
            force_str(settings.LOGIN_URL) + '?attempt_login_only=true')

        login_scheme, login_netloc = urlparse(attempt_only_login_url)[:2]
        current_scheme, current_netloc = urlparse(path)[:2]

        if ((not login_scheme  # noqa: W503
             or login_scheme == current_scheme) and  # noqa: W504, W503
                (not login_netloc or login_netloc == current_netloc)):
            path = request.get_full_path()

        # the 'next' param is set with this redirect:
        return redirect_to_login(path, attempt_only_login_url)
Ejemplo n.º 6
0
 def _wrapped_view(request, *args, **kwargs):
     
     # First, check if the user has the permission (even anon users)
     try:
         _check_perms(perms, request.user, kwargs)
     except PermissionDenied:
         # In case the 403 handler should be called, raise the exception
         if raise_exception:
             raise
     else:
         return view_func(request, *args, **kwargs)
     
     # As the last resort, show the login form
     path = request.build_absolute_uri()
     resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
     
     # If the login url is the same scheme and net location then just
     # use the path as the "next" url.
     login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
     current_scheme, current_netloc = urlparse(path)[:2]
     
     if ((not login_scheme or login_scheme == current_scheme) and
             (not login_netloc or login_netloc == current_netloc)):
         path = request.get_full_path()
     
     from django.contrib.auth.views import redirect_to_login
     
     return redirect_to_login(path, resolved_login_url)
Ejemplo n.º 7
0
def same_origin(url1, url2):
    """
    Checks if two URLs share the same origin, IE the same protocol,
    host, and port.
    """
    p1, p2 = urlparse(url1), urlparse(url2)
    return (p1.scheme, p1.hostname, p1.port) == (p2.scheme, p2.hostname, p2.port)
Ejemplo n.º 8
0
 def build_links(self, request=None):
     links = {}
     if request is not None:
         links["self"] = request.build_absolute_uri(request.path)
         page = self._current_page
         if page is not None:
             if page.has_previous():
                 u = urlparse(links["self"])
                 q = parse_qs(u.query)
                 q["page[number]"] = str(page.previous_page_number())
                 links["prev"] = ParseResult(
                     u.scheme,
                     u.netloc,
                     u.path,
                     u.params,
                     urlencode(q),
                     u.fragment,
                 ).geturl()
             if page.has_next():
                 u = urlparse(links["self"])
                 q = parse_qs(u.query)
                 q["page[number]"] = str(page.next_page_number())
                 links["next"] = ParseResult(
                     u.scheme,
                     u.netloc,
                     u.path,
                     u.params,
                     urlencode(q),
                     u.fragment,
                 ).geturl()
     return links
Ejemplo n.º 9
0
        def _wrapped_view(request, *args, **kwargs):

            if check_perms(perms, request.user, kwargs['slug'], raise_exception=raise_exception):
                return view_func(request, *args, **kwargs)

            if request.user.is_authenticated():
                if WALIKI_RENDER_403:
                    return render(request, 'waliki/403.html', kwargs, status=403)
                else:
                    raise PermissionDenied

            path = request.build_absolute_uri()
            # urlparse chokes on lazy objects in Python 3, force to str
            resolved_login_url = force_str(
                resolve_url(login_url or settings.LOGIN_URL))
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
Ejemplo n.º 10
0
    def wrapper(request, *args, **kw):
        if request.user.is_authenticated():

            #setting collections data as a session var if not already set
            if "collections" not in request.session or request.session['collections'] is None:
                resp = t_collections(request)
                if isinstance(resp,HttpResponse): return resp

            # We check here to see if we are still authenticated with transkribus
            # a quick post request to auth/refresh should do?
            # If we get 401/403 redirect to logout if not 200 raise exception
            response = None
            try:
                response = function(request, *args, **kw)
            except requests.exceptions.HTTPError as e:
                t_log(e)
#                if e.status_code not in (401, 403):
#                    raise e
                response = HttpResponseRedirect(request.build_absolute_uri("/logout/?next={!s}".format(request.get_full_path())))

            return response
        else:
            path = request.build_absolute_uri()
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url. #TODO fix this after port from django source....
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
Ejemplo n.º 11
0
 def _wrapped_view(request, *args, **kwargs):
     if request.user.is_authenticated():
         if 'scan_id' in kwargs:
             scan_id = UUID(kwargs.get('scan_id'))
             try:
                 scan = IrmaScan.objects.get(irma_scan=scan_id)
             except IrmaScan.DoesNotExist:
                 return process_error(request, error=ERROR_NOT_FOUND)
             if (request.user == scan.user and request.user.has_perm('fir_irma.scan_files')) or \
                     request.user.has_perm('fir_irma.read_all_results'):
                 kwargs['scan'] = scan
                 return view_func(request, *args, **kwargs)
     elif settings.IRMA_ANONYMOUS_SCAN and settings.IRMA_IS_STANDALONE:
         if 'scan_id' in kwargs:
             scan_id = UUID(kwargs.get('scan_id'))
             client_ip = get_ip(request)
             try:
                 scan = IrmaScan.objects.get(irma_scan=scan_id, client_ip=client_ip)
                 kwargs['scan'] = scan
                 return view_func(request, *args, **kwargs)
             except IrmaScan.DoesNotExist:
                 return process_error(request, error=ERROR_NOT_FOUND)
     path = request.build_absolute_uri()
     resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
     # If the login url is the same scheme and net location then just
     # use the path as the "next" url.
     login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
     current_scheme, current_netloc = urlparse(path)[:2]
     if ((not login_scheme or login_scheme == current_scheme) and
             (not login_netloc or login_netloc == current_netloc)):
         path = request.get_full_path()
     from django.contrib.auth.views import redirect_to_login
     return redirect_to_login(
         path, resolved_login_url, redirect_field_name)
Ejemplo n.º 12
0
        def _wrapped_view(request, *args, **kwargs):

            try:
                course_title = request.path.split("/")[1]
                course = Course.objects.get(short_title=course_title)
            except (IndexError, Course.DoesNotExist):
                raise LookupError("aurora_login_required - can only be used when the url contains the course.")

            if request.user.is_authenticated() and (request.user.is_staff or course.user_is_enlisted(request.user)):
                return view_func(request, *args, **kwargs)

            path = request.build_absolute_uri()
            # urlparse chokes on lazy objects in Python 3, force to str
            resolved_login_url = force_str(
                resolve_url(settings.LOGIN_URL))
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, REDIRECT_FIELD_NAME)
Ejemplo n.º 13
0
 def _wrapped_view(request, *args, **kwargs):
     if request.user.is_authenticated():
         if not isinstance(perm, (list, tuple)):
             perms = (perm, )
         else:
             perms = perm
         if request.user.has_perms(perms):
             return view_func(request, *args, **kwargs)
         if unprivileged_url is not None:
             return redirect(unprivileged_url)
         return process_error(request, error=ERROR_UNAUTHORIZED)
     elif settings.IRMA_ANONYMOUS_SCAN and settings.IRMA_IS_STANDALONE:
         return view_func(request, *args, **kwargs)
     else:
         path = request.build_absolute_uri()
         resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
         # If the login url is the same scheme and net location then just
         # use the path as the "next" url.
         login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
         current_scheme, current_netloc = urlparse(path)[:2]
         if ((not login_scheme or login_scheme == current_scheme) and
                 (not login_netloc or login_netloc == current_netloc)):
             path = request.get_full_path()
         from django.contrib.auth.views import redirect_to_login
         return redirect_to_login(
             path, resolved_login_url, redirect_field_name)
Ejemplo n.º 14
0
    def _wrapped_view(request, *args, **kwargs):
        user = None
        token = None
        basic_auth = request.META.get('HTTP_AUTHORIZATION')

        user = request.POST.get('user', request.GET.get('user'))
        token = request.POST.get('token', request.GET.get('token'))

        if not (user and token) and basic_auth:
            auth_method, auth_string = basic_auth.split(' ', 1)

            if auth_method.lower() == 'basic':
                auth_string = auth_string.strip().decode('base64')
                user, token = auth_string.split(':', 1)

        path = request.build_absolute_uri()
        resolved_login_url = resolve_url(settings.LOGIN_URL)
        login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
        current_scheme, current_netloc = urlparse(path)[:2]
        if ((not login_scheme or login_scheme == current_scheme) and
            (not login_netloc or login_netloc == current_netloc)):
            path = request.get_full_path()
        from django.contrib.auth.views import redirect_to_login
        login_view = redirect_to_login(path, resolved_login_url, REDIRECT_FIELD_NAME)

        if not (user and token):
            if request.user.is_authenticated():
                return view_func(request, *args, **kwargs)
        else:
            user = authenticate(pk=user, token=token)
            if user:
                login(request, user)
                return view_func(request, *args, **kwargs)
        return login_view
Ejemplo n.º 15
0
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)

            if request.ACCEPT_FORMAT == 'json':
                return JsonResponse(
                        status = 401,
                        data = {
                            'error' : 'User does not authorized'
                            },
                        )
            elif request.ACCEPT_FORMAT == 'html':
                if not redirect:
                    return HttpResponse(
                            status = 401,
                            content = 'User does not authorized'
                            )
                else:
                    path = request.build_absolute_uri()
                    resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
                    # If the login url is the same scheme and net location then just
                    # use the path as the "next" url.
                    login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
                    current_scheme, current_netloc = urlparse(path)[:2]
                    if ((not login_scheme or login_scheme == current_scheme) and
                            (not login_netloc or login_netloc == current_netloc)):
                        path = request.get_full_path()
                    from django.contrib.auth.views import redirect_to_login
                    return redirect_to_login(
                        path, resolved_login_url, redirect_field_name)
            else:
                return HttpResponse(
                        status = 401,
                        content = 'User does not authorized'
                        )
Ejemplo n.º 16
0
    def wrapper(request, *args, **kw):	
        if request.user.is_authenticated():
	    # We check here to see if we are still authenticated with transkribus
	    # a quick post request ti auth/refresh should do?
	    # If we don't get a 200 we logout
    	    if not settings.OFFLINE:
	        if not services.t_refresh():
		    return HttpResponseRedirect('/library/logout?next='+request.get_full_path())
            #setting collections data as a session var if no already set
	    if "collections" not in request.session or request.session['collections'] is None:
	        request.session['collections'] = services.t_collections()
            return function(request, *args, **kw)
        else:
	    path = request.build_absolute_uri()
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url. #TODO fix this after port from django source....
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
Ejemplo n.º 17
0
 def build_callback_url(self, request, jump_url):
     callback = request.build_absolute_uri()
     login_scheme, login_netloc = urlparse(jump_url)[:2]
     current_scheme, current_netloc = urlparse(callback)[:2]
     if ((not login_scheme or login_scheme == current_scheme) and
             (not login_netloc or login_netloc == current_netloc)):
         callback = request.get_full_path()
     return callback
Ejemplo n.º 18
0
Archivo: http.py Proyecto: 8jo/django
def same_origin(url1, url2):
    """
    Checks if two URLs are 'same-origin'
    """
    p1, p2 = urlparse(url1), urlparse(url2)
    try:
        return (p1.scheme, p1.hostname, p1.port) == (p2.scheme, p2.hostname, p2.port)
    except ValueError:
        return False
Ejemplo n.º 19
0
def same_origin(url1, url2):
    """
    Checks if two URLs are 'same-origin'
    """
    p1, p2 = urlparse(url1), urlparse(url2)
    try:
        o1 = (p1.scheme, p1.hostname, p1.port or PROTOCOL_TO_PORT[p1.scheme])
        o2 = (p2.scheme, p2.hostname, p2.port or PROTOCOL_TO_PORT[p2.scheme])
        return o1 == o2
    except (ValueError, KeyError):
        return False
Ejemplo n.º 20
0
 def _wrapped_view(self, request, *args, **kwargs):
     if test_func(request.user):
         return view_func(self, request, *args, **kwargs)
     path = request.build_absolute_uri()
     resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
     login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
     current_scheme, current_netloc = urlparse(path)[:2]
     if ((not login_scheme or login_scheme == current_scheme) and
             (not login_netloc or login_netloc == current_netloc)):
         path = request.get_full_path()
     from django.contrib.auth.views import redirect_to_login
     return redirect_to_login(
         path, resolved_login_url, redirect_field_name)
Ejemplo n.º 21
0
def redirect_to_login(request, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    path = request.build_absolute_uri()
    resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
    # If the login url is the same scheme and net location then just
    # use the path as the "next" url.
    login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
    current_scheme, current_netloc = urlparse(path)[:2]
    if ((not login_scheme or login_scheme == current_scheme) and
        (not login_netloc or login_netloc == current_netloc)):
        path = request.get_full_path()
    from django.contrib.auth.views import redirect_to_login
    return redirect_to_login(
        path, resolved_login_url, redirect_field_name)
Ejemplo n.º 22
0
    def test_assertion_consumer_service(self):
        # Get initial number of users
        initial_user_count = User.objects.count()
        settings.SAML_CONFIG = conf.create_conf(
            sp_host='sp.example.com',
            idp_hosts=['idp.example.com'],
            metadata_file='remote_metadata_one_idp.xml',
        )

        self.init_cookies()

        # session_id should start with a letter since it is a NCName
        session_id = "a0123456789abcdef0123456789abcdef"
        came_from = '/another-view/'
        self.add_outstanding_query(session_id, came_from)

        # this will create a user
        saml_response = auth_response(session_id, 'student')
        response = self.client.post(reverse('saml2_acs'), {
                'SAMLResponse': self.b64_for_post(saml_response),
                'RelayState': came_from,
                })
        self.assertEquals(response.status_code, 302)
        location = response['Location']
        url = urlparse(location)
        self.assertEquals(url.path, came_from)

        self.assertEquals(User.objects.count(), initial_user_count + 1)
        user_id = self.client.session[SESSION_KEY]
        user = User.objects.get(id=user_id)
        self.assertEquals(user.username, 'student')

        # let's create another user and log in with that one
        new_user = User.objects.create(username='******', password='******')

        session_id = "a1111111111111111111111111111111"
        came_from = ''  # bad, let's see if we can deal with this
        saml_response = auth_response(session_id, 'teacher')
        self.add_outstanding_query(session_id, '/')
        response = self.client.post(reverse('saml2_acs'), {
                'SAMLResponse': self.b64_for_post(saml_response),
                'RelayState': came_from,
                })
        self.assertEquals(response.status_code, 302)
        location = response['Location']

        url = urlparse(location)
        # as the RelayState is empty we have redirect to LOGIN_REDIRECT_URL
        self.assertEquals(url.path, '/accounts/profile/')
        self.assertEquals(force_text(new_user.id), self.client.session[SESSION_KEY])
Ejemplo n.º 23
0
    def test_login_one_idp(self):
        # monkey patch SAML configuration
        settings.SAML_CONFIG = conf.create_conf(
            sp_host='sp.example.com',
            idp_hosts=['idp.example.com'],
            metadata_file='remote_metadata_one_idp.xml',
        )

        response = self.client.get(reverse('saml2_login'))
        self.assertEquals(response.status_code, 302)
        location = response['Location']

        url = urlparse(location)
        self.assertEquals(url.hostname, 'idp.example.com')
        self.assertEquals(url.path, '/simplesaml/saml2/idp/SSOService.php')

        params = parse_qs(url.query)
        self.assert_('SAMLRequest' in params)
        self.assert_('RelayState' in params)

        saml_request = params['SAMLRequest'][0]
        if PY_VERSION < (2, 7):
            expected_request = """<?xml version='1.0' encoding='UTF-8'?>
<samlp:AuthnRequest AssertionConsumerServiceURL="http://sp.example.com/saml2/acs/" Destination="https://idp.example.com/simplesaml/saml2/idp/SSOService.php" ID="XXXXXXXXXXXXXXXXXXXXXX" IssueInstant="2010-01-01T00:00:00Z" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"><saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">http://sp.example.com/saml2/metadata/</saml:Issuer><samlp:NameIDPolicy AllowCreate="false" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" /></samlp:AuthnRequest>"""
        elif PY_VERSION < (3,):
            expected_request = """<?xml version='1.0' encoding='UTF-8'?>
<samlp:AuthnRequest xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" AssertionConsumerServiceURL="http://sp.example.com/saml2/acs/" Destination="https://idp.example.com/simplesaml/saml2/idp/SSOService.php" ID="XXXXXXXXXXXXXXXXXXXXXX" IssueInstant="2010-01-01T00:00:00Z" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Version="2.0"><saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">http://sp.example.com/saml2/metadata/</saml:Issuer><samlp:NameIDPolicy AllowCreate="false" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" /></samlp:AuthnRequest>"""
        else:
            expected_request = """<samlp:AuthnRequest xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" AssertionConsumerServiceURL="http://sp.example.com/saml2/acs/" Destination="https://idp.example.com/simplesaml/saml2/idp/SSOService.php" ID="XXXXXXXXXXXXXXXXXXXXXX" IssueInstant="2010-01-01T00:00:00Z" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Version="2.0"><saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">http://sp.example.com/saml2/metadata/</saml:Issuer><samlp:NameIDPolicy AllowCreate="false" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" /></samlp:AuthnRequest>"""

        self.assertSAMLRequestsEquals(
            decode_base64_and_inflate(saml_request).decode('utf-8'),
            expected_request)

        # if we set a next arg in the login view, it is preserverd
        # in the RelayState argument
        next = '/another-view/'
        response = self.client.get(reverse('saml2_login'), {'next': next})
        self.assertEquals(response.status_code, 302)
        location = response['Location']

        url = urlparse(location)
        self.assertEquals(url.hostname, 'idp.example.com')
        self.assertEquals(url.path, '/simplesaml/saml2/idp/SSOService.php')

        params = parse_qs(url.query)
        self.assert_('SAMLRequest' in params)
        self.assert_('RelayState' in params)
        self.assertEquals(params['RelayState'][0], next)
Ejemplo n.º 24
0
		def _wrapped_view(request, *args, **kwargs):
			if test_func(request.user):
				return view_func(request, *args, **kwargs)

			if message:
				messages.add_message(request, messages.ERROR, message)

			path = request.build_absolute_uri()
			resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
			login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
			current_scheme, current_netloc = urlparse(path)[:2]

			if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)):
				path = request.get_full_path()
			return redirect_to_login(path, resolved_login_url, redirect_field_name)
Ejemplo n.º 25
0
		def _wrapped_view(request,*args,**kwargs):
			if not request.user.is_authenticated():
				path = request.build_absolute_uri()
				resolved_login_url = resolve_url(Login_url or settings.LOGIN_URL)
				login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
				current_scheme, current_netloc = urlparse(path)[:2]
				if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)):
					path = request.get_full_path()
				return redirect_to_login(path, resolved_login_url, redirect_field_name)
			if test_func(request.user,*args,**kwargs):
				return view_func(request, *args, **kwargs)
			elif redirect_template == None:
				raise PermissionDenied
			else:
				return TemplateResponse(request,redirect_template,redirect_context)
def assertUrisEqual(testcase, expected, actual):
  """Test that URIs are the same, up to reordering of query parameters."""
  expected = urlparse(expected)
  actual = urlparse(actual)
  testcase.assertEqual(expected.scheme, actual.scheme)
  testcase.assertEqual(expected.netloc, actual.netloc)
  testcase.assertEqual(expected.path, actual.path)
  testcase.assertEqual(expected.params, actual.params)
  testcase.assertEqual(expected.fragment, actual.fragment)
  expected_query = parse_qs(expected.query)
  actual_query = parse_qs(actual.query)
  for name in list(expected_query.keys()):
    testcase.assertEqual(expected_query[name], actual_query[name])
  for name in list(actual_query.keys()):
    testcase.assertEqual(expected_query[name], actual_query[name])
Ejemplo n.º 27
0
 def _wrapped_view(request, *args, **kwargs):
     if test_func(request): 
         return view_func(request, *args, **kwargs)
     path = request.build_absolute_uri()
     resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
     # If the login url is the same scheme and net location then just
     # use the path as the "next" url.
     login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
     current_scheme, current_netloc = urlparse(path)[:2]
     if ((not login_scheme or login_scheme == current_scheme) and
             (not login_netloc or login_netloc == current_netloc)):
         path = request.get_full_path()
     from django.contrib.auth.views import redirect_to_login
     return redirect_to_login(
         path, resolved_login_url, redirect_field_name)
Ejemplo n.º 28
0
Archivo: views.py Proyecto: rutube/alco
    def get_redirect_url(self, *args, **kwargs):
        obj = self.get_object()
        url = parse.urlparse(obj.url)
        query_params = copy(self.request.GET)
        lookup = self.kwargs.get('default_value')
        if lookup and obj.default_field:
            query_params[obj.default_field.name] = lookup

        query_params.update(**dict(parse.parse_qsl(url.query)))

        url = reverse('grep_view', kwargs={'name': obj.index.name})
        url = parse.urlparse(url)
        parts = list(url)
        parts[4] = parse.urlencode(query_params)
        return parse.urlunparse(parts)
Ejemplo n.º 29
0
    def clean_hosting_url(self):
        """Clean the hosting_url field.

        This method ensures that the URL has a scheme.

        Returns:
            unicode: The URL.

        Raises:
            django.core.exceptions.ValidationError:
                The URL was missing a scheme.
        """
        hosting_url = self.cleaned_data['hosting_url']
        result = urlparse(hosting_url)

        if not result.scheme:
            raise ValidationError(
                _('Invalid hosting URL "%(url)s": missing scheme (e.g., HTTP '
                  'or HTTPS)')
                % {
                    'url': hosting_url,
                }
            )

        return hosting_url
Ejemplo n.º 30
0
def format_url_replacement(url, text):
    url = url.strip()
    text = text.strip()
    url_domain = urlparse(url).netloc
    if url and text and url_domain != text and url != text:
        return '%s (%s)' % (url, text)
    return url or text or ''
Ejemplo n.º 31
0
def store_file(file_object, file_name_prefix=''):
    """Creates an instance of django's file storage
    object based on the file-like object,
    returns the storage object, file name, file url
    """
    file_ext = os.path.splitext(file_object.name)[1].lower()
    file_name = make_file_name(file_ext, file_name_prefix)
    file_storage = get_storage_class()()
    # use default storage to store file
    file_storage.save(file_name, file_object)

    file_url = file_storage.url(file_name)
    parsed_url = urlparse(file_url)
    file_url = urlunparse(
        ParseResult(
            parsed_url.scheme,
            parsed_url.netloc,
            parsed_url.path,
            '', '', ''
        )
    )

    return file_storage, file_name, file_url
Ejemplo n.º 32
0
def as_signed_url(location, request):
    parts = urlparse(location)
    bucket_name = parts.netloc.split('.')[0]
    key_name = parts.path
    if bucket_name.startswith('s3-'):
        name_parts = key_name.split('/')
        if name_parts and not name_parts[0]:
            name_parts.pop(0)
        bucket_name = name_parts[0]
        key_name = '/'.join(name_parts[1:])
    if key_name.startswith('/'):
        # we rename leading '/' otherwise S3 copy triggers a 404
        # because it creates an URL with '//'.
        key_name = key_name[1:]
    kwargs = {}
    for key in ['access_key', 'secret_key', 'security_token']:
        if key in request.session:
            kwargs[key] = request.session[key]
    if not kwargs:
        LOGGER.error("called `as_signed_url(bucket_name=%s, key_name=%s)`"\
            " with no credentials.", bucket_name, key_name)
    s3_storage = S3BotoStorage(bucket=bucket_name, **kwargs)
    return s3_storage.url(key_name)
Ejemplo n.º 33
0
    def _decode_location(self, location):
        """Return splitted configuration data from location."""
        splitted_url = urlparse.urlparse(location)
        config = {}

        if splitted_url.scheme not in ('ftp', 'aftp'):
            raise ImproperlyConfigured(
                'FTPStorage works only with FTP protocol!'
            )
        if splitted_url.hostname == '':
            raise ImproperlyConfigured('You must at least provide hostname!')

        if splitted_url.scheme == 'aftp':
            config['active'] = True
        else:
            config['active'] = False
        config['path'] = splitted_url.path
        config['host'] = splitted_url.hostname
        config['user'] = splitted_url.username
        config['passwd'] = splitted_url.password
        config['port'] = int(splitted_url.port)

        return config
    def _https_referer_replace(self, request):
        """
        When https is enabled, django CSRF checking includes referer checking
        which breaks when using CORS. This function updates the HTTP_REFERER
        header to make sure it matches HTTP_HOST, provided that our cors logic
        succeeds
        """
        origin = request.META.get('HTTP_ORIGIN')

        if request.is_secure() and origin and 'ORIGINAL_HTTP_REFERER' not in request.META:

            url = urlparse(origin)
            if not conf.CORS_ORIGIN_ALLOW_ALL and not self.origin_found_in_white_lists(origin, url):
                return

            try:
                http_referer = request.META['HTTP_REFERER']
                http_host = "https://%s/" % request.META['HTTP_HOST']
                request.META = request.META.copy()
                request.META['ORIGINAL_HTTP_REFERER'] = http_referer
                request.META['HTTP_REFERER'] = http_host
            except KeyError:
                pass
Ejemplo n.º 35
0
    def clean_hosting_url(self):
        """Clean the hosting_url field.

        This method ensures that the URL has a scheme.

        Returns:
            unicode: The URL.

        Raises:
            django.core.exceptions.ValidationError:
                The URL was missing a scheme.
        """
        hosting_url = self.cleaned_data['hosting_url']
        result = urlparse(hosting_url)

        if not result.scheme:
            raise ValidationError(
                _('Invalid hosting URL "%(url)s": missing scheme (e.g., HTTP '
                  'or HTTPS)') % {
                      'url': hosting_url,
                  })

        return hosting_url
Ejemplo n.º 36
0
    def get_build_path(self, obj):
        url = self.get_url(obj)

        if url.startswith('http'):
            # Multisite has absolute urls
            url_parsed = urlparse(url)
            path = url_parsed.path
            hostname = url_parsed.hostname

            if getattr(settings, 'BAKERY_MULTISITE', False):
                build_path = os.path.join(
                    settings.BUILD_DIR, hostname, path[1:])
            else:
                build_path = os.path.join(settings.BUILD_DIR, path[1:])
        else:
            # Single site has relative urls
            build_path = os.path.join(settings.BUILD_DIR, url[1:])

        # Make sure the (deeply) directories are created
        os.path.exists(build_path) or os.makedirs(build_path)

        # Always append index.html at the end of the path
        return os.path.join(build_path, 'index.html')
Ejemplo n.º 37
0
    def clean(self):
        projects = OrderedDict()  # using this since sets aren't ordered

        if self.requirements is None:
            self.requirements = []
        for requirement in self.requirements:
            url = urlparse(requirement)
            if url.scheme in ('http', 'https', 'file'):
                requirement = [sanitize_github_url(requirement, url)]
                try:
                    for project in projects_from_requirements(requirement):
                        projects[project] = None
                except:
                    raise ValidationError("Couldn't check %s." % requirement)
            else:
                projects[requirement] = None

        self.projects = list(projects.keys())

        for index, project_name in enumerate(self.projects):
            validators.RegexValidator(project_name_re,
                                      'Project %s invalid' %
                                      project_name)(project_name)
Ejemplo n.º 38
0
 def configure_from_settings(self, settings):
     # Default configuration
     self.autorefresh = settings.DEBUG
     self.use_finders = settings.DEBUG
     self.static_prefix = urlparse(settings.STATIC_URL or '').path
     if settings.FORCE_SCRIPT_NAME:
         script_name = settings.FORCE_SCRIPT_NAME.rstrip('/')
         if self.static_prefix.startswith(script_name):
             self.static_prefix = self.static_prefix[len(script_name):]
     if settings.DEBUG:
         self.max_age = 0
     # Allow settings to override default attributes
     for attr in self.config_attrs:
         settings_key = 'WHITENOISE_{0}'.format(attr.upper())
         try:
             value = getattr(settings, settings_key)
         except AttributeError:
             pass
         else:
             value = decode_if_byte_string(value)
             setattr(self, attr, value)
     self.static_prefix = ensure_leading_trailing_slash(self.static_prefix)
     self.static_root = decode_if_byte_string(settings.STATIC_ROOT)
Ejemplo n.º 39
0
 def passthrough_shipping_label(self, request):
     label_url = request.GET.get('url')
     res = requests.get(label_url, auth=self.credentials)
     if res.status_code == 200:
         # mark the parcel label as printed
         try:
             parcel_id = urlparse(label_url).path.split('/')[-1]
             delivery = DeliveryModel.objects.get(shipping_id=parcel_id)
         except DeliveryModel.DoesNotExist:
             parcel_id = None
         else:
             delivery.shipped_at = timezone.now()
             delivery.save(update_fields=['shipped_at'])
     else:
         parcel_id = None
     response = HttpResponse(res.content,
                             status=res.status_code,
                             content_type=res.headers['content-type'])
     if parcel_id:
         response[
             'Content-Disposition'] = 'filename="parcel_label_{}.pdf"'.format(
                 parcel_id)
     return response
Ejemplo n.º 40
0
    def test_logout_service_global(self):
        settings.SAML_CONFIG = conf.create_conf(
            sp_host='sp.example.com',
            idp_hosts=['idp.example.com'],
            metadata_file='remote_metadata_one_idp.xml',
        )

        self.do_login()

        # now simulate a global logout process initiated by another SP
        subject_id = views._get_subject_id(self.client.session)
        instant = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
        saml_request = """<?xml version='1.0' encoding='UTF-8'?>
<samlp:LogoutRequest xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="_9961abbaae6d06d251226cb25e38bf8f468036e57e" Version="2.0" IssueInstant="%s" Destination="http://sp.example.com/saml2/ls/"><saml:Issuer>https://idp.example.com/simplesaml/saml2/idp/metadata.php</saml:Issuer><saml:NameID SPNameQualifier="http://sp.example.com/saml2/metadata/" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient">%s</saml:NameID><samlp:SessionIndex>_1837687b7bc9faad85839dbeb319627889f3021757</samlp:SessionIndex></samlp:LogoutRequest>""" % (instant, subject_id.text)

        response = self.client.get(reverse('saml2_ls'), {
                'SAMLRequest': deflate_and_base64_encode(saml_request),
                })
        self.assertEqual(response.status_code, 302)
        location = response['Location']

        url = urlparse(location)
        self.assertEqual(url.hostname, 'idp.example.com')
        self.assertEqual(url.path,
                         '/simplesaml/saml2/idp/SingleLogoutService.php')

        params = parse_qs(url.query)
        self.assertIn('SAMLResponse', params)

        saml_response = params['SAMLResponse'][0]
        if PY_VERSION < (3,):
            expected_response = """<?xml version='1.0' encoding='UTF-8'?>
<samlp:LogoutResponse xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Destination="https://idp.example.com/simplesaml/saml2/idp/SingleLogoutService.php" ID="a140848e7ce2bce834d7264ecdde0151" InResponseTo="_9961abbaae6d06d251226cb25e38bf8f468036e57e" IssueInstant="2010-09-05T09:10:12Z" Version="2.0"><saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">http://sp.example.com/saml2/metadata/</saml:Issuer><samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" /></samlp:Status></samlp:LogoutResponse>"""
        else:
            expected_response = """<samlp:LogoutResponse xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Destination="https://idp.example.com/simplesaml/saml2/idp/SingleLogoutService.php" ID="a140848e7ce2bce834d7264ecdde0151" InResponseTo="_9961abbaae6d06d251226cb25e38bf8f468036e57e" IssueInstant="2010-09-05T09:10:12Z" Version="2.0"><saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">http://sp.example.com/saml2/metadata/</saml:Issuer><samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" /></samlp:Status></samlp:LogoutResponse>"""
        self.assertSAMLRequestsEquals(decode_base64_and_inflate(saml_response).decode('utf-8'),
                                      expected_response)
Ejemplo n.º 41
0
    def __init__(self, params):
        super(ElasticSearch, self).__init__(params)

        # Get settings
        self.es_hosts = params.pop('HOSTS', None)
        self.es_index = params.pop('INDEX', 'wagtail')
        self.es_timeout = params.pop('TIMEOUT', 10)

        # If HOSTS is not set, convert URLS setting to HOSTS
        es_urls = params.pop('URLS', ['http://localhost:9200'])
        if self.es_hosts is None:
            self.es_hosts = []

            for url in es_urls:
                parsed_url = urlparse(url)

                use_ssl = parsed_url.scheme == 'https'
                port = parsed_url.port or (443 if use_ssl else 80)

                http_auth = None
                if parsed_url.username is not None and parsed_url.password is not None:
                    http_auth = (parsed_url.username, parsed_url.password)

                self.es_hosts.append({
                    'host': parsed_url.hostname,
                    'port': port,
                    'url_prefix': parsed_url.path,
                    'use_ssl': use_ssl,
                    'http_auth': http_auth,
                })

        # Get ElasticSearch interface
        # Any remaining params are passed into the ElasticSearch constructor
        self.es = Elasticsearch(
            hosts=self.es_hosts,
            timeout=self.es_timeout,
            **params)
Ejemplo n.º 42
0
    def test_login_several_idps(self):
        settings.SAML_CONFIG = conf.create_conf(
            sp_host='sp.example.com',
            idp_hosts=[
                'idp1.example.com', 'idp2.example.com', 'idp3.example.com'
            ],
            metadata_file='remote_metadata_three_idps.xml',
        )
        response = self.client.get(reverse('saml2_login'))
        # a WAYF page should be displayed
        self.assertContains(response, 'Where are you from?', status_code=200)
        for i in range(1, 4):
            link = '/login/?idp=https://idp%d.example.com/simplesaml/saml2/idp/metadata.php&next=/'
            self.assertContains(response, link % i)

        # click on the second idp
        response = self.client.get(
            reverse('saml2_login'), {
                'idp':
                'https://idp2.example.com/simplesaml/saml2/idp/metadata.php',
                'next': '/',
            })
        self.assertEqual(response.status_code, 302)
        location = response['Location']

        url = urlparse(location)
        self.assertEqual(url.hostname, 'idp2.example.com')
        self.assertEqual(url.path, '/simplesaml/saml2/idp/SSOService.php')

        params = parse_qs(url.query)
        self.assertIn('SAMLRequest', params)
        self.assertIn('RelayState', params)

        saml_request = params['SAMLRequest'][0]
        if 'AuthnRequest xmlns' not in decode_base64_and_inflate(
                saml_request).decode('utf-8'):
            raise Exception('Not a valid AuthnRequest')
Ejemplo n.º 43
0
def purge_page_from_cache(page, backend_settings=None, backends=None):
    page_url = page.full_url
    if page_url is None:  # nothing to be done if the page has no routable URL
        return

    if settings.USE_I18N:
        langs_regex = "^/(%s)/" % "|".join([l[0] for l in settings.LANGUAGES])

    for backend_name, backend in get_backends(
            backend_settings=backend_settings, backends=backends).items():
        # Purge cached paths from cache
        for path in page.specific.get_cached_paths():
            if settings.USE_I18N:
                _purged_urls = []
                # Purge the given url for each managed language instead of just the one with the current language
                for isocode, description in settings.LANGUAGES:
                    up = urlparse(page_url)
                    new_page_url = urlunparse(
                        (up.scheme, up.netloc,
                         re.sub(langs_regex, "/%s/" % isocode,
                                up.path), up.params, up.query, up.fragment))

                    purge_url = new_page_url + path[1:]
                    # Check for best performance. True if re.sub found no match
                    # It happens when i18n_patterns was not used in urls.py to serve content for different languages from different URLs
                    if purge_url in _purged_urls:
                        continue

                    logger.info("[%s] Purging URL: %s", backend_name,
                                purge_url)
                    backend.purge(purge_url)

                    _purged_urls.append(purge_url)
            else:
                logger.info("[%s] Purging URL: %s", backend_name,
                            page_url + path[1:])
                backend.purge(page_url + path[1:])
Ejemplo n.º 44
0
def add_preserved_filters(context, url, popup=False, to_field=None):
    opts = context.get('opts')
    preserved_filters = context.get('preserved_filters')

    parsed_url = list(urlparse(url))
    parsed_qs = dict(parse_qsl(parsed_url[4]))
    merged_qs = dict()

    if opts and preserved_filters:
        preserved_filters = dict(parse_qsl(preserved_filters))

        match_url = '/%s' % url.partition(get_script_prefix())[2]
        try:
            match = resolve(match_url)
        except Resolver404:
            pass
        else:
            current_url = '%s:%s' % (match.app_name, match.url_name)
            changelist_url = 'admin:%s_%s_changelist' % (opts.app_label,
                                                         opts.model_name)
            if changelist_url == current_url and '_changelist_filters' in preserved_filters:
                preserved_filters = dict(
                    parse_qsl(preserved_filters['_changelist_filters']))

        merged_qs.update(preserved_filters)

    if popup:
        from django.contrib.admin.options import IS_POPUP_VAR
        merged_qs[IS_POPUP_VAR] = 1
    if to_field:
        from django.contrib.admin.options import TO_FIELD_VAR
        merged_qs[TO_FIELD_VAR] = to_field

    merged_qs.update(parsed_qs)

    parsed_url[4] = urlencode(merged_qs)
    return urlunparse(parsed_url)
Ejemplo n.º 45
0
def add_preserved_filters(context, url, popup=False, to_field=None):
    opts = context.get('opts')
    preserved_filters = context.get('preserved_filters')

    parsed_url = list(urlparse(url))
    parsed_qs = dict(parse_qsl(parsed_url[4]))
    merged_qs = dict()

    if opts and preserved_filters:
        preserved_filters = dict(parse_qsl(preserved_filters))

        match_url = '/{0}'.format(url.partition(get_script_prefix())[2])
        try:
            match = resolve(match_url)
        except Resolver404:
            pass
        else:
            current_url = '{0}:{1}'.format(match.app_name, match.url_name)
            changelist_url = 'desk:{0}_{1}_changelist'.format(
                opts.app_label, opts.model_name)
            if (current_url == changelist_url
                    and '_changelist_filters' in preserved_filters):
                preserved_filters = dict(
                    parse_qsl(preserved_filters['_changelist_filters']))

        merged_qs.update(preserved_filters)

    if popup:
        merged_qs[IS_POPUP_VAR] = 1

    if to_field:
        merged_qs[TO_FIELD_VAR] = to_field

    merged_qs.update(parsed_qs)

    parsed_url[4] = urlencode(merged_qs)
    return urlunparse(parsed_url)
Ejemplo n.º 46
0
def get_thread_id_from_url(request, url):
    try:
        clean_url = six.text_type(url).strip()
        bits = urlparse(clean_url)
    except:
        return None

    if bits.netloc and bits.netloc != request.get_host():
        return None

    if bits.path.startswith(request.get_host()):
        clean_path = bits.path.lstrip(request.get_host())
    else:
        clean_path = bits.path

    try:
        wsgi_alias = request.path[:len(request.path_info) * -1]
        if wsgi_alias and not clean_path.startswith(wsgi_alias):
            return None
        resolution = resolve(clean_path[len(wsgi_alias):])
    except:
        return None

    if not resolution.namespaces:
        return None

    url_name = '{}:{}'.format(':'.join(resolution.namespaces),
                              resolution.url_name)
    kwargname = SUPPORTED_THREAD_ROUTES.get(url_name)

    if not kwargname:
        return None

    try:
        return int(resolution.kwargs.get(kwargname))
    except (TypeError, ValueError):
        return None
Ejemplo n.º 47
0
    def purge_batch(self, urls):
        paths_by_distribution_id = defaultdict(list)

        for url in urls:
            url_parsed = urlparse(url)
            distribution_id = None

            if isinstance(self.cloudfront_distribution_id, dict):
                host = url_parsed.hostname
                if host in self.cloudfront_distribution_id:
                    distribution_id = self.cloudfront_distribution_id.get(host)
                else:
                    logger.info(
                        "Couldn't purge '%s' from CloudFront. Hostname '%s' not found in the DISTRIBUTION_ID mapping",
                        url, host)
            else:
                distribution_id = self.cloudfront_distribution_id

            if distribution_id:
                paths_by_distribution_id[distribution_id].append(
                    url_parsed.path)

        for distribution_id, paths in paths_by_distribution_id.items():
            self._create_invalidation(distribution_id, paths)
Ejemplo n.º 48
0
def is_safe_url(url, host=None):
    """
    Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
    a different host and uses a safe scheme).

    Always returns ``False`` on an empty url.
    """
    if not url:
        return False
    # Chrome treats \ completely as /
    url = url.replace('\\', '/')
    # Chrome considers any URL with more than two slashes to be absolute, but
    # urlparse is not so flexible. Treat any url with three slashes as unsafe.
    if url.startswith('///'):
        return False
    url_info = urlparse(url)
    # Forbid URLs like http:///example.com - with a scheme, but without a hostname.
    # In that URL, example.com is not the hostname but, a path component. However,
    # Chrome will still consider example.com to be the hostname, so we must not
    # allow this syntax.
    if not url_info.netloc and url_info.scheme:
        return False
    return ((not url_info.netloc or url_info.netloc == host) and
            (not url_info.scheme or url_info.scheme in ['http', 'https']))
Ejemplo n.º 49
0
    def download_image_url(self, url):
        from cropduster.models import StandaloneImage
        from cropduster.views.forms import clean_upload_data

        image_contents = urlopen(url).read()
        md5_hash = hashlib.md5()
        md5_hash.update(image_contents)
        try:
            standalone_image = StandaloneImage.objects.get(
                md5=md5_hash.hexdigest())
        except StandaloneImage.DoesNotExist:
            pass
        else:
            return get_relative_media_url(standalone_image.image.name)

        parse_result = urlparse.urlparse(url)

        fake_upload = SimpleUploadedFile(os.path.basename(parse_result.path),
                                         image_contents)
        file_data = clean_upload_data({
            'image': fake_upload,
            'upload_to': self.upload_to,
        })
        return get_relative_media_url(file_data['image'].name)
Ejemplo n.º 50
0
    def is_safe_url(self, url, host=None):
        """
        判断url是否与当前host的根域一致

        以下情况返回False:
            1)根域不一致
            2)url的scheme不为:https(s)
            3)url为空
        """
        if url is not None:
            url = url.strip()
        if not url:
            return False
        # Chrome treats \ completely as /
        url = url.replace('\\', '/')
        # Chrome considers any URL with more than two slashes to be absolute, but
        # urlparse is not so flexible. Treat any url with three slashes as unsafe.
        if url.startswith('///'):
            return False
        url_info = urlparse(url)
        # Forbid URLs like http:///example.com - with a scheme, but without a hostname.
        # In that URL, example.com is not the hostname but, a path component. However,
        # Chrome will still consider example.com to be the hostname, so we must not
        # allow this syntax.
        if not url_info.netloc and url_info.scheme:
            return False
        # Forbid URLs that start with control characters. Some browsers (like
        # Chrome) ignore quite a few control characters at the start of a
        # URL and might consider the URL as scheme relative.
        if unicodedata.category(url[0])[0] == 'C':
            return False
        url_domain = url_info.netloc.split(':')[0].split(
            '.')[-2] if url_info.netloc else ''
        host_domain = host.split(':')[0].split('.')[-2] if host else ''
        return ((not url_info.netloc or url_domain == host_domain) and
                (not url_info.scheme or url_info.scheme in ['http', 'https']))
Ejemplo n.º 51
0
Archivo: http.py Proyecto: waspa/django
def _is_safe_url(url, allowed_hosts, require_https=False):
    # Chrome considers any URL with more than two slashes to be absolute, but
    # urlparse is not so flexible. Treat any url with three slashes as unsafe.
    if url.startswith('///'):
        return False
    url_info = urlparse(url)
    # Forbid URLs like http:///example.com - with a scheme, but without a hostname.
    # In that URL, example.com is not the hostname but, a path component. However,
    # Chrome will still consider example.com to be the hostname, so we must not
    # allow this syntax.
    if not url_info.netloc and url_info.scheme:
        return False
    # Forbid URLs that start with control characters. Some browsers (like
    # Chrome) ignore quite a few control characters at the start of a
    # URL and might consider the URL as scheme relative.
    if unicodedata.category(url[0])[0] == 'C':
        return False
    scheme = url_info.scheme
    # Consider URLs without a scheme (e.g. //example.com/p) to be http.
    if not url_info.scheme and url_info.netloc:
        scheme = 'http'
    valid_schemes = ['https'] if require_https else ['http', 'https']
    return ((not url_info.netloc or url_info.netloc in allowed_hosts) and
            (not scheme or scheme in valid_schemes))
Ejemplo n.º 52
0
 def generic(self,
             method,
             path,
             data='',
             content_type='application/octet-stream',
             **extra):
     """Constructs an arbitrary HTTP request."""
     parsed = urlparse(path)
     data = force_bytes(data, settings.DEFAULT_CHARSET)
     r = {
         'PATH_INFO': self._get_path(parsed),
         'REQUEST_METHOD': str(method),
     }
     if data:
         r.update({
             'CONTENT_LENGTH': len(data),
             'CONTENT_TYPE': str(content_type),
             'wsgi.input': FakePayload(data),
         })
     r.update(extra)
     # If QUERY_STRING is absent or empty, we want to extract it from the URL.
     if not r.get('QUERY_STRING'):
         r['QUERY_STRING'] = force_str(parsed[4])
     return self.request(**r)
Ejemplo n.º 53
0
    def clean(self):
        if not self.created:
            self.created = timezone.now()

        article = (
            Article.objects.only('is_comment_allowed')
            .filter(pk=self.article_id).first()
        )
        if not getattr(article, 'is_comment_allowed', False):
            raise PermissionDenied()

        spam = SpamSnippet.objects.values_list('snippet')
        fields = (self.user_name, self.user_email, self.user_url, self.content)
        for (snippet, ) in spam:
            if any(snippet.lower() in field.lower() for field in fields):
                raise PermissionDenied()

        if (self.user_name.startswith('http://') or
                self.user_name.endswith(('.com', '.org', '.net'))):
            raise ValidationError({
                'user_name': [_('Links are not allowed here'), ]
            })

        url = urlparse(self.user_url)
        if len(url.path) > 10 or len(url.query) > 10:
            raise ValidationError({
                'user_url': [_('This link is too long'), ]
            })

        if any(markup in self.content for markup in ('<a href', '[url')) or \
                self.content.startswith('http://'):
            raise ValidationError({
                'content': [_('Please, use Markdown syntax for links'), ]
            })
            
            from django.db import models
Ejemplo n.º 54
0
    def rf(url, data_or_user=None, user=None, middleware=None, expect=None, **kwargs):
        if type(data_or_user) is User and user is None:
            user = data_or_user
        elif 'data' not in kwargs:
            kwargs['data'] = data_or_user
        if 'format' not in kwargs:
            kwargs['format'] = 'json'

        view, view_args, view_kwargs = resolve(urlparse(url)[2])
        request = getattr(APIRequestFactory(), verb)(url, **kwargs)
        if middleware:
            middleware.process_request(request)
        if user:
            force_authenticate(request, user=user)

        response = view(request, *view_args, **view_kwargs)
        if middleware:
            middleware.process_response(request, response)
        if expect:
            if response.status_code != expect:
                data_copy = response.data.copy()
                try:
                    # Make translated strings printable
                    for key, value in response.data.items():
                        if isinstance(value, list):
                            response.data[key] = []
                            for item in value:
                                response.data[key].append(str(value))
                        else:
                            response.data[key] = str(value)
                except Exception:
                    response.data = data_copy
                print(response.data)
            assert response.status_code == expect
        response.render()
        return response
Ejemplo n.º 55
0
def test_template_base(db, app, idp, caplog, sp_settings):
    response = app.get(reverse('mellon_metadata'))
    response = app.get(reverse('mellon_login'))
    url, body, relay_state = idp.process_authn_request_redirect(
        response['Location'],
        auth_result=False,
        msg='User is not allowed to login')
    response = app.post(reverse('mellon_login'),
                        params={
                            'SAMLResponse': body,
                            'RelayState': relay_state
                        })
    assert 'Theme is ok' in response.text

    response = app.get(reverse('mellon_login'))
    url, body, relay_state = idp.process_authn_request_redirect(
        response['Location'])
    response = app.post(reverse('mellon_login'),
                        params={
                            'SAMLResponse': body,
                            'RelayState': relay_state
                        })
    response = app.get(reverse('mellon_logout'))
    assert urlparse.urlparse(response['Location']).path == '/singleLogout'
Ejemplo n.º 56
0
    def clean(self):
        """Clean the form.

        This method does no additional validation. It only parses the Gerrit
        URL to determine the domain to use for SSH access (since it will be the
        same domain as for HTTP access).

        Returns:
            dict:
            The cleaned form data.
        """
        self.cleaned_data = super(GerritForm, self).clean()

        gerrit_url = self.cleaned_data.get('gerrit_url')

        if gerrit_url:
            gerrit_domain = urlparse(gerrit_url).netloc

            if ':' in gerrit_domain:
                gerrit_domain = gerrit_domain.split(':', 1)[0]

            self.cleaned_data['gerrit_domain'] = gerrit_domain

        return self.cleaned_data
Ejemplo n.º 57
0
    def test_logout(self):
        settings.SAML_CONFIG = conf.create_conf(
            sp_host='sp.example.com',
            idp_hosts=['idp.example.com'],
            metadata_file='remote_metadata_one_idp.xml',
        )
        self.do_login()

        response = self.client.get(reverse('saml2_logout'))
        self.assertEqual(response.status_code, 302)
        location = response['Location']

        url = urlparse(location)
        self.assertEqual(url.hostname, 'idp.example.com')
        self.assertEqual(url.path,
                         '/simplesaml/saml2/idp/SingleLogoutService.php')

        params = parse_qs(url.query)
        self.assertIn('SAMLRequest', params)

        saml_request = params['SAMLRequest'][0]
                                      
        if 'LogoutRequest xmlns' not in decode_base64_and_inflate(saml_request).decode('utf-8'):
            raise Exception('Not a valid LogoutRequest')
Ejemplo n.º 58
0
def site_url(url):
    from askbot.conf import settings
    base_url = urlparse(settings.APP_URL)
    return base_url.scheme + '://' + base_url.netloc + url
Ejemplo n.º 59
0
    def process_view(self, request, callback, callback_args, callback_kwargs):
        if getattr(request, 'csrf_processing_done', False):
            return None

        try:
            cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
        except KeyError:
            csrf_token = None
        else:
            csrf_token = _sanitize_token(cookie_token)
            if csrf_token != cookie_token:
                # Cookie token needed to be replaced;
                # the cookie needs to be reset.
                request.csrf_cookie_needs_reset = True
            # Use same token next time.
            request.META['CSRF_COOKIE'] = csrf_token

        # Wait until request.META["CSRF_COOKIE"] has been manipulated before
        # bailing out, so that get_token still works
        if getattr(callback, 'csrf_exempt', False):
            return None

        # Assume that anything not defined as 'safe' by RFC7231 needs protection
        if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
            if getattr(request, '_dont_enforce_csrf_checks', False):
                # Mechanism to turn off CSRF checks for test suite.
                # It comes after the creation of CSRF cookies, so that
                # everything else continues to work exactly the same
                # (e.g. cookies are sent, etc.), but before any
                # branches that call reject().
                return self._accept(request)

            if request.is_secure():
                # Suppose user visits http://example.com/
                # An active network attacker (man-in-the-middle, MITM) sends a
                # POST form that targets https://example.com/detonate-bomb/ and
                # submits it via JavaScript.
                #
                # The attacker will need to provide a CSRF cookie and token, but
                # that's no problem for a MITM and the session-independent
                # secret we're using. So the MITM can circumvent the CSRF
                # protection. This is true for any HTTP connection, but anyone
                # using HTTPS expects better! For this reason, for
                # https://example.com/ we need additional protection that treats
                # http://example.com/ as completely untrusted. Under HTTPS,
                # Barth et al. found that the Referer header is missing for
                # same-domain requests in only about 0.2% of cases or less, so
                # we can use strict Referer checking.
                referer = force_text(request.META.get('HTTP_REFERER'),
                                     strings_only=True,
                                     errors='replace')
                if referer is not None:
                    referer = urlparse(referer)

                    # Make sure we have a valid URL for Referer.
                    if '' in (referer.scheme, referer.netloc):
                        return self._reject(request, REASON_MALFORMED_REFERER)

                    # Ensure that our Referer is also secure.
                    if referer.scheme != 'https':
                        return self._reject(request, REASON_INSECURE_REFERER)

                    # If there isn't a CSRF_COOKIE_DOMAIN, assume we need an exact
                    # match on host:port. If not, obey the cookie rules.
                    if settings.CSRF_COOKIE_DOMAIN is None:
                        # request.get_host() includes the port.
                        good_referer = request.get_host()
                    else:
                        good_referer = settings.CSRF_COOKIE_DOMAIN
                        server_port = request.get_port()
                        if server_port not in ('443', '80'):
                            good_referer = '%s:%s' % (good_referer,
                                                      server_port)

                    # Here we generate a list of all acceptable HTTP referers,
                    # including the current host since that has been validated
                    # upstream.
                    good_hosts = list(settings.CSRF_TRUSTED_ORIGINS)
                    good_hosts.append(good_referer)

                    if not any(
                            is_same_domain(referer.netloc, host)
                            for host in good_hosts):
                        reason = REASON_BAD_REFERER % referer.geturl()
                        return self._reject(request, reason)

            if csrf_token is None:
                # No CSRF cookie. For POST requests, we insist on a CSRF cookie,
                # and in this way we can avoid all CSRF attacks, including login
                # CSRF.
                return self._reject(request, REASON_NO_CSRF_COOKIE)

            # Check non-cookie token for match.
            request_csrf_token = ""
            if request.method == "POST":
                try:
                    request_csrf_token = request.POST.get(
                        'csrfmiddlewaretoken', '')
                except IOError:
                    # Handle a broken connection before we've completed reading
                    # the POST data. process_view shouldn't raise any
                    # exceptions, so we'll ignore and serve the user a 403
                    # (assuming they're still listening, which they probably
                    # aren't because of the error).
                    pass

            if request_csrf_token == "":
                # Fall back to X-CSRFToken, to make things easier for AJAX,
                # and possible for PUT/DELETE.
                request_csrf_token = request.META.get(
                    settings.CSRF_HEADER_NAME, '')

            request_csrf_token = _sanitize_token(request_csrf_token)
            if not _compare_salted_tokens(request_csrf_token, csrf_token):
                return self._reject(request, REASON_BAD_TOKEN)

        return self._accept(request)
Ejemplo n.º 60
0
def get_pagination_context(
    page,
    pages_to_show=11,
    url=None,
    size=None,
    justify_content=None,
    extra=None,
    parameter_name="page",
):
    """
    Generate Bootstrap pagination context from a page object
    """
    pages_to_show = int(pages_to_show)
    if pages_to_show < 1:
        raise ValueError(
            "Pagination pages_to_show should be a positive integer, you specified {pages}".format(
                pages=pages_to_show
            )
        )
    num_pages = page.paginator.num_pages
    current_page = page.number
    half_page_num = int(floor(pages_to_show / 2))
    if half_page_num < 0:
        half_page_num = 0
    first_page = current_page - half_page_num
    if first_page <= 1:
        first_page = 1
    if first_page > 1:
        pages_back = first_page - half_page_num
        if pages_back < 1:
            pages_back = 1
    else:
        pages_back = None
    last_page = first_page + pages_to_show - 1
    if pages_back is None:
        last_page += 1
    if last_page > num_pages:
        last_page = num_pages
    if last_page < num_pages:
        pages_forward = last_page + half_page_num
        if pages_forward > num_pages:
            pages_forward = num_pages
    else:
        pages_forward = None
        if first_page > 1:
            first_page -= 1
        if pages_back is not None and pages_back > 1:
            pages_back -= 1
        else:
            pages_back = None
    pages_shown = []
    for i in range(first_page, last_page + 1):
        pages_shown.append(i)

    # parse the url
    parts = urlparse(url or "")
    params = parse_qs(parts.query)

    # append extra querystring parameters to the url.
    if extra:
        params.update(parse_qs(extra))

    # build url again.
    url = urlunparse(
        [
            parts.scheme,
            parts.netloc,
            parts.path,
            parts.params,
            urlencode(params, doseq=True),
            parts.fragment,
        ]
    )

    # Set CSS classes, see http://getbootstrap.com/components/#pagination
    pagination_css_classes = ["pagination"]
    if size == "small":
        pagination_css_classes.append("pagination-sm")
    elif size == "large":
        pagination_css_classes.append("pagination-lg")

    if justify_content == "start":
        pagination_css_classes.append("justify-content-start")
    elif justify_content == "center":
        pagination_css_classes.append("justify-content-center")
    elif justify_content == "end":
        pagination_css_classes.append("justify-content-end")

    return {
        "bootstrap_pagination_url": url,
        "num_pages": num_pages,
        "current_page": current_page,
        "first_page": first_page,
        "last_page": last_page,
        "pages_shown": pages_shown,
        "pages_back": pages_back,
        "pages_forward": pages_forward,
        "pagination_css_classes": " ".join(pagination_css_classes),
        "parameter_name": parameter_name,
    }