Example #1
0
def media_facet(request, result_path, search_set):
    nvps = request
    if 'mt' in nvps:
        media_type = nvps.get('mt')
        query = urlquote(media_type)
        url = ('%s&q=(type:%s+AND+%s)'
               '&rows=0'
               '&facet=true'
               '&facet.field=itemType'
               '&facet.zeros=false'
               '&facet.limit=-1'
               % (solr, query, search_set))
        solr_response = get_solr(url, 'json')
        if isinstance(solr_response, dict):
            facets = solr_response['facet_counts']['facet_fields']['itemType']
            labels = facets[::2]
            counts = facets[1::2]
            html = ''
            for l, c in zip(labels, counts):
                item_type = urlquote(l)
                html += ('<li>'
                         '<input type="checkbox" '
                         'id="%s" '
                         'name="itype" '
                         'value="%s" /> '
                         '<a href="/%s?itype=%s&amp;mt=%s">'
                         '<label for="%s">%s</label>'
                         '</a>'
                         ' (%s)</li>'
                         % (''.join(l.split(' ')), l, result_path, item_type, media_type, ''.join(l.split(' ')), l, c))
            return html
    else:
        return ''
Example #2
0
    def test_get(self):
        """
        This tests that the view responds correctly for a user with edit permissions on this image
        """
        # Get
        response = self.client.get(reverse('wagtailimages_generate_url', args=(self.image.id, 'fill-800x600')))

        # Check response
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/json')

        # Check JSON
        content_json = json.loads(response.content.decode())

        self.assertEqual(set(content_json.keys()), set(['url', 'local_url']))

        expected_url = 'http://localhost/images/%(signature)s/%(image_id)d/fill-800x600/' % {
            'signature': urlquote(generate_signature(self.image.id, 'fill-800x600').decode()),
            'image_id': self.image.id,
        }
        self.assertEqual(content_json['url'], expected_url)

        expected_local_url = '/images/%(signature)s/%(image_id)d/fill-800x600/' % {
            'signature': urlquote(generate_signature(self.image.id, 'fill-800x600').decode()),
            'image_id': self.image.id,
        }
        self.assertEqual(content_json['local_url'], expected_local_url)
Example #3
0
def router_info(request):
    base_url = get_base_url()
    full_path = request.path
    path = get_wq_path(request)
    if not path:
        return {}
    if request.GET:
        path += "?" + request.GET.urlencode()

    info = {
        'base_url': base_url,
        'path': path,
        'path_enc': urlquote(path),
        'params': request.GET,
        'full_path': full_path,
        'full_path_enc': urlquote(full_path),
        'prev_path': '',  # Referer?
    }

    return {
        'rt': base_url,
        'svc': base_url,
        'router_info': info,
        'pages_info': info,  # FIXME: Remove in 2.0
    }
Example #4
0
def has_url(text, trim_url_limit=None, nofollow=False, autoescape=False):
    middle = "nope"
    trim_url = (
        lambda x, limit=trim_url_limit: limit is not None
        and (len(x) > limit and ("%s..." % x[: max(0, limit - 3)]))
        or x
    )
    safe_input = isinstance(text, SafeData)
    words = word_split_re.split(force_unicode(text))
    nofollow_attr = nofollow and ' rel="nofollow"' or ""
    for i, word in enumerate(words):
        match = None
        if "." in word or "@" in word or ":" in word:
            match = punctuation_re.match(word)
        if match:
            lead, middle, trail = match.groups()
            url = None
            if middle.startswith("http://") or middle.startswith("https://"):
                url = urlquote(middle, safe="/&=:;#?+*")
            elif middle.startswith("www.") or (
                "@" not in middle
                and middle
                and middle[0] in string.ascii_letters + string.digits
                and (middle.endswith(".org") or middle.endswith(".net") or middle.endswith(".com"))
            ):
                url = urlquote("http://%s" % middle, safe="/&=:;#?+*")
            elif "@" in middle and not ":" in middle and simple_email_re.match(middle):
                url = "mailto:%s" % middle
                nofollow_attr = ""
            if url:
                return True
    return False
def authenticate(request):
    """ Code derived from https://github.com/ThatGreenSpace/django-freshdesk
    Copyright (c) 2014 That Green Space Pte Ltd and individual contributors.
    All rights reserved.
    """
    if not hasattr(settings, 'FRESHDESK_URL'):
        raise ImproperlyConfigured("Set the FRESHDESK_URL settings variable")
    if not hasattr(settings, 'FRESHDESK_SECRET_KEY'):
        raise ImproperlyConfigured("Set the FRESHDESK_SECRET_KEY settings variable")

    if not request.user:
        raise Http404()

    first_name = request.user.first_name
    last_name = request.user.last_name
    username = request.user.get_username()
    full_name = '{0} {1}'.format(first_name, last_name) if first_name or last_name else username

    utctime = int(time.time())
    data = '{0}{1}{2}'.format(
        full_name, request.user.email, utctime)
    generated_hash = hmac.new(
        settings.FRESHDESK_SECRET_KEY.encode(), data.encode('utf-8'), hashlib.md5).hexdigest()
    url = '{0}/login/sso?name={1}&email={2}&timestamp={3}&hash={4}'.format(
        settings.FRESHDESK_URL.strip('/'),
        urlquote(full_name), urlquote(request.user.email), utctime, generated_hash)

    # If configured, we have an option to divert the user based on his email to
    # an url insetad of the freshdesk.
    if hasattr(settings, 'FRESHDESK_DIVERT_CLASS'):
        diverter = (import_class(settings.FRESHDESK_DIVERT_CLASS))()
        if diverter.should_divert(request.user):
            return HttpResponseRedirect(diverter.divert_url(request.user, request))

    return HttpResponseRedirect(iri_to_uri(url))
Example #6
0
        def _wrapped_view(request, *args, **kwargs):
            obj = None

            try:
                rule = RulePermission.objects.get(codename=perm)
            except RulePermission.DoesNotExist:
                raise NonexistentPermission("Permission %s does not exist" % perm)

            # Only look in kwargs, if the views are entry points through urls Django passes parameters as kwargs
            # We could look in args using  inspect.getcallargs in Python 2.7 or a custom function that
            # imitates it, but if the view is internal, I think it's better to force the user to pass
            # parameters as kwargs
            if rule.view_param_pk not in kwargs:
                raise RulesError("The view does not have a parameter called %s in kwargs" % rule.view_param_pk)

            model_class = rule.content_type.model_class()
            obj = get_object_or_404(model_class, pk=kwargs[rule.view_param_pk])

            if not request.user.has_perm(perm, obj):
                if return_403:
                    raise PermissionDenied
                else:
                    if redirect_url:
                        try:
                            path = urlquote(request.get_full_path())
                            redirect_url_reversed = reverse(redirect_url)
                            tup = redirect_url_reversed, redirect_field_name, path
                        except NoReverseMatch:
                            tup = redirect_url, redirect_field_name, path
                    else:
                        path = urlquote(request.get_full_path())
                        tup = login_url, redirect_field_name, path

                    return HttpResponseRedirect("%s?%s=%s" % tup)
            return view_func(request, *args, **kwargs)
def show_bookmarks(context, title, object_or_url, description=""):
    """ Displays the bookmarks
        TODO: Add in the javascript cleanup part
    """

    if hasattr(object_or_url, 'get_absolute_url'):
        url = getattr(object_or_url, 'get_absolute_url')()

    url = unicode(object_or_url)
    
    if not url.startswith('http'):
        url = context['request'].build_absolute_uri(url)

    # TODO: Bookmark should have a .active manager:
    bookmarks = Bookmark.objects.filter(status=2).values()

    for bookmark in bookmarks:
        bookmark['description'] = description
        bookmark['link'] = bookmark['url'] % {'title': urlquote(title),
                                        'url': urlquote(url),
                                        'description': urlquote(description)
                                       }


    return {'bookmarks':bookmarks, 'MEDIA_URL': context['MEDIA_URL']}
Example #8
0
    def to_li(self):
        href = PivotNode.base_url
        parents = self.get_parents()
        url_parts = []

        if parents:
            url_parts.append(u'&in=on')

        for parent in parents:
            url_parts += u''.join([u'&pattr=', urlquote(parent.field), u'&pq=', urlquote(parent.value)])

        item_li = [u'<li class="pivot__element">']
        href += u''.join([u'?attr=', urlquote(self.field), u'&q=', urlquote(self.value)])

        if url_parts:
            href += u''.join(url_parts)
        item_li.append(
            u'<a href="%s" class="pivot__title" id="pt_%s">%s</a>' % (href, self.field, self.value)
        )
        item_li.append(u'<div class="pivot__count">Документы: %s</div>' % (self.count,))
        if self.views is not None:
            item_li.append(u'<div class="pivot__views">Просмотры: %s</div>' % (self.views,))

        if self.pivot:
            item_li.append(self.children_to_html())
        item_li.append(u'</li>')

        return u''.join(item_li)
Example #9
0
def urlize_target(text, target='', trim_url_limit=None, nofollow=False, autoescape=False):
    """
    Converts any URLs in text into clickable links.

    Works on http://, https://, www. links and links ending in .org, .net or
    .com. Links can have trailing punctuation (periods, commas, close-parens)
    and leading punctuation (opening parens) and it'll still do the right
    thing.

    If trim_url_limit is not None, the URLs in link text longer than this limit
    will truncated to trim_url_limit-3 characters and appended with an elipsis.

    If nofollow is True, the URLs in link text will get a rel="nofollow"
    attribute.

    If autoescape is True, the link text and URLs will get autoescaped.
    """
    
    trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x
    safe_input = isinstance(text, SafeData)
    words = word_split_re.split(force_unicode(text))
    nofollow_attr = nofollow and ' rel="nofollow"' or ''
    target_attr = ''
    if target != '':
    	target_attr=' target="' + target +'"'
    for i, word in enumerate(words):
        match = None
        if '.' in word or '@' in word or ':' in word:
            match = punctuation_re.match(word)
        if match:
            lead, middle, trail = match.groups()
            # Make URL we want to point to.
            url = None
            if middle.startswith('http://') or middle.startswith('https://'):
                url = urlquote(middle, safe='/&=:;#?+*')
            elif middle.startswith('www.') or ('@' not in middle and \
                    middle and middle[0] in string.ascii_letters + string.digits and \
                    (middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))):
                url = urlquote('http://%s' % middle, safe='/&=:;#?+*')
            elif '@' in middle and not ':' in middle and simple_email_re.match(middle):
                url = 'mailto:%s' % middle
                nofollow_attr = ''
            # Make link.
            if url:
                trimmed = trim_url(middle)
                if autoescape and not safe_input:
                    lead, trail = escape(lead), escape(trail)
                    url, trimmed = escape(url), escape(trimmed)
                middle = '<a href="%s"%s%s>%s</a>' % (url, target_attr, nofollow_attr, trimmed)
                words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
            else:
                if safe_input:
                    words[i] = mark_safe(word)
                elif autoescape:
                    words[i] = escape(word)
        elif safe_input:
            words[i] = mark_safe(word)
        elif autoescape:
            words[i] = escape(word)
    return u''.join(words)
Example #10
0
def user(request, username):
    user = get_object_or_404(User, username=username, is_active=True)
    via = request.GET.get('f')
    delta = datetime.datetime.now() - user.date_joined
    data = {'username': username,
            'profile': user.profile,
            'logged_in': request.user.is_authenticated(),
            'date_joined_delta': _total_seconds(delta),
            'is_user_page': True,
            'countries': json.dumps(countries[request.locale]),
            'sparked_countries': json.dumps(user.profile.sparked_countries),
            'twitter_url': urlquote(user.profile.twitter_sharing_url),
            'twitter_msg': urlquote(unicode(TWITTER_SHARE_MSG)),
            'facebook_url': user.profile.facebook_sharing_url,
            'facebook_redirect': absolute_url(django_reverse('desktop.close_popup')),
            'facebook_title': urlquote(unicode(FACEBOOK_SPARK_TITLE)),
            'facebook_spark_msg': urlquote(unicode(FACEBOOK_SPARK_MSG)),
            'stats': get_global_stats(),
            'FB_APP_ID': settings.FB_APP_ID}
    
    if not request.user.is_authenticated():
        data.update({'login_next_url': request.path})

    response = jingo.render(request, 'desktop/user.html', data)
    return set_sharing_cookies(response, username, via)
Example #11
0
 def last_fm(self, obj):
     link = \
         '<a href="http://www.last.fm/music/{}/{}">Last.fm</a>'.format(
             urlquote(obj.artist.name.replace(' ', '+')),
             urlquote(obj.title.replace(' ', '+'))
         )
     return link
Example #12
0
def single_signon_check(request):
    """
    This view applies only on the central site.
    Used when the user is loggin on a local site and sent to the central site to
    check if they are already authed. If they are, the GET params 'user_id' and
    'hmac' will be filled with the user PK and message to authenticate. The user
    is then sent back to the URL in the 'next' GET param.
    """
    if not request.site.is_central():
        raise PermissionDenied

    if 'next' not in request.GET:
        raise PermissionDenied

    if not request.user.is_authenticated():
        # The user is not authenticated; redirect to the return URL as-is
        # without 'user_id' or 'hmac' params.
        return redirect(request.GET['next'])
    else:
        hmac_b64 = sso_hmac(request.user)
        return redirect('%s&user_id=%s&hmac=%s' % (
            request.GET['next'],
            urlquote(str(request.user.id)),
            urlquote(hmac_b64),
        ))
Example #13
0
    def test_logout_shib_user(self):
        
        # If shib user logs out.
        # Redirect to shib logout.

        environ = {settings.META_USERNAME: '******'}

        client = Client()

        request_url = settings.LOGIN_URL
        client.get(request_url, ** environ)

        self.assert_(SESSION_KEY in client.session)

        request_url = '/admin/logout/'
        response = client.get(request_url, ** environ)
        self.failUnlessEqual(response.status_code, 302)
        self.failUnlessEqual(response['Location'],
                             '%s%s%s' % \
                             (settings.SHIB_LOGOUT_URL,
                             urlquote('http://testserver'),
                             urlquote(request_url)))
                             
        self.assert_(SESSION_KEY not in client.session)

        request_url = '/admin/logout/'
        response = client.get(request_url)

        self.failUnlessEqual(response.status_code, 200)
        self.failUnlessEqual(response.template[0].name,
                             'registration/logged_out.html')
        self.assert_(SESSION_KEY not in client.session)
Example #14
0
def render_search_result(request, catalog, zresult=''):
    cookies = {}
    if zresult == '':
        url = catalog.url
        new_get = []
        for key in request.GET:
            if key == 'zstate': continue
            new_get.append(urlquote(key) + '=' + urlquote(request.GET[key]))

        new_get = '&'.join(new_get)

        if request.GET['zstate'] == 'action':
            url = url + '?' + new_get
        else:
            url = url + '?' + request.GET['zstate'].replace(' ', '+')

        (zresult, cookies) = zworker.request(url, cookies=request.COOKIES)
    try:
        zresults_body_element = zworker.get_body_element(zresult)
        zresults_body_element = zworker.change_form_action(zresults_body_element)

        zresults_body_element = zworker.change_links_href(zresults_body_element)
    except Exception:
        return HttpResponse(u'Некорректный url')
    result = zworker.make_html_body_content(zresults_body_element)

    response = render(request, 'zgate/search_results.html', {
        'catalog_title': catalog.title,
        'search_results': result
    })

    return  set_cookies_to_response(cookies, response)
Example #15
0
 def create_share(self, obj):
     share = Utils.create_object()
     share.title = obj.logo_title
     share.description = obj.short_description
     share.url = Utils.get_current_url(self.request)
     encoded_url = urlquote_plus(share.url)
     title = obj.logo_title
     encoded_title = urlquote_plus(title)
     encoded_detail = urlquote_plus(obj.short_description)
     url_detail = obj.short_description + '\n\n' + share.url
     encoded_url_detail = urlquote_plus(url_detail)
     share.image_url = Utils.get_url(
         self.request,
         PosterService.poster_image_url(obj)
     )
     encoded_image_url = urlquote_plus(share.image_url)
     # email shouldn't encode space
     share.email = 'subject=%s&body=%s' % (
         urlquote(title, ''), urlquote(url_detail, '')
     )
     #
     share.fb = 'u=%s' % encoded_url
     #
     share.twitter = 'text=%s' % encoded_url_detail
     #
     share.google_plus = 'url=%s' % encoded_url
     #
     share.linkedin = 'url=%s&title=%s&summary=%s' % (
         encoded_url, encoded_title, encoded_detail
     )
     #
     share.pinterest = 'url=%s&media=%s&description=%s' % (
         encoded_url, encoded_image_url, encoded_detail
     )
     return share
Example #16
0
def tag_url(value):
    if not getattr(settings, 'TAGS_URL', ''):
        return ''
    try:
        return settings.TAGS_URL % urlquote(value)
    except TypeError:
        return settings.TAGS_URL + urlquote(value)
Example #17
0
def show_bookmarks(context, title, object_or_url, description=""):
    """ Displays the bookmarks
        TODO: Add in the javascript cleanup part
    """

    if hasattr(object_or_url, "get_absolute_url"):
        url = getattr(object_or_url, "get_absolute_url")()

    url = unicode(object_or_url)

    if not url.startswith("http"):
        url = context["request"].build_absolute_uri(url)

    # TODO: Bookmark should have a .active manager:
    bookmarks = Bookmark.objects.filter(status=2).values()

    for bookmark in bookmarks:
        bookmark["description"] = description
        bookmark["link"] = bookmark["url"] % {
            "title": urlquote(title),
            "url": urlquote(url),
            "description": urlquote(description),
        }

    return {"bookmarks": bookmarks, "MEDIA_URL": context["MEDIA_URL"]}
Example #18
0
    def test_security_check(self, password="******"):
        login_url = reverse("django.contrib.auth.views.login")

        # Those URLs should not pass the security check
        for bad_url in ("http://example.com", "https://example.com", "ftp://exampel.com", "//example.com"):

            nasty_url = "%(url)s?%(next)s=%(bad_url)s" % {
                "url": login_url,
                "next": REDIRECT_FIELD_NAME,
                "bad_url": urlquote(bad_url),
            }
            response = self.client.post(nasty_url, {"username": "******", "password": password})
            self.assertEqual(response.status_code, 302)
            self.assertFalse(bad_url in response["Location"], "%s should be blocked" % bad_url)

        # These URLs *should* still pass the security check
        for good_url in (
            "/view/?param=http://example.com",
            "/view/?param=https://example.com",
            "/view?param=ftp://exampel.com",
            "view/?param=//example.com",
            "https:///",
            "//testserver/",
            "/url%20with%20spaces/",
        ):  # see ticket #12534
            safe_url = "%(url)s?%(next)s=%(good_url)s" % {
                "url": login_url,
                "next": REDIRECT_FIELD_NAME,
                "good_url": urlquote(good_url),
            }
            response = self.client.post(safe_url, {"username": "******", "password": password})
            self.assertEqual(response.status_code, 302)
            self.assertTrue(good_url in response["Location"], "%s should be allowed" % good_url)
Example #19
0
def rename_tag(request):
    from django.utils.http import urlquote
    
    key = request.POST['key']
    value = request.POST.get('value', None)
    
    if value:
        tags = Tag.objects.filter(key=key, value=value)
    else:
        tags = Tag.objects.filter(key=key)

    for tag in tags:
        if value and 'new_value' in request.POST:
            tag.value = request.POST['new_value']
        if 'new_key' in request.POST:
            tag.key = request.POST['new_key']
        tag.save()
    
    if 'new_key' in request.POST:
        if 'new_value' in request.POST:    
            return redirect_to(request, reverse('openresources_tag', kwargs={'key':urlquote(request.POST['new_key']), 'value': urlquote(request.POST['new_value'])}))
        return redirect_to(request, reverse('openresources_tag_key', kwargs={'key':urlquote(request.POST['new_key'])}))

    if value:
        return redirect_to(request, reverse('openresources_tag', kwargs={'key':urlquote(key), 'value': urlquote(value)}))
    
    return redirect_to(request, reverse('openresources_tag_key', kwargs={'key':urlquote(key)}))
Example #20
0
 def get_project_category_totals(self):
     result_dict = {}
     cat_dict = {}
     all_tasks = self.task_set.all()
     for task in all_tasks:
         try:
             cat_dict[task.category.id]
         except KeyError:
             cat_dict[task.category.id] = task.category
     for cat in cat_dict:
         cat_exp_total = self.get_category_expense(cat_dict[cat])
         cat_price_total = self.get_category_price(cat_dict[cat])
         task_set_objects = all_tasks.filter(category_id=cat_dict[cat].id)
         task_set = task_set_objects.values()
         task_set_json = {}
         for task in task_set:
             task['title_url'] = urlquote(task['title'])
             task['update_url'] = task_set_objects.get(id=task['id']).get_update_url()
             task_set_json[task['id']] = task
         result_dict[cat_dict[cat].id] = {
             'slug': cat_dict[cat].slug,
             'title': cat_dict[cat].title,
             'title_url': urlquote(cat_dict[cat].title),
             'order': cat_dict[cat].order,
             'expense': cat_exp_total,
             'price': cat_price_total,
             'total': sum([cat_exp_total, cat_price_total]),
             'task_set': task_set_json,
         }
     return result_dict
Example #21
0
    def format_file_uploaded_msg(self):
        """
        
        Arguments:
        - `self`:
        """
        d = json.loads(self.detail)
        filename = d['file_name']
        repo_id = d['repo_id']
        if d['uploaded_to'] == '/':
            # current upload path is '/'
            file_path = '/' + filename
            link = reverse('view_common_lib_dir', args=[repo_id, ''])
            name = seafile_api.get_repo(repo_id).name
        else:
            uploaded_to = d['uploaded_to'].rstrip('/')
            file_path = uploaded_to + '/' + filename
            link = reverse('view_common_lib_dir', args=[repo_id, urlquote(uploaded_to.lstrip('/'))])
            name = os.path.basename(uploaded_to)

        file_link = reverse('view_lib_file', args=[repo_id, urlquote(file_path)])

        msg = _(u"A file named <a href='%(file_link)s'>%(file_name)s</a> is uploaded to <a href='%(link)s'>%(name)s</a>") % {
            'file_link': file_link,
            'file_name': escape(filename),
            'link': link,
            'name': escape(name),
            }
        return msg
Example #22
0
def pre_process_story(entry):
    date_published = entry.get('published', entry.get('updated'))
    if not date_published:
        date_published = str(datetime.datetime.now())
        entry['published_now'] = True
    if not isinstance(date_published, datetime.datetime):
        date_published = dateutil_parse(date_published)
    # Change the date to UTC and remove timezone info since 
    # MySQL doesn't support it.
    timezone_diff = datetime.datetime.utcnow() - datetime.datetime.now()
    date_published_offset = date_published.utcoffset()
    if date_published_offset:
        date_published = (date_published - date_published_offset
                          - timezone_diff).replace(tzinfo=None)
    else:
        date_published = date_published.replace(tzinfo=None)

    entry['published'] = date_published
    
    entry_link = entry.get('link', '')
    protocol_index = entry_link.find("://")
    if protocol_index != -1:
        entry['link'] = (entry_link[:protocol_index+3]
                        + urlquote(entry_link[protocol_index+3:]))
    else:
        entry['link'] = urlquote(entry_link)
    return entry
Example #23
0
def manage_badge_view(request, output = 'png', user_id = 0):
    response = HttpResponseForbidden()

    user = None
    try:
        user = User.objects.get(id=int(user_id))
    except:
        user = None

    if user:
        filepath = content_type = content_disposition = None
        if output == 'png':
            filepath = BadgeGenerator.get_path_png(user_id)
            content_type = 'image/png'
            content_disposition = 'inline; filename=badge-%s_%d.png' % (urlquote(user.username), user.id)
        elif output == 'bigpng':
            filepath = BadgeGenerator.get_path_big_png(user_id)
            content_type = 'image/png'
            content_disposition = 'inline; filename=badgebig-%s_%d.png' % (urlquote(user.username), user.id)
        elif output == 'pdf':
            filepath = BadgeGenerator.get_path_pdf(user_id)
            content_type = 'application/pdf'
            content_disposition = 'attachement; filename=badge-%s_%d.pdf' % (urlquote(user.username), user.id)

        if filepath and os.path.exists(filepath):
            wrapper = FileWrapper(file(filepath))
            response = HttpResponse(wrapper, content_type=content_type)
            response['Content-Disposition'] = content_disposition
            response['Content-Length'] = os.path.getsize(filepath)

    return response
Example #24
0
    def dispatch(self, request, *args, **kwargs):
        self._check_permissions_attr()

        perms_all = self.permissions.get("all") or None
        perms_any = self.permissions.get("any") or None

        self._check_permissions_keys_set(perms_all, perms_any)
        self._check_perms_keys("all", perms_all)
        self._check_perms_keys("any", perms_any)

        # If perms_all, check that user has all permissions in the list/tuple
        if perms_all:
            if not request.user.has_perms(perms_all):
                if self.raise_exception:
                    return HttpResponseForbidden()
                path = urlquote(request.get_full_path())
                tup = self.login_url, self.redirect_field_name, path
                return HttpResponseRedirect("%s?%s=%s" % tup)

        # If perms_any, check that user has at least one in the list/tuple
        if perms_any:
            has_one_perm = False
            for perm in perms_any:
                if request.user.has_perm(perm):
                    has_one_perm = True
                    break

            if not has_one_perm:
                if self.raise_exception:
                    return HttpResponseForbidden()
                path = urlquote(request.get_full_path())
                tup = self.login_url, self.redirect_field_name, path
                return HttpResponseRedirect("%s?%s=%s" % tup)

        return super(MultiplePermissionsRequiredMixin, self).dispatch(request, *args, **kwargs)
Example #25
0
def sharebadge(request):
    badge_id = request.GET.get('id')
    try:
        # Verify that this badge exists
        badge = Challenge.objects.get(pk=badge_id)
        
        # Verify also that this user has earned this badge
        profile = request.user.profile
        has_badge = profile.has_badge(badge_id)
        
        if has_badge:
            data = {'badge_name': get_badge_name(badge.id),
                    'twitter_url': urlquote(profile.twitter_sharing_url),
                    'twitter_badge_msg': TWITTER_BADGE_MSG,
                    'facebook_url': profile.facebook_sharing_url,
                    'facebook_redirect': absolute_url(django_reverse('mobile.home')),
                    'facebook_title': urlquote(unicode(FACEBOOK_SPARK_TITLE)),
                    'facebook_badge_msg': FACEBOOK_BADGE_MSG,
                    'facebook_img': absolute_url(settings.MEDIA_URL+'img/badges/fb/'+badge.id.replace('_','-')+'.png'),
                    'facebook_desc': urlquote(badge.badge_description),
                    'FB_APP_ID': settings.FB_APP_ID}
            return jingo.render(request, 'mobile/sharebadge.html', data)
    except Challenge.DoesNotExist:
        # Ignore invalid badges
        pass
    
    # Return to earned badges page if the querystring contains an invalid badge id
    # or if the user tried to share a badge he/she has not earned yet.
    return HttpResponseRedirect(reverse('mobile.badges'))
def pie_chart(items, width=440, height=190):
    return '//chart.googleapis.com/chart?cht=p3&chd=t:{0}&chs={1}x{2}&chl={3}'.format(
        urlquote(','.join([str(item[1]) for item in items])),
        width,
        height,
        urlquote('|'.join([str(item[0]) for item in items])),
    )
Example #27
0
    def real_work(request_info, user_id, game_id):
        try:
            user = UserProfile.objects.get(pk=user_id)
            fb_profile = user.facebook
            if not fb_profile:
                return

            game = Game.objects.get(pk=game_id, p1__user__exact=user)
            if game.state != 0:
                return

            # The data received is untrusted, so we must quote it to avoid
            # allowng an attaker to forge Facebook requests from us.
            request_id = urlquote(request_info['request'], '')
            targets = [urlquote(t, '') for t in request_info['to']]
            cached = FacebookRequest(id=request_id, game=game, targets=targets)

            # Validate received information
            fb_request = fb_ograph_call(partial(get_fb_request, request_id))
            if fb_profile.uid != fb_request['from']['id'] or fb_request['data'] != game_id or game.p1.user != user:
                # Request is invalid, delete it from Facebook.
                start_cancel_request(cached)
            else:
                # Request passes validation test, save it.
                cached.save()
        except (ObjectDoesNotExist, KeyError):
            pass
def show_bookmarks_related(context, title, url, object, description=""):
    """
    Displays the bookmarks with counter.
    """
    
    if not isinstance(object, models.Model):
        raise TypeError, "object must be a valid Model"

    if not url.startswith('http'):
        url = context['request'].build_absolute_uri(url)
    
    bookmarks = Bookmark.objects.get_active().values()
    content_type = ContentType.objects.get_for_model(object)
    bookmarks_related = dict((related['bookmark_id'], related)\
                             for related in BookmarkRelated.objects.filter(content_type=content_type,
                                                                           object_id=object.pk)
                                                                   .values())
    
    for bookmark in bookmarks:
        bookmark.update({
            'url': urlquote(bookmark['url'] % {'title': urlquote(title),
                                      'url': urlquote(url),
                                      'description': urlquote(description)}),
            'content_type': "%s.%s" % (content_type.app_label, content_type.model),
            'object_pk': object.pk,
            'visits': bookmarks_related[bookmark['id']]['visits'] if bookmark['id'] in bookmarks_related else DEFAULT_VISITS
        })
    
    return {'bookmarks': bookmarks, 'MEDIA_URL': context['MEDIA_URL']}
Example #29
0
    def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
        if args and kwargs:
            raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
        text_args = [force_text(v) for v in args]
        text_kwargs = dict((k, force_text(v)) for (k, v) in kwargs.items())

        if not self._populated:
            self._populate()

        try:
            if lookup_view in self._callback_strs:
                lookup_view = get_callable(lookup_view, True)
        except (ImportError, AttributeError) as e:
            raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e))
        possibilities = self.reverse_dict.getlist(lookup_view)

        prefix_norm, prefix_args = normalize(urlquote(_prefix))[0]
        for possibility, pattern, defaults in possibilities:
            for result, params in possibility:
                if args:
                    if len(args) != len(params) + len(prefix_args):
                        continue
                    candidate_subs = dict(zip(prefix_args + params, text_args))
                else:
                    if set(kwargs.keys()) | set(defaults.keys()) != set(params) | set(defaults.keys()) | set(
                        prefix_args
                    ):
                        continue
                    matches = True
                    for k, v in defaults.items():
                        if kwargs.get(k, v) != v:
                            matches = False
                            break
                    if not matches:
                        continue
                    candidate_subs = text_kwargs
                # WSGI provides decoded URLs, without %xx escapes, and the URL
                # resolver operates on such URLs. First substitute arguments
                # without quoting to build a decoded URL and look for a match.
                # Then, if we have a match, redo the substitution with quoted
                # arguments in order to return a properly encoded URL.
                candidate_pat = prefix_norm.replace("%", "%%") + result
                if re.search("^%s%s" % (prefix_norm, pattern), candidate_pat % candidate_subs, re.UNICODE):
                    candidate_subs = dict((k, urlquote(v)) for (k, v) in candidate_subs.items())
                    return candidate_pat % candidate_subs
        # lookup_view can be URL label, or dotted path, or callable, Any of
        # these can be passed in at the top, but callables are not friendly in
        # error messages.
        m = getattr(lookup_view, "__module__", None)
        n = getattr(lookup_view, "__name__", None)
        if m is not None and n is not None:
            lookup_view_s = "%s.%s" % (m, n)
        else:
            lookup_view_s = lookup_view

        patterns = [pattern for (possibility, pattern, defaults) in possibilities]
        raise NoReverseMatch(
            "Reverse for '%s' with arguments '%s' and keyword "
            "arguments '%s' not found. %d pattern(s) tried: %s" % (lookup_view_s, args, kwargs, len(patterns), patterns)
        )
Example #30
0
 def parse(self):
     gd = self.match.groupdict()
     gd.update({'css': ''})
     if gd['arg1']:
         gd[gd['arg1']] = gd['val1']
     if gd['arg2']:
         gd[gd['arg2']] = gd['val2']
     if gd['href']:
         href = self.variables.resolve(gd['href'])
         inner = self.parse_inner()
     else:
         inner = ''
         for node in self.nodes:
             if node.is_text_node or isinstance(node, AutoDetectURL):
                 inner += node.raw_content
             else:
                 self.soft_raise("Url tag cannot have nested tags without "
                                 "an argument.")
         href = self.variables.resolve(inner)
         inner = href
     if gd['css']:
         css = ' class="%s"' % gd['css'].replace(',', ' ')
     else:
         css = ''
     raw_href = self.variables.resolve(href)
     if raw_href.startswith('http://'):
         href = raw_href[:7] + urlquote(raw_href[7:])
     else:
         href = urlquote(raw_href)
     css = self.variables.resolve(css)
     return u'<a href="%s"%s target="_blank">%s</a>' % (href, css, inner)
Example #31
0
def get_pool_link(member):
    return reverse("horizon:project:loadbalancers:pooldetails",
                   args=(http.urlquote(member.pool_id), ))
Example #32
0
def bddc_upload_hwz(request):
    excel = request.FILES.get('excel')
    bd_type = request.POST.get('bd_type')
    # 获取文件类型
    file_type = excel.name.rsplit('.')[-1]
    file_type = file_type.lower()

    # 获取当前时间的时间戳
    timestr = str(time.time()).replace('.', '')
    file_name = '{0}.{1}'.format(timestr, file_type)
    # 获取程序需要写入的文件路径
    path = os.path.join(settings.BASE_DIR + settings.MEDIA_URL, file_name)
    # 根据路径打开指定的文件(以二进制读写方式打开)
    f = open(path, 'wb+')
    # chunks将对应的文件数据转换成若干片段, 分段写入, 可以有效提高文件的写入速度, 适用于2.5M以上的文件
    for chunk in excel.chunks():
        f.write(chunk)
    f.close()

    # 创建比对结果导出文档
    result_path = os.path.join(settings.BASE_DIR + settings.MEDIA_URL, 'bddc/',
                               '{0}.xls'.format(timestr))

    bddc_result_xls = xlsxwriter.Workbook(result_path)  # 新建excel表
    same_sheet = bddc_result_xls.add_worksheet('镇海库中有对象导出')
    different_sheet = bddc_result_xls.add_worksheet('库中无')

    # 写入第一行标题
    same_sheet.write_row(0, 0, [
        '手机号', '姓名', '身份证号', '户籍地址', '现住地址', '所属街道', '是否武汉', '是否湖北', '市内非镇海',
        '省内非宁波', '省外', '何省返回', '何市返回', '返回年', '返回月', '返回日', '当前状态', '当前状态备注',
        '拨打情况', '自述情况', '白名单', '数据来源', '入库时间', '管控人', '管控人电话', '备用1', '备用2',
        '备用3'
    ])

    same_sheet_row_num = 1
    different_sheet_row_num = 0

    # 开始导入excel模板
    book = xlrd.open_workbook(path)
    sheet1 = book.sheets()[0]
    row_num = sheet1.nrows

    for n in range(0, row_num):

        cell_0_value = sheet1.cell_value(n, 0)
        if sheet1.cell(n, 0).ctype == 2:
            cell_0_value = str(int(cell_0_value))
        cell_0_value = cell_0_value.strip()

        cell_1_value = sheet1.cell_value(n, 1)
        if sheet1.cell(n, 1).ctype == 2:
            cell_1_value = str(int(cell_1_value))
        cell_1_value = cell_1_value.strip()
        kwargs = {}  # 动态查询的字段

        if bd_type == '1' and cell_0_value != '':  # 手机号
            kwargs['phone_no'] = cell_0_value
        elif bd_type == '2' and cell_0_value != '':  # 身份证号
            kwargs['sfzh'] = cell_0_value
        elif bd_type == '3' and cell_1_value != '':  # 手机第一列,姓名第二列
            kwargs['phone_no'] = cell_0_value
            kwargs['name'] = cell_1_value
        elif bd_type == '4':
            pass
        # 执行过滤
        queryset_tmp = yqdx_hwz.objects.filter(**kwargs)
        if kwargs and queryset_tmp.exists():
            queryset = queryset_tmp.first()
            query_set_list = [
                queryset.phone_no, queryset.name, queryset.sfzh, queryset.hjdz,
                queryset.xzdz, queryset.ssjd, queryset.is_wuhan,
                queryset.is_hubei, queryset.is_not_zhenhai,
                queryset.is_not_ningbo, queryset.is_not_zhejiang,
                queryset.back_provinces, queryset.back_city,
                queryset.back_year, queryset.back_month, queryset.back_day,
                queryset.status, queryset.status_remarks, queryset.call_detail,
                queryset.self_tell, queryset.white_list_flag.type_name,
                queryset.from_source,
                queryset.timestamp.strftime('%Y-%m-%d %H:%M'), queryset.gkr,
                queryset.gkr_phone, queryset.other1, queryset.other2,
                queryset.other3
            ]

            same_sheet.write_row(same_sheet_row_num, 0, query_set_list)
            same_sheet_row_num += 1

        else:
            different_sheet.write_row(different_sheet_row_num, 0,
                                      sheet1.row_values(n))
            different_sheet_row_num += 1
    bddc_result_xls.close()

    file_tmp = open(result_path, 'rb')

    response = FileResponse(file_tmp)

    response['Content-Type'] = 'application/vnd.ms-excel'
    response['Content-Disposition'] = 'attachment;filename=' + urlquote(
        '库中比对导出结果' + timestr + '.xls')  # 返回下载文件的名称(activity.xls)

    return response
Example #33
0
 def test_item_guid(self):
     t = self.feed.item_guid(self.addon)
     url = u'/addon/%s/versions/v%s' % (self.addon.slug,
                                        urllib.urlquote(self.u))
     assert t.endswith(url), t
Example #34
0
def opds_feed_for_works(the_facet, page=None, order_by='newest'):
    works = the_facet.works
    feed_path = the_facet.feed_path
    title = the_facet.title
    feed_xml = """<feed xmlns:dcterms="http://purl.org/dc/terms/" 
      xmlns:opds="http://opds-spec.org/"
      xmlns="http://www.w3.org/2005/Atom"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:schema="http://schema.org/"
      xsi:noNamespaceSchemaLocation="http://www.kbcafe.com/rss/atom.xsd.xml"
      xsi:schemaLocation="http://purl.org/dc/elements/1.1/ http://dublincore.org/schemas/xmls/qdc/2008/02/11/dc.xsd 
      http://purl.org/dc/terms/ http://dublincore.org/schemas/xmls/qdc/2008/02/11/dcterms.xsd"/>"""

    feed = etree.fromstring(feed_xml)

    # add title
    # TO DO: will need to calculate the number items and where in the feed we are

    feed.append(text_node('title', title + ' - sorted by ' + order_by))

    # id

    feed.append(
        text_node(
            'id', "{url}/api/opds/{feed_path}/?order_by={order_by}".format(
                url=UNGLUEIT_URL,
                feed_path=urlquote(feed_path),
                order_by=order_by)))

    # updated
    # TO DO:  fix time zone?
    # also use our wrapped datetime code

    feed.append(
        text_node('updated',
                  pytz.utc.localize(datetime.datetime.utcnow()).isoformat()))

    # author

    author_node = etree.Element("author")
    author_node.append(text_node('name', 'unglue.it'))
    author_node.append(text_node('uri', UNGLUEIT_URL))
    feed.append(author_node)

    # links:  start, self, next/prev (depending what's necessary -- to start with put all CC books)

    # start link
    append_navlink(feed, 'start', feed_path, None, order_by, title="First 10")

    # next link

    if not page:
        page = 0
    else:
        try:
            page = int(page)
        except TypeError:
            page = 0

    try:
        works[10 * page + 10]
        append_navlink(feed,
                       'next',
                       feed_path,
                       page + 1,
                       order_by,
                       title="Next 10")
    except IndexError:
        pass

    # sort facets
    append_navlink(feed,
                   FACET_RELATION,
                   feed_path,
                   None,
                   'popular',
                   group="Order",
                   active=order_by == 'popular',
                   title="Sorted by popularity")
    append_navlink(feed,
                   FACET_RELATION,
                   feed_path,
                   None,
                   'newest',
                   group="Order",
                   active=order_by == 'newest',
                   title="Sorted by newest")

    #other facets
    if feed_path not in old_facets:
        for other_group in the_facet.facet_object.get_other_groups():
            for facet_object in other_group.get_facets():
                append_navlink(feed,
                               FACET_RELATION,
                               feed_path + '/' + facet_object.facet_name,
                               None,
                               order_by,
                               group=other_group.title,
                               title=facet_object.title)

    works = islice(works, 10 * page, 10 * page + 10)
    if page > 0:
        append_navlink(feed,
                       'previous',
                       feed_path,
                       page - 1,
                       order_by,
                       title="Previous 10")
    for work in works:
        node = work_node(work, facet=the_facet.facet_object)
        feed.append(node)

    return etree.tostring(feed, pretty_print=True)
Example #35
0
 def get_google_reverse_image_search_url(self, image_url):
     url = "https://www.google.com/searchbyimage?&image_url="
     absolute_image_url = self.request.build_absolute_uri(image_url)
     return url + urlquote(absolute_image_url)
Example #36
0
 def get_absolute_url(self):
     """Get absolute URL."""
     return '/factories/%s/' % urlquote(self.name)
Example #37
0
class LoginAndPermissionMiddleware(object):
    """
  Middleware that forces all views (except those that opt out) through authentication.
  """
    def process_view(self, request, view_func, view_args, view_kwargs):
        """
    We also perform access logging in ``process_view()`` since we have the view function,
    which tells us the log level. The downside is that we don't have the status code,
    which isn't useful for status logging anyways.
    """
        access_log_level = getattr(view_func, 'access_log_level', None)
        # First, skip views not requiring login

        # If the view has "opted out" of login required, skip
        if hasattr(view_func, "login_notrequired"):
            log_page_hit(request,
                         view_func,
                         level=access_log_level or logging.DEBUG)
            return None

        # There are certain django views which are also opt-out, but
        # it would be evil to go add attributes to them
        if view_func in DJANGO_VIEW_AUTH_WHITELIST:
            log_page_hit(request,
                         view_func,
                         level=access_log_level or logging.DEBUG)
            return None

        # If user is logged in, check that he has permissions to access the
        # app.
        if request.user.is_active and request.user.is_authenticated():
            AppSpecificMiddleware.augment_request_with_app(request, view_func)

            # Until we get Django 1.3 and resolve returning the URL name, we just do a match of the name of the view
            try:
                access_view = 'access_view:%s:%s' % (
                    request._desktop_app, resolve(request.path)[0].__name__)
            except Exception, e:
                access_log(request,
                           'error checking view perm: %s',
                           e,
                           level=access_log_level)
                access_view = ''

            # Accessing an app can access an underlying other app.
            # e.g. impala or spark uses code from beeswax and so accessing impala shows up as beeswax here.
            # Here we trust the URL to be the real app we need to check the perms.
            app_accessed = request._desktop_app
            ui_app_accessed = get_app_name(request)
            if app_accessed != ui_app_accessed and ui_app_accessed not in (
                    'logs', 'accounts', 'login'):
                app_accessed = ui_app_accessed

            if app_accessed and \
                app_accessed not in ("desktop", "home", "about") and \
                not (request.user.has_hue_permission(action="access", app=app_accessed) or
                     request.user.has_hue_permission(action=access_view, app=app_accessed)):
                access_log(request,
                           'permission denied',
                           level=access_log_level)
                return PopupException(_(
                    "You do not have permission to access the %(app_name)s application."
                ) % {
                    'app_name': app_accessed.capitalize()
                },
                                      error_code=401).response(request)
            else:
                log_page_hit(request, view_func, level=access_log_level)
                return None

        logging.info("Redirecting to login page: %s", request.get_full_path())
        access_log(request, 'login redirection', level=access_log_level)
        if request.ajax:
            # Send back a magic header which causes Hue.Request to interpose itself
            # in the ajax request and make the user login before resubmitting the
            # request.
            response = HttpResponse("/* login required */",
                                    content_type="text/javascript")
            response[MIDDLEWARE_HEADER] = 'LOGIN_REQUIRED'
            return response
        else:
            return HttpResponseRedirect(
                "%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                              urlquote(request.get_full_path())))
Example #38
0
def get_cas_url(cas):
    if cas:
        return u"{}?cas={}".format(reverse('assessment:cas_details'),
                                   urlquote(cas))
    else:
        return None
Example #39
0
from django.utils import http as utils_http

from mox3.mox import IsA  # noqa

from openstack_dashboard import api
from openstack_dashboard.dashboards.project.containers import forms
from openstack_dashboard.dashboards.project.containers import tables
from openstack_dashboard.dashboards.project.containers import utils
from openstack_dashboard.dashboards.project.containers import views
from openstack_dashboard.test import helpers as test

from horizon.utils.urlresolvers import reverse  # noqa

CONTAINER_NAME_1 = u"container one%\u6346"
CONTAINER_NAME_2 = u"container_two\u6346"
CONTAINER_NAME_1_QUOTED = utils_http.urlquote(CONTAINER_NAME_1)
CONTAINER_NAME_2_QUOTED = utils_http.urlquote(CONTAINER_NAME_2)
INVALID_CONTAINER_NAME_1 = utils_http.urlquote(CONTAINER_NAME_1_QUOTED)
INVALID_CONTAINER_NAME_2 = utils_http.urlquote(CONTAINER_NAME_2_QUOTED)
CONTAINER_INDEX_URL = reverse('horizon:project:containers:index')

INVALID_PATHS = []


def invalid_paths():
    if not INVALID_PATHS:
        for x in (CONTAINER_NAME_1_QUOTED, CONTAINER_NAME_2_QUOTED):
            y = reverse('horizon:project:containers:index',
                        args=(utils.wrap_delimiter(x), ))
            INVALID_PATHS.append(y)
        for x in (CONTAINER_NAME_1, CONTAINER_NAME_2):
Example #40
0
def jjbd_upload_hwz(request):
    excel = request.FILES.get('excel')
    bd_type = request.POST.get('bd_type')

    # 获取文件类型
    file_type = excel.name.rsplit('.')[-1]
    file_type = file_type.lower()

    # 获取当前时间的时间戳
    timestr = str(time.time()).replace('.', '')
    # 获取程序需要写入的文件路径
    path = os.path.join(settings.BASE_DIR + settings.MEDIA_URL,
                        '{0}.{1}'.format(timestr, file_type))
    # 根据路径打开指定的文件(以二进制读写方式打开)
    f = open(path, 'wb+')
    # chunks将对应的文件数据转换成若干片段, 分段写入, 可以有效提高文件的写入速度, 适用于2.5M以上的文件
    for chunk in excel.chunks():
        f.write(chunk)
    f.close()

    # 创建比对结果导出文档
    result_path = os.path.join(settings.BASE_DIR + settings.MEDIA_URL, 'jjbd/',
                               '{0}.xls'.format(timestr))
    jjbd_result_xls = xlsxwriter.Workbook(result_path)  # 新建excel表
    same_sheet = jjbd_result_xls.add_worksheet('相同结果集')
    different_sheet = jjbd_result_xls.add_worksheet('不同结果集')
    same_sheet_row_num = 0
    different_sheet_row_num = 0

    # 开始导入excel模板
    book = xlrd.open_workbook(path)
    sheet1 = book.sheets()[0]
    row_num = sheet1.nrows

    for n in range(0, row_num):
        cell_0_value = sheet1.cell_value(n, 0)
        if sheet1.cell(n, 0).ctype == 2:
            cell_0_value = str(int(cell_0_value))
        cell_0_value = cell_0_value.strip()

        cell_1_value = sheet1.cell_value(n, 1)
        if sheet1.cell(n, 1).ctype == 2:
            cell_1_value = str(int(cell_1_value))
        cell_1_value = cell_1_value.strip()
        kwargs = {
            # 动态查询的字段
        }

        if bd_type == '1' and cell_0_value != '':  # 手机号
            kwargs['phone_no'] = cell_0_value
        elif bd_type == '2' and cell_0_value != '':  # 身份证号
            kwargs['sfzh'] = cell_0_value
        elif bd_type == '3' and cell_1_value != '':  # 手机第一列,姓名第二列
            kwargs['phone_no'] = cell_0_value
            kwargs['name'] = cell_1_value
        elif bd_type == '4':
            pass
        if kwargs and yqdx_hwz.objects.filter(**kwargs).exists():
            same_sheet.write_row(same_sheet_row_num, 0, sheet1.row_values(n))
            same_sheet_row_num += 1
        else:
            different_sheet.write_row(different_sheet_row_num, 0,
                                      sheet1.row_values(n))
            different_sheet_row_num += 1
    jjbd_result_xls.close()

    file_tmp = open(result_path, 'rb')

    response = FileResponse(file_tmp)

    response['Content-Type'] = 'application/vnd.ms-excel'
    response['Content-Disposition'] = 'attachment;filename=' + urlquote(
        '比对结果' + timestr + '.xls')  # 返回下载文件的名称(activity.xls)

    return response
Example #41
0
def _redirect_for_login_or_domain(request, redirect_field_name, login_url):
    path = urlquote(request.get_full_path())
    nextURL = '%s?%s=%s' % (login_url, redirect_field_name, path)
    return HttpResponseRedirect(nextURL)
Example #42
0
def share(request, spot_id=None):
    if request.method == 'POST':
        form = ShareForm(request.POST)

        try:
            back = request.POST['back']
            validate_back_link(back)
        except:
            back = '/'

        if form.is_valid():
            spot_id = form.cleaned_data['spot_id']
            back = form.cleaned_data['back']
            sender = form.cleaned_data['sender']
            recipient = form.cleaned_data['recipient']
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            bot_test = form.cleaned_data['email_confirmation']

            url = "{0}/api/v1/spot/{1}/share".format(
                settings.SS_WEB_SERVER_HOST, spot_id)

            body = json.dumps({
                'to': recipient,
                'from': sender,
                'comment': message,
                'subject': subject
            })

            headers = {
                "XOAUTH_USER": "******" % request.user.username,
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }

            consumer = oauth2.Consumer(key=settings.SS_WEB_OAUTH_KEY,
                                       secret=settings.SS_WEB_OAUTH_SECRET)
            client = oauth2.Client(consumer)

            resp, content = client.request(url,
                                           method='PUT',
                                           body=body,
                                           headers=headers)

            if not (resp.status == 200 or resp.status == 201):
                logger.error('Share service failure %s: %s' %
                             (resp.status, url))
                return HttpResponseRedirect('/share/sorry/')

            return HttpResponseRedirect('/share/thankyou/?back=' +
                                        urlquote(back))
    else:
        # mask user from silliness
        try:
            back = request.GET['back']
            validate_back_link(back)
        except:
            back = '/'

        if request.user and request.user.is_authenticated():
            consumer = oauth2.Consumer(key=settings.SS_WEB_OAUTH_KEY,
                                       secret=settings.SS_WEB_OAUTH_SECRET)
            client = oauth2.Client(consumer)
            url = "{0}/api/v1/user/me".format(settings.SS_WEB_SERVER_HOST)

            headers = {
                "XOAUTH_USER": "******" % request.user.username,
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }

            resp, content = client.request(url, method='GET', headers=headers)

            sender = "%s@%s" % (request.user.username,
                                getattr(settings, 'SS_MAIL_DOMAIN', 'uw.edu'))
            if resp.status == 200:
                me = content = json.loads(content)
                if 'email' in me and len(me['email']):
                    sender = me['email']
        else:
            sender = ''

        form = ShareForm(
            initial={
                'spot_id': spot_id,
                'back': back,
                'sender': sender,
                'subject': 'Check out this space I found on SpaceScout',
            })

    try:
        spot = Spot(spot_id).get()
        share_text = [spot["name"], spot["type"]]
        if 'extended_info' in spot and 'location_description' in spot[
                'extended_info']:
            share_text.append(spot['extended_info']['location_description'])
    except SpotException as e:
        logger.error('Share failure for spot %s: %s' % (spot_id, e))
        return render_to_response('spacescout_web/share-sorry.html', {
            'problem':
            'Sorry, but the space you wish to share does not exist.',
            'back': back,
        },
                                  context_instance=RequestContext(request))

    share_url = 'http://%s/space/%s/%s' % (getattr(
        settings, 'SS_APP_SERVER',
        socket.gethostname()), spot_id, urlquote(spot["name"]))

    return render_to_response('spacescout_web/share-form.html', {
        'form': form,
        'back': back,
        'spot_id': spot_id,
        'share_text': share_text,
        'share_url': share_url,
        'hidden': ["spot_id", "back"],
        'is_mobile': (request.MOBILE == 1),
    },
                              context_instance=RequestContext(request))
    def render(self, request, instance, **kwargs):
        url = u"http://gist.github.com/{0}.js".format(instance.gist_id)
        if instance.filename:
            url += u"?file={0}".format(urlquote(instance.filename))

        return mark_safe(u'<script src="{0}"></script>'.format(url))
Example #44
0
 def get_absolute_url(self):
     return "/users/%s/" % urlquote(self.email)
Example #45
0
def details(request, slug):
    """
    The main view of the Django-CMS! Takes a request and a slug, renders the
    page.
    """
    response_timestamp = now()
    if get_cms_setting("PAGE_CACHE") and (
            not hasattr(request, 'toolbar') or
        (not request.toolbar.edit_mode_active
         and not request.toolbar.show_toolbar  # noqa: W503
         and not request.user.is_authenticated  # noqa: W503
         )):
        cache_content = get_page_cache(request)
        if cache_content is not None:
            content, headers, expires_datetime = cache_content
            response = HttpResponse(content)
            response.xframe_options_exempt = True
            if DJANGO_2_2 or DJANGO_3_0 or DJANGO_3_1:
                response._headers = headers
            else:
                #  for django3.2 and above. response.headers replace response._headers in earlier versions of django
                response.headers = headers
            # Recalculate the max-age header for this cached response
            max_age = int((expires_datetime -
                           response_timestamp).total_seconds() + 0.5)
            patch_cache_control(response, max_age=max_age)
            return response

    # Get a Page model object from the request
    site = get_current_site()
    page = get_page_from_request(request, use_path=slug)
    toolbar = get_toolbar_from_request(request)
    tree_nodes = TreeNode.objects.get_for_site(site)

    if not page and not slug and not tree_nodes.exists():
        # render the welcome page if the requested path is root "/"
        # and there's no pages
        return _render_welcome_page(request)

    if not page:
        # raise 404
        _handle_no_page(request)

    request.current_page = page

    if hasattr(request, 'user') and request.user.is_staff:
        user_languages = get_language_list(site_id=site.pk)
    else:
        user_languages = get_public_languages(site_id=site.pk)

    if is_language_prefix_patterns_used():
        request_language = get_language_from_request(request, check_path=True)
    else:
        request_language = get_default_language_for_site(site.pk)

    if not page.is_home and request_language not in user_languages:
        # The homepage is treated differently because
        # when a request goes to the root of the site (/)
        # without a language, Django will redirect to the user's
        # browser language which might not be a valid cms language,
        # this means we need to correctly redirect that request.
        return _handle_no_page(request)

    # get_published_languages will return all languages in draft mode
    # and published only in live mode.
    # These languages are then filtered out by the user allowed languages
    available_languages = [
        language for language in user_languages
        if language in list(page.get_published_languages())
    ]

    own_urls = [
        request.build_absolute_uri(request.path),
        '/%s' % request.path,
        request.path,
    ]

    try:
        redirect_on_fallback = get_redirect_on_fallback(request_language,
                                                        site_id=site.pk)
    except LanguageError:
        redirect_on_fallback = False

    if request_language not in user_languages:
        # Language is not allowed
        # Use the default site language
        default_language = get_default_language_for_site(site.pk)
        fallbacks = get_fallback_languages(default_language, site_id=site.pk)
        fallbacks = [default_language] + fallbacks
    else:
        fallbacks = get_fallback_languages(request_language, site_id=site.pk)

    # Only fallback to languages the user is allowed to see
    fallback_languages = [
        language for language in fallbacks
        if language != request_language and language in available_languages
    ]
    language_is_unavailable = request_language not in available_languages

    if language_is_unavailable and not fallback_languages:
        # There is no page with the requested language
        # and there's no configured fallbacks
        return _handle_no_page(request)
    elif language_is_unavailable and (redirect_on_fallback or page.is_home):
        # There is no page with the requested language and
        # the user has explicitly requested to redirect on fallbacks,
        # so redirect to the first configured / available fallback language
        fallback = fallback_languages[0]
        redirect_url = page.get_absolute_url(fallback, fallback=False)
    else:
        page_path = page.get_absolute_url(request_language)
        page_slug = page.get_path(request_language) or page.get_slug(
            request_language)

        if slug and slug != page_slug and request.path[:len(page_path
                                                            )] != page_path:
            # The current language does not match its slug.
            # Redirect to the current language.
            return HttpResponseRedirect(page_path)
        # Check if the page has a redirect url defined for this language.
        redirect_url = page.get_redirect(request_language,
                                         fallback=False) or ''
        redirect_url = _clean_redirect_url(redirect_url, request_language)

    if redirect_url:
        if request.user.is_staff and toolbar.edit_mode_active:
            toolbar.redirect_url = redirect_url
        elif redirect_url not in own_urls:
            # prevent redirect to self
            return HttpResponseRedirect(redirect_url)

    # permission checks
    if page.login_required and not request.user.is_authenticated:
        return redirect_to_login(urlquote(request.get_full_path()),
                                 settings.LOGIN_URL)

    if hasattr(request, 'toolbar'):
        request.toolbar.set_object(page)

    structure_requested = get_cms_setting(
        'CMS_TOOLBAR_URL__BUILD') in request.GET

    if user_can_change_page(request.user, page) and structure_requested:
        return render_object_structure(request, page)
    return render_page(request,
                       page,
                       current_language=request_language,
                       slug=slug)
Example #46
0
def check_active(url, element, full_path, css_class, menu):
    '''check "active" url, apply css_class'''
    # django > 1.5 template boolean\None variables feature
    if isinstance(menu, bool):
        if menu:
            menu = 'yes'
        else:
            menu = 'no'
    elif menu is None:
        menu = 'no'
    # check menu configuration, set boolean value
    if menu.lower() in ('yes', 'true'):
        menu = True
    elif menu.lower() in ('no', 'false'):
        menu = False
    else:
        raise ImproperlyConfigured('''
            malformed menu value
        ''')
    # check missing href parameter
    if not url.attrib.get('href', None) is None:
        # get href attribute
        href = url.attrib['href'].strip()
        # cut off hashtag (anchor)
        href = re.sub(r'\#.+', '', href)
        # check empty href
        if href == '':
            # replace href with current location
            href = full_path
        # compare full_path with href according to menu configuration

        # maybe an urlquoted href was supplied
        quoted_full_path = urlquote(full_path)

        if menu:
            # try mark "root" (/) url as "active", in equals way
            if href == '/' == full_path:
                logic = True
            # skip "root" (/) url, otherwise it will be always "active"
            elif href != '/':
                # start with logic
                logic = full_path.startswith(href) or \
                    quoted_full_path.startswith(href)
            else:
                logic = False
        else:
            # equals logic
            logic = (full_path == href or quoted_full_path == href)
        # "active" url found
        if logic:
            # check parent tag has "class" attribute or it is empty
            if element.attrib.get('class'):
                # prevent multiple "class" attribute adding
                if css_class not in element.attrib['class']:
                    # append "active" class
                    element.attrib['class'] += ' ' + css_class
            else:
                # create or set (if empty) "class" attribute
                element.attrib['class'] = css_class
            return True
    # no "active" urls found
    return False
Example #47
0
def login(request,
          template_name='registration/login.html',
          redirect_if_logged_in=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.REQUEST.get(redirect_field_name, '')
    ip = get_remote_ip(request)
    failed_attempt = _get_login_failed_attempts(ip=ip)

    if request.method == "POST":
        username = urlquote(request.REQUEST.get('username', '').strip())
        remember_me = True if request.REQUEST.get('remember_me',
                                                  '') == 'on' else False

        if failed_attempt >= settings.LOGIN_ATTEMPT_LIMIT:
            # have captcha
            form = CaptchaAuthenticationForm(data=request.POST)
            if form.is_valid():
                # captcha & passwod is valid, log user in
                request.session['remember_me'] = remember_me
                return log_user_in(request, form.get_user(), redirect_to)
            else:
                # show page with captcha and increase failed login attempts
                _incr_login_faied_attempts(username=username, ip=ip)
        else:
            form = authentication_form(data=request.POST)
            if form.is_valid():
                # password is valid, log user in
                request.session['remember_me'] = remember_me
                return log_user_in(request, form.get_user(), redirect_to)
            else:
                login = urlquote(request.REQUEST.get('login', '').strip())
                failed_attempt = _incr_login_faied_attempts(username=login,
                                                            ip=ip)

                if failed_attempt >= settings.LOGIN_ATTEMPT_LIMIT:
                    logger.warn(
                        'Login attempt limit reached, email/username: %s, ip: %s, attemps: %d'
                        % (login, ip, failed_attempt))
                    form = CaptchaAuthenticationForm()
                else:
                    form = authentication_form(data=request.POST)
    else:
        ### GET
        if failed_attempt >= settings.LOGIN_ATTEMPT_LIMIT:
            logger.warn('Login attempt limit reached, ip: %s, attempts: %d' %
                        (ip, failed_attempt))
            form = CaptchaAuthenticationForm(request)
        else:
            form = authentication_form(request)

    request.session.set_test_cookie()

    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)

    multi_tenancy = getattr(settings, 'MULTI_TENANCY', False)

    if config.ENABLE_SIGNUP:
        if multi_tenancy:
            org_account_only = getattr(settings, 'FORCE_ORG_REGISTER', False)
            if org_account_only:
                signup_url = reverse('org_register')
            else:
                signup_url = reverse('choose_register')
        else:
            signup_url = reverse('registration_register')
    else:
        signup_url = ''

    enable_shib_login = getattr(settings, 'ENABLE_SHIB_LOGIN', False)

    return render_to_response(template_name, {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'remember_days': config.LOGIN_REMEMBER_DAYS,
        'signup_url': signup_url,
        'enable_shib_login': enable_shib_login,
    },
                              context_instance=RequestContext(request))
Example #48
0
def details(request, slug):
    """
    The main view of the Django-CMS! Takes a request and a slug, renders the
    page.
    """

    if get_cms_setting("PAGE_CACHE") and (
            not hasattr(request, 'toolbar') or
        (not request.toolbar.edit_mode and not request.toolbar.show_toolbar
         and not request.user.is_authenticated())):
        cache_content = get_page_cache(request)
        if cache_content is not None:
            content, headers = cache_content
            response = HttpResponse(content)
            response._headers = headers
            return response

    # Get a Page model object from the request
    page = get_page_from_request(request, use_path=slug)
    if not page:
        return _handle_no_page(request, slug)
    current_language = request.GET.get('language', None)
    if not current_language:
        current_language = request.POST.get('language', None)
    if current_language:
        current_language = get_language_code(current_language)
        if current_language not in get_language_list(page.site_id):
            current_language = None
    if current_language is None:
        current_language = get_language_code(
            getattr(request, 'LANGUAGE_CODE', None))
        if current_language:
            current_language = get_language_code(current_language)
            if current_language not in get_language_list(page.site_id):
                current_language = None
    if current_language is None:
        current_language = get_language_code(get_language())
    # Check that the current page is available in the desired (current) language
    available_languages = []
    # this will return all languages in draft mode, and published only in live mode
    page_languages = list(page.get_published_languages())
    if hasattr(request, 'user') and request.user.is_staff:
        user_languages = get_language_list()
    else:
        user_languages = get_public_languages()
    for frontend_lang in user_languages:
        if frontend_lang in page_languages:
            available_languages.append(frontend_lang)
    # Check that the language is in FRONTEND_LANGUAGES:
    own_urls = [
        'http%s://%s%s' %
        ('s' if request.is_secure() else '', request.get_host(), request.path),
        '/%s' % request.path,
        request.path,
    ]
    if current_language not in user_languages:
        #are we on root?
        if not slug:
            #redirect to supported language
            languages = []
            for language in available_languages:
                languages.append((language, language))
            if languages:
                # get supported language
                new_language = get_language_from_request(request)
                if new_language in get_public_languages():
                    with force_language(new_language):
                        pages_root = reverse('pages-root')
                        if (hasattr(request, 'toolbar')
                                and request.user.is_staff
                                and request.toolbar.edit_mode):
                            request.toolbar.redirect_url = pages_root
                        elif pages_root not in own_urls:
                            return HttpResponseRedirect(pages_root)
            elif not hasattr(request,
                             'toolbar') or not request.toolbar.redirect_url:
                _handle_no_page(request, slug)
        else:
            return _handle_no_page(request, slug)
    if current_language not in available_languages:
        # If we didn't find the required page in the requested (current)
        # language, let's try to find a fallback
        found = False
        for alt_lang in get_fallback_languages(current_language):
            if alt_lang in available_languages:
                if get_redirect_on_fallback(current_language) or slug == "":
                    with force_language(alt_lang):
                        path = page.get_absolute_url(language=alt_lang,
                                                     fallback=True)
                        # In the case where the page is not available in the
                    # preferred language, *redirect* to the fallback page. This
                    # is a design decision (instead of rendering in place)).
                    if (hasattr(request, 'toolbar') and request.user.is_staff
                            and request.toolbar.edit_mode):
                        request.toolbar.redirect_url = path
                    elif path not in own_urls:
                        return HttpResponseRedirect(path)
                else:
                    found = True
        if not found and (not hasattr(request, 'toolbar')
                          or not request.toolbar.redirect_url):
            # There is a page object we can't find a proper language to render it
            _handle_no_page(request, slug)

    if apphook_pool.get_apphooks():
        # There are apphooks in the pool. Let's see if there is one for the
        # current page
        # since we always have a page at this point, applications_page_check is
        # pointless
        # page = applications_page_check(request, page, slug)
        # Check for apphooks! This time for real!
        app_urls = page.get_application_urls(current_language, False)
        skip_app = False
        if (not page.is_published(current_language)
                and hasattr(request, 'toolbar') and request.toolbar.edit_mode):
            skip_app = True
        if app_urls and not skip_app:
            app = apphook_pool.get_apphook(app_urls)
            pattern_list = []
            for urlpatterns in get_app_urls(app.urls):
                pattern_list += urlpatterns
            try:
                view, args, kwargs = resolve('/', tuple(pattern_list))
                return view(request, *args, **kwargs)
            except Resolver404:
                pass
                # Check if the page has a redirect url defined for this language.
    redirect_url = page.get_redirect(language=current_language)
    if redirect_url:
        if (is_language_prefix_patterns_used() and redirect_url[0] == "/"
                and not redirect_url.startswith('/%s/' % current_language)):
            # add language prefix to url
            redirect_url = "/%s/%s" % (current_language,
                                       redirect_url.lstrip("/"))
            # prevent redirect to self

        if hasattr(request, 'toolbar'
                   ) and request.user.is_staff and request.toolbar.edit_mode:
            request.toolbar.redirect_url = redirect_url
        elif redirect_url not in own_urls:
            return HttpResponseRedirect(redirect_url)

    # permission checks
    if page.login_required and not request.user.is_authenticated():
        return redirect_to_login(urlquote(request.get_full_path()),
                                 settings.LOGIN_URL)
    if hasattr(request, 'toolbar'):
        request.toolbar.set_object(page)

    response = render_page(request,
                           page,
                           current_language=current_language,
                           slug=slug)
    return response
Example #49
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        """
    We also perform access logging in ``process_view()`` since we have the view function,
    which tells us the log level. The downside is that we don't have the status code,
    which isn't useful for status logging anyways.
    """
        request.ts = time.time()
        request.view_func = view_func
        access_log_level = getattr(view_func, 'access_log_level', None)

        # Skip loop for oidc
        if request.path in [
                '/oidc/authenticate/', '/oidc/callback/', '/oidc/logout/',
                '/hue/oidc_failed/'
        ]:
            return None

        # Skip views not requiring login

        # If the view has "opted out" of login required, skip
        if hasattr(view_func, "login_notrequired"):
            log_page_hit(request,
                         view_func,
                         level=access_log_level or logging.DEBUG)
            return None

        # There are certain django views which are also opt-out, but
        # it would be evil to go add attributes to them
        if view_func in DJANGO_VIEW_AUTH_WHITELIST:
            log_page_hit(request,
                         view_func,
                         level=access_log_level or logging.DEBUG)
            return None

        # If user is logged in, check that he has permissions to access the app
        if request.user.is_active and request.user.is_authenticated():
            AppSpecificMiddleware.augment_request_with_app(request, view_func)

            # Until Django 1.3 which resolves returning the URL name, just do a match of the name of the view
            try:
                access_view = 'access_view:%s:%s' % (
                    request._desktop_app, resolve(request.path)[0].__name__)
            except Exception as e:
                access_log(request,
                           'error checking view perm: %s' % e,
                           level=access_log_level)
                access_view = ''

            app_accessed = request._desktop_app
            app_libs_whitelist = ("desktop", "home", "home2", "about", "hue",
                                  "editor", "notebook", "indexer", "404",
                                  "500", "403")
            # Accessing an app can access an underlying other app.
            # e.g. impala or spark uses code from beeswax and so accessing impala shows up as beeswax here.
            # Here we trust the URL to be the real app we need to check the perms.
            ui_app_accessed = get_app_name(request)
            if app_accessed != ui_app_accessed and ui_app_accessed not in (
                    'logs', 'accounts', 'login'):
                app_accessed = ui_app_accessed

            if app_accessed and \
                app_accessed not in app_libs_whitelist and \
                not (
                    is_admin(request.user) or
                    request.user.has_hue_permission(action="access", app=app_accessed) or
                    request.user.has_hue_permission(action=access_view, app=app_accessed)
                ) and \
                not (app_accessed == '__debug__' and DJANGO_DEBUG_MODE.get()):
                access_log(request,
                           'permission denied',
                           level=access_log_level)
                return PopupException(_(
                    "You do not have permission to access the %(app_name)s application."
                ) % {
                    'app_name': app_accessed.capitalize()
                },
                                      error_code=401).response(request)
            else:
                if not hasattr(request, 'view_func'):
                    log_page_hit(request, view_func, level=access_log_level)
                return None

        logging.info("Redirecting to login page: %s", request.get_full_path())
        access_log(request, 'login redirection', level=access_log_level)
        no_idle_backends = ("libsaml.backend.SAML2Backend",
                            "desktop.auth.backend.SpnegoDjangoBackend",
                            "desktop.auth.backend.KnoxSpnegoDjangoBackend")
        if request.ajax and all(no_idle_backend not in AUTH.BACKEND.get()
                                for no_idle_backend in no_idle_backends):
            # Send back a magic header which causes Hue.Request to interpose itself
            # in the ajax request and make the user login before resubmitting the
            # request.
            response = HttpResponse("/* login required */",
                                    content_type="text/javascript")
            response[MIDDLEWARE_HEADER] = 'LOGIN_REQUIRED'
            return response
        else:
            if request.GET.get('is_embeddable'):
                return JsonResponse(
                    {
                        'url':
                        "%s?%s=%s" %
                        (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                         urlquote('/hue' + request.get_full_path().replace(
                             'is_embeddable=true', '').replace('&&', '&')))
                    }
                )  # Remove embeddable so redirect from & to login works. Login page is not embeddable
            else:
                return HttpResponseRedirect(
                    "%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                                  urlquote(request.get_full_path())))
Example #50
0
    def get_object(self, queryset=None):
        obj = super(PosterView, self).get_object(queryset)
        # limit 20
        # obj.comments = obj.comment_set.all().select_related('creator').order_by('-created_at')[:self.COMMENT_SIZE]
        # stats
        queryset = PosterStatistics.objects.filter(pk=obj.pk)
        fields = dict(views_count=1)
        if 'scan' in self.request.GET:
            fields['scans_count'] = 1
        DBUtils.increase_counts(queryset, fields)
        # orgnize elements
        images = dict()
        videos = dict()
        for poster_image in obj.poster_images.all():
            images[poster_image.name] = poster_image.image
        for poster_video in obj.poster_videos.all():
            videos[poster_video.name] = poster_video.video
        obj.images = images
        obj.videos = videos
        poster_pages = obj.poster_pages.all()
        pages = [None for poster_page in poster_pages]
        regions = []
        for poster_page in poster_pages:
            pages[poster_page.index] = poster_page
            poster_regions = []
            for template_region in poster_page.template.template_regions.all():
                poster_regions.append(template_region)
                regions.append(template_region)
            poster_page.regions = poster_regions
        obj.pages = pages
        obj.regions = regions
        obj.capture = 'capture' in self.request.GET
        PosterService.parse_media_file(obj.html.name, obj)
        if not obj.capture:
            obj.image_url, obj.pdf_url = PosterService.capture(self.request, obj, force='force' in self.request.GET)
        obj.share = self.create_share(obj)
        user = self.request.user
        if user.is_authenticated():
            my_rating = obj.ratings.all()
            if my_rating:
                obj.my_rating = my_rating[0]
        # tailor mobile format, if no mobile then copy phone
        if not obj.mobile and obj.phone:
            obj.mobile = obj.phone
        if len(obj.mobile)<=10:
            obj.mobile = obj.mobile[:3]+'-'+obj.mobile[3:6]+'-'+obj.mobile[6:]
        # prepare email content to send
        url_detail = '\nquote:\n"'+obj.short_description+'\n'+Utils.get_current_url(self.request)+'\n"'
        title = obj.logo_title
        obj.email_content = 'subject=%s&body=%s' % ('To: '+urlquote(title, ''), urlquote(url_detail, ''))
        # extract hours details and check whether available currently
        now = datetime.datetime.now(tz=pytz.utc)
        timezone = pytz.timezone(obj.lifetime_timezone)
        now = now.astimezone(timezone)
        day_now = now.strftime('%Y-%m-%d')
        obj.day_now = day_now
        hours_available = False
        hours_info = 'Hours Today: Disabled'
        hours_details = OrderedDict()
        try:
            hours_all = json.loads(obj.lifetime_value,object_pairs_hook=OrderedDict)
            hours = None
            if obj.lifetime_type == 'weekly':
                """ e.g. {"Wednesday": {"disabled": 1, "time_start": "", "time_end": ""}, "Monday":
                {"time_start": "08:00:00", "enabled": 1, "time_end": "18:00:00"}, "Tuesday": {"
                enabled": 1, "time_start": "08:00:00", "time_end": "18:00:00"}}
                """
                # the lifetime value of hours must be json format, auto generated by program
                weekday = now.strftime('%A')# 'Monday', or 'Tuesday'
                hours = hours_all[weekday]
            elif obj.lifetime_type == 'specific_days':
                """e.g. {"2015-11-20": {"time_start": "08:00:00", "enabled": 1,
                "time_end": "21:00:00", "message": "Funding opening day and project demonstration"}}
                """
                if day_now in hours_all.keys():
                    hours = hours_all[day_now]
            if hours:
                if 'enabled' in hours and hours['enabled']:
                    if 'time_start' in hours and hours['time_start']:
                        time_start = timezone.localize(datetime.datetime.strptime(day_now+' '+hours['time_start'],'%Y-%m-%d %I:%M %p'))
                        time_end = timezone.localize(datetime.datetime.strptime(day_now+' '+hours['time_end'],'%Y-%m-%d %I:%M %p'))
                        hours_info = 'Hours Today: '+ time_start.strftime('%I:%M %p') + ' - ' + time_end.strftime('%I:%M %p')
                        if time_start <= now <= time_end:
                            hours_available = True

            # extract details of hours
            for day, day_hours in hours_all.items():
                if 'enabled' in day_hours and day_hours['enabled']:
                    if 'time_start' in day_hours and day_hours['time_start']:
                        hours_detail = day_hours['time_start'] + ' - '+day_hours['time_end']
                    else:
                        hours_detail =  '8:00 am - 6:00 pm'
                    if 'message'in day_hours and day_hours['message']:
                        hours_detail += '<br/>' + day_hours['message']
                else:
                    if 'time_start' in day_hours and day_hours['time_start']:
                        hours_detail = day_hours['time_start'] + ' - ' +\
                                                    day_hours['time_end'] + ' (closed temporarily)'
                    else:
                        hours_detail = 'closed'
                hours_details[day] = hours_detail
        except ValueError:
                None
        if hours_available:
            obj.hours_status = 'Open'
        else:
            obj.hours_status = 'Closed'
        obj.hours = hours_info
        obj.hours_details = hours_details
        # extract address info
        addr = obj.address
        obj.address_info = addr.address1 + ', ' + addr.city + ', ' + addr.state + ' ' + addr.post_code
        obj.address_mapped = (addr.address1 + ','+addr.city + ' '+addr.state).replace(' ', '+')
        obj.description_first_line = obj.short_description[:60]
        obj.description_others = obj.short_description[60:]
        cookie_abutton_fun_enabled =  self.request.COOKIES.get('abutton-fun-enabled')
        if cookie_abutton_fun_enabled:
            obj.abutton_fun_enabled = cookie_abutton_fun_enabled
        else:
            obj.abutton_fun_enabled = 1
        cookie_abutton_like_enabled =  self.request.COOKIES.get('abutton-like-enabled')
        if cookie_abutton_like_enabled:
            obj.abutton_like_enabled = cookie_abutton_like_enabled
        else:
            obj.abutton_like_enabled = 1
        cookie_abutton_bookmark_enabled =  self.request.COOKIES.get('abutton-bookmark-enabled')
        if cookie_abutton_bookmark_enabled:
            obj.abutton_bookmark_enabled = cookie_abutton_bookmark_enabled
        else:
            obj.abutton_bookmark_enabled = 1
        cookie_abutton_subscribe_enabled =  self.request.COOKIES.get('abutton-bookmark-enabled')
        if cookie_abutton_subscribe_enabled:
            obj.abutton_subscribe_enabled = cookie_abutton_subscribe_enabled
        else:
            obj.abutton_subscribe_enabled = 1


        return obj
Example #51
0
def login(request, template_name='registration/login.html',
          redirect_if_logged_in=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.REQUEST.get(redirect_field_name, '')
    ip = get_remote_ip(request)


    if request.method == "POST":
        login = urlquote(request.REQUEST.get('login', '').strip())
        failed_attempt = _get_login_failed_attempts(username=login, ip=ip)
        remember_me = True if request.REQUEST.get('remember_me',
                                                  '') == 'on' else False

        # check the form
        used_captcha_already = False
        if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
            form = authentication_form(data=request.POST)
        else:
            if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
                form = CaptchaAuthenticationForm(data=request.POST)
                used_captcha_already = True
            else:
                form = authentication_form(data=request.POST)

        if form.is_valid():
            return _handle_login_form_valid(request, form.get_user(),
                                            redirect_to, remember_me)

        # form is invalid
        failed_attempt = _incr_login_failed_attempts(username=login,
                                                    ip=ip)

        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                # log user in if password is valid otherwise freeze account
                logger.warn('Login attempt limit reached, try freeze the user, email/username: %s, ip: %s, attemps: %d' %
                            (login, ip, failed_attempt))
                login = request.REQUEST.get('login', '')
                email = Profile.objects.get_username_by_login_id(login)
                if email is None:
                    email = login
                try:
                    user = User.objects.get(email)
                    if user.is_active:
                        user.freeze_user(notify_admins=True)
                        logger.warn('Login attempt limit reached, freeze the user email/username: %s, ip: %s, attemps: %d' %
                                    (login, ip, failed_attempt))
                except User.DoesNotExist:
                    logger.warn('Login attempt limit reached with invalid email/username: %s, ip: %s, attemps: %d' %
                                (login, ip, failed_attempt))
                    pass
                form.errors['freeze_account'] = _('This account has been frozen due to too many failed login attempts.')
            else:
                # use a new form with Captcha
                logger.warn('Login attempt limit reached, show Captcha, email/username: %s, ip: %s, attemps: %d' %
                            (login, ip, failed_attempt))
                if not used_captcha_already:
                    form = CaptchaAuthenticationForm()
    else:
        ### GET
        failed_attempt = _get_login_failed_attempts(ip=ip)
        if failed_attempt >= config.LOGIN_ATTEMPT_LIMIT:
            if bool(config.FREEZE_USER_ON_LOGIN_FAILED) is True:
                form = authentication_form()
            else:
                logger.warn('Login attempt limit reached, show Captcha, ip: %s, attempts: %d' %
                            (ip, failed_attempt))
                form = CaptchaAuthenticationForm()
        else:
            form = authentication_form()

    request.session.set_test_cookie()

    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)

    multi_tenancy = getattr(settings, 'MULTI_TENANCY', False)

    if config.ENABLE_SIGNUP:
        if multi_tenancy:
            org_account_only = getattr(settings, 'FORCE_ORG_REGISTER', False)
            if org_account_only:
                signup_url = reverse('org_register')
            else:
                signup_url = reverse('choose_register')
        else:
            signup_url = reverse('registration_register')
    else:
        signup_url = ''

    enable_shib_login = getattr(settings, 'ENABLE_SHIB_LOGIN', False)
    enable_krb5_login = getattr(settings, 'ENABLE_KRB5_LOGIN', False)
    enable_adfs_login = getattr(settings, 'ENABLE_ADFS_LOGIN', False)

    return render_to_response(template_name, {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'remember_days': config.LOGIN_REMEMBER_DAYS,
        'signup_url': signup_url,
        'enable_shib_login': enable_shib_login,
        'enable_krb5_login': enable_krb5_login,
        'enable_adfs_login': enable_adfs_login,
    }, context_instance=RequestContext(request))
Example #52
0
 def _wrapped_view(request, *args, **kwargs):
     if test_func(request.user):
         return view_func(request, *args, **kwargs)
     path = urlquote(request.get_full_path())
     tup = reverse('login'), redirect_field_name, path
     return HttpResponseRedirect('%s?%s=%s' % tup)
Example #53
0
 def quoted_logical_path(self):
     return urlquote(self.pretty_logical_path)
Example #54
0
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    "Redirects the user to the login page, passing the given 'next' page"
    if not login_url:
        login_url = settings.LOGIN_URL
    return HttpResponseRedirect('%s?%s=%s' % (login_url, urlquote(redirect_field_name), urlquote(next)))
Example #55
0
 def get_view_link(self):
     return '/offer/%s' % self.id + '/' + urlquote(slugify(
         self.issue.title))
Example #56
0
 def get_absolute_url(self):
     return "/clients/%s/" % urlquote(self.email)
Example #57
0
def get_vip_link(pool):
    if pool.vip_id:
        return reverse("horizon:project:loadbalancers:vipdetails",
                       args=(http.urlquote(pool.vip_id), ))
    else:
        return None
def sendfile(request,
             filename,
             attachment=False,
             attachment_filename=None,
             mimetype=None,
             encoding=None):
    '''
    create a response to send file using backend configured in SENDFILE_BACKEND

    If attachment is True the content-disposition header will be set.
    This will typically prompt the user to download the file, rather
    than view it.  The content-disposition filename depends on the
    value of attachment_filename:

        None (default): Same as filename
        False: No content-disposition filename
        String: Value used as filename

    If no mimetype or encoding are specified, then they will be guessed via the
    filename (using the standard python mimetypes module)
    '''
    _sendfile = _get_sendfile()

    if not os.path.exists(filename):
        from django.http import Http404
        raise Http404('"%s" does not exist' % filename)

    guessed_mimetype, guessed_encoding = guess_type(filename)
    if mimetype is None:
        if guessed_mimetype:
            mimetype = guessed_mimetype
        else:
            mimetype = 'application/octet-stream'

    response = _sendfile(request, filename, mimetype=mimetype)
    parts = []
    if attachment:
        if attachment_filename is None:
            attachment_filename = os.path.basename(filename)
        parts.append('attachment')
    if attachment_filename:
        try:
            from django.utils.encoding import force_text
        except ImportError:
            # Django 1.3
            from django.utils.encoding import force_unicode as force_text
        attachment_filename = force_text(attachment_filename)
        ascii_filename = unicodedata.normalize('NFKD',
                                               attachment_filename).encode(
                                                   'ascii', 'ignore')
        parts.append('filename="%s"' % ascii_filename)
        if ascii_filename != attachment_filename:
            from django.utils.http import urlquote
            quoted_filename = urlquote(attachment_filename)
            parts.append('filename*=UTF-8\'\'%s' % quoted_filename)
    if parts:
        response['Content-Disposition'] = '; '.join(parts)

    response['Content-length'] = os.path.getsize(filename)
    response['Content-Type'] = mimetype
    if not encoding:
        encoding = guessed_encoding
    if encoding:
        response['Content-Encoding'] = encoding

    return response
Example #59
0
                    v = v()
                elif type(f) == fields.DateField:
                    v = v.strftime('%Y-%m-%d')
                elif type(f) == fields.DateTimeField:
                    v = v.strftime('%Y-%m-%d %H:%M')
                elif type(f) == fields.CharField and f.choices:
                    fc = 'get_'+field+'_display'
                    v = getattr(obj,fc)()
                elif type(f) == related.ForeignKey:
                    v = str(v)
                sheet.write(row_index,col_index,v)
                col_index += 1
            row_index += 1
        response = HttpResponse(content_type='application/vnd.ms-excel')
        agent = request.META.get('HTTP_USER_AGENT')
        nn = smart_str(file_name)
        if agent and re.search('MSIE',agent):
            nn = urlquote(file_name)
        response['Content-Disposition'] = 'attachment; filename=%s.xls'%nn
        workbook.save(response)
        return response
        #self.message_user(request,'SUCCESS')
    export_selected_data.short_description = _("export selected %(verbose_name_plural)s")

    class Meta:
        ordering = ['-creation']

    class Media:
        css = {'all':('css/maximus.css',)}
        js = ('js/maximus.js',)
Example #60
0
 def get_view_link(self):
     return '/project/%s/%s' % (self.id, urlquote(self.name))