示例#1
0
def get_flatpages(context, starts_with=None, user=None, site_pk=None):
    """
    Context-function similar to get_flatpages tag in Django templates.

    Usage:
        <ul>
            {% for page in get_flatpages(starts_with='/about/', user=user, site_pk=site.pk) %}
                <li><a href="{{ page.url }}">{{ page.title }}</a></li>
            {% endfor %}
        </ul>

    """
    if 'request' in context:
        request = context['request']
        if hasattr(request, 'site'):
            site_pk = request.site.pk
        else:
            site_pk = get_current_site(request).pk
    else:
        site_pk = settings.SITE_ID

    flatpages = FlatPage.objects.filter(sites__id=site_pk or settings.SITE_ID)

    if starts_with:
        flatpages = flatpages.filter(url__startswith=starts_with)

    if not user or not user.is_authenticated():
        flatpages = flatpages.filter(registration_required=False)

    return flatpages
示例#2
0
def remember_me_login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationRememberMeForm,
          current_app=None, extra_context=None):
    """
    Based on login view cribbed from
    https://github.com/django/django/blob/1.6/django/contrib/auth/views.py#L25

    Displays the login form with a remember me checkbox and handles the
    login action.

    The authentication_form parameter has been changed from
    ``django.contrib.auth.forms.AuthenticationForm`` to
    ``remember_me.forms.AuthenticationRememberMeForm``.  To change this, pass a
    different form class as the ``authentication_form`` parameter.

    """

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

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            if not form.cleaned_data.get('remember_me'):
                request.session.set_expiry(0)

            # Okay, security checks complete. Log the user in.
            auth_login(request, form.get_user())

            return HttpResponseRedirect(redirect_to)

        # TODO:
        # Temporary patch to redirect invalid credentials to Yezdo's old app
        elif request.POST.get('email') and request.POST.get('password'):
            from cfdi.views import get_login_redirect
            if not User.objects.filter(email=request.POST.get('email')).exists():
                return get_login_redirect(request.POST['email'], request.POST['password'], url='https://app.yezdo.com/cuentas/ingresar/')

    else:
        form = authentication_form(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context,
                            current_app=current_app)
示例#3
0
def editable(context, element):
    request = context['request']
    if not element or not request.user.has_perm('can_edit_site', get_current_site(None)):
        return ''
    if isinstance(element, list):
        idx = element[0]
        element[0] += 1
    else:
        idx = element
    return '_ped_%s" contenteditable="true' % idx
示例#4
0
    def resend_activation_email(self, request, queryset):
        """
        Re-sends activation emails for the selected users.

        Note that this will *only* send activation emails for users
        who are eligible to activate; emails will not be sent to users
        whose activation keys have expired or who have already
        activated.

        """
        site = get_current_site(request)

        for profile in queryset:
            if not profile.activation_key_expired():
                profile.send_activation_email(site)
示例#5
0
    def send_activation_email(self, site=None):
        """
        Send an activation email to the user associated with this
        ``RegistrationProfile``.

        The activation email will make use of two templates:

        ``registration/activation_email_subject.txt``
            This template will be used for the subject line of the
            email. Because it is used as the subject line of an email,
            this template's output **must** be only a single line of
            text; output longer than one line will be forcibly joined
            into only a single line.

        ``registration/activation_email.txt``
            This template will be used for the body of the email.

        These templates will each receive the following context
        variables:

        ``activation_key``
            The activation key for the new account.

        ``expiration_days``
            The number of days remaining during which the account may
            be activated.

        ``site``
            An object representing the site on which the user
            registered; depending on whether ``django.contrib.sites``
            is installed, this may be an instance of either
            ``django.contrib.sites.models.Site`` (if the sites
            application is installed) or
            ``django.contrib.sites.models.RequestSite`` (if
            not). Consult the documentation for the Django sites
            framework for details regarding these objects' interfaces.

        """
        if site is None:
            site = get_current_site(None)
示例#6
0
    def save(self, domain_override=None,
             subject_template_name='registration/password_reset_subject.txt',
             email_template_name='registration/password_reset_email.html',
             use_https=False, token_generator=default_token_generator,
             from_email=None, request=None):
        """
        Generates a one-use only link for resetting password and sends to the
        user.

        """
        UserModel = get_user_model()
        email = self.cleaned_data["email"]
        active_users = UserModel._default_manager.filter(
            email__iexact=email, is_active=True)

        PROTOCOL = 'https' if use_https else 'http'
        if not domain_override:
            current_site = get_current_site(request)
            SITE_NAME = current_site.name
            SITE_DOMAIN = current_site.domain
        else:
            SITE_NAME = SITE_DOMAIN = domain_override

        for user in active_users:
            # Do allow senfing of emails to a users that actually have a password
            # marked as unusable. (differs from django's PasswordResetForm)

            # create_notice_body(
            #     'registration.password_reset',
            #     user,
            #     uid=urlsafe_base64_encode(force_bytes(user.pk)),
            #     token=token_generator.make_token(user),
            #     PROTOCOL=PROTOCOL,
            #     SITE_NAME=SITE_NAME,
            #     SITE_DOMAIN=SITE_DOMAIN,
            # ).post_to(user)
            pass
示例#7
0
def activate(request, backend,
             template_name='registration/activate.html',
             success_url=None, extra_context=None,
             is_admin_site=False,
             token_generator=default_token_generator,
             **kwargs):
    """
    Activate a user's account.

    The actual activation of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    the backend's ``activate()`` method will be called, passing any
    keyword arguments captured from the URL, and will be assumed to
    return a ``User`` if activation was successful, or a value which
    evaluates to ``False`` in boolean context if not.

    Upon successful activation, the backend's
    ``post_activation_redirect()`` method will be called, passing the
    ``HttpRequest`` and the activated ``User`` to determine the URL to
    redirect the user to. To override this, pass the argument
    ``success_url`` (see below).

    On unsuccessful activation, will render the template
    ``registration/activate.html`` to display an error message; to
    override thise, pass the argument ``template_name`` (see below).

    **Arguments**

    ``backend``
        The dotted Python import path to the backend class to
        use. Required.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context. Optional.

    ``success_url``
        The name of a URL pattern to redirect to on successful
        acivation. This is optional; if not specified, this will be
        obtained by calling the backend's
        ``post_activation_redirect()`` method.

    ``template_name``
        A custom template to use. This is optional; if not specified,
        this will default to ``registration/activate.html``.

    ``\*\*kwargs``
        Any keyword arguments captured from the URL, such as an
        activation key, which will be passed to the backend's
        ``activate()`` method.

    **Context:**

    The context will be populated from the keyword arguments captured
    in the URL, and any extra variables supplied in the
    ``extra_context`` argument (see above).

    **Template:**

    registration/activate.html or ``template_name`` keyword argument.

    """
    backend = get_backend(backend)
    account = backend.activate(request, **kwargs)

    if account:
        if not account.has_usable_password() and account.email:
            account.password = User.objects.make_random_password()
            account.save()

            uid = urlsafe_base64_encode(force_bytes(account.pk))
            token = token_generator.make_token(account)
            protocol = 'https' if request.is_secure() else 'http'

            if is_admin_site:
                domain = request.get_host()
            else:
                current_site = get_current_site(request)
                domain = current_site.domain

            return HttpResponseRedirect("{protocol}://{domain}{url}".format(
                protocol=protocol,
                domain=domain,
                url=reverse('password_reset_confirm', kwargs=dict(uidb64=uid, token=token)),
            ))

        if success_url is None:
            to, args, kwargs = backend.post_activation_redirect(
                request, account)
            return redirect(to, *args, **kwargs)
        else:
            return redirect(success_url)

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              kwargs,
                              context_instance=context)
示例#8
0
def page(context):
    request = context['request']
    if not request.user.has_perm('can_edit_site', get_current_site(None)):
        return None
    return [0]