Example #1
0
    def activate(request, activation_key):
      '''This view displays the account activation page.

      **Required arguments**

      ``activation_key``
        The activation key to validate and use for activating the user.
        User gets it with his account activation email.

      **Templates**

      `"authentication/register/activate_done.html"`
        Template rendered if an account was activated.

        **Context**

          ``form``
            An :class:`django.contrib.auth.forms.AuthenticationForm`
            displayed so that a user can immediately login.

      `"authentication/register/activate_error.html"`
        Template rendered if an account was not activated.

        **Context**: none.
      '''
      from registration.models import RegistrationProfile

      activation_key = activation_key.lower() # Normalize before trying anything with it.
      user = RegistrationProfile.objects.activate_user(activation_key)
      if not user:
        return render_to_response2(request, 'authentication/register/activate_error.html')
      else:
        from django.contrib.auth.forms import AuthenticationForm
        form = AuthenticationForm(initial={'username': user.username})
        return render_to_response2(request, 'authentication/register/activate_done.html', {'form': form})
Example #2
0
def render(request):
  if request.method == 'POST':
    form = None
    source = None

    form_input = MarkupInputForm(request.POST)
    form_upload = MarkupUploadForm(request.POST, request.FILES)

    if form_input.is_valid():
      form = form_input
      source = form_input.cleaned_data['source']
    elif form_upload.is_valid():
      form = form_upload
      source = request.FILES['file'].read()

    if form is not None:
      template_name = None
      if form.is_markdown():
        template_name = 'markup/result-markdown.html'
      elif form.is_textile():
        template_name = 'markup/result-textile.html'
      elif form.is_restructuredtext():
        template_name = 'markup/result-restructuredtext.html'

      response = render_to_response2(request, template_name, {'source': source})
      response.set_cookie(COOKIE_DEFAULT_MARKUP_TYPE, form.cleaned_data['markup_type'])
      return response

  else:
    initial = {}
    markup_type = request.COOKIES.get(COOKIE_DEFAULT_MARKUP_TYPE, '')
    if markup_type in MarkupForm.MARKUP_TYPES:
      initial['markup_type'] = markup_type
    form_input = MarkupInputForm(initial=initial)
    form_upload = MarkupUploadForm(initial=initial)

  return render_to_response2(request, 'markup/source.html', {
    'form_input': form_input,
    'form_upload': form_upload,
  })
Example #3
0
  def profile(request):
    '''The profile page containing

    * password change form;
    * forms to associate and dissociate OpenID's;
    * a button to delete account.

    **Authentication restrictions**

    If a user that is not logged in tries to visit this page, he will
    be redirected to the login page. If he successfully logs in there,
    he'll be redirected back here.

    **Templates**

    `"authentication/profile/profile.html"`
      Page template.

      **Context**

      ``form_change_password``
        A :class:`django.contrib.auth.forms.SetPasswordForm`.
      ``form_add_openid_msg``
        Form errors for ``form_add_openid`` (see below).
      ``form_add_openid``
        An :class:`django_authopenid.forms.AssociateOpenID`.
      ``form_delete_openid``
        An :class:`authentication.forms.DeleteOpenidForm`.
      ``form_delete``
        An :class:`authentication.forms.DeleteAccountForm`.

    `"authentication/profile/password_changed.html"`
      Templates rendered after the change password form was submitted and user's
      password was successfull changed.

      **Context**

      ``next``
        The link for previous page tracking or ``''`` if it is unknown
        (i.e., was not passed);
    '''
    from django.contrib.auth.forms import SetPasswordForm
    from django_authopenid.forms import AssociateOpenID
    from forms import DeleteOpenidForm, DeleteAccountForm

    redirect_to = next = request.GET.get('next')
    if not redirect_to or '://' in redirect_to:
      redirect_to = settings.LOGIN_REDIRECT_URL
      next = ''

    form_change_password = SetPasswordForm(request.user)
    form_add_openid_msg = ''
    form_add_openid = AssociateOpenID(request.user)
    form_delete_openid = DeleteOpenidForm.new(request.user)
    form_delete = DeleteAccountForm()
    if request.method == 'POST':
      if 'new_password1' in request.POST.keys():
        form_change_password = SetPasswordForm(request.user, request.POST)
        if form_change_password.is_valid():
          request.user.set_password(form_change_password.cleaned_data['new_password1'])
          request.user.save()
          return render_to_response2(request, 'authentication/profile/password_changed.html', {'next': next})
      elif 'openid_url' in request.POST.keys():
        form_add_openid = AssociateOpenID(request.user, request.POST)
        if form_add_openid.is_valid():
          openid_url = form_add_openid.cleaned_data['openid_url']
          redirect_url = "%s?%s" % (
            request.build_absolute_uri(request.path),
            urllib.urlencode({'next': redirect_to, 'openid_url': openid_url})
          )
          try:
            return Overrides.Authopenid.ask_openid(request, openid_url, redirect_url)
          except Overrides.Authopenid.OpenidError, e:
            form_add_openid_msg = unicode(e)

      elif 'openid_url_to_delete' in request.POST.keys():
        form_delete_openid = DeleteOpenidForm.process(request.user, request.POST)
      else:
        form_delete = DeleteAccountForm(request.POST)
        if form_delete.is_valid():
          request.user.delete()
          auth.logout(request)
          return HttpResponseRedirect(redirect_to)
Example #4
0
  def forget_password(request, activation_key):
    '''Login a user if a valid activation key is passed.

    **Required arguments**

    ``activation_key``
      The activation key taken by the user from a forget-password email.

    **Templates**

    `"authentication/login/forget_password/activate.html"`
      Page template.

      **Context**

        ``key_invalid``
          Set to ``True`` if the supplied key is invalid (expired, etc.),
          otherwise set to ``False``.
        ``account_disabled``
          Set to ``True`` if the account user tries to login to with this
          activation key is disabled, otherwise set to ``False``. Do not
          check this variable if ``key_invalid`` is ``True``.
        ``user``
          If the user successfully logged in, this variable is set to the
          :class:`~django.contrib.auth.models.User` object corresponding to the
          user. If ``key_invalid`` or ``account_disabled`` is ``True``, this
          variable is set to ``None``.
    '''
    key_invalid = False
    account_disabled = False
    user = None

    activation_key = activation_key.lower() # Normalize before trying anything with it.
    user = LoginEmail.objects.activate(activation_key)
    if user is None:
      key_invalid = True
    else:

      if not user.is_active:
        account_disabled = True
      else:
          #
          # We **must** authenticate the user before calling ``login`` (see
          # `Calling authenticate() first <http://docs.djangoproject.com/en/dev/topics/auth/#how-to-log-a-user-in>`__
          # note in Django documentation).
          #
          # As the standard authentication backend always takes user's password
          # and we (and the user itself) do not know it, the only way to log
          # the user in is to write our own unsafe authentication backend
          # that considers an username to be enough.
          #
          #
          # **NOTE**: The user object returned can be not exactly equal to the
          # "previous" object we got from ``LoginEmail.object.activate``.
          # Actually, Django adds ``backend`` attribute on the object, so
          # calling ``login`` with the "previous" object will lead to an error.
          #
        user = auth.authenticate(username=user.username)
        auth.login(request, user)

    return render_to_response2(request, 'authentication/login/forget_password/activate.html', {
      'key_invalid': key_invalid,
      'account_disabled': account_disabled,
      'user': user,
    })
Example #5
0
    def register(request):
      '''This view displays the registration page.

      **Templates**

      `"authentication/register/register.html"`
        Template of the page.

        **Context**

        ``form``
          An :class:`authentication.forms.RegistrationForm`.

      `"authentication/register/email_*.txt"`
        Templates for subject and body of account activation emails.

        **Context**

        ``username``
          Username.
        ``sitename``
          Site name (set in admin).
        ``activation_key``
          Activation key.
        ``expiry_date``
          Activation key expiry date.

      `"authentication/register/email_*.html"`
        Templates of pages displayed after an account activation email was sent
        or if an error occured during it.

        **Context**

        ``next``
          The link for previous page tracking or ``''`` if it is unknown
          (i.e., was not passed);
        ``error``
          (only for `"authentication/register/email_error.html"` template)
          description of the error occured.
      '''
      from registration.models import RegistrationProfile
      from registration.views import register as registration_register
      from forms import RegistrationForm

      form_class = RegistrationForm
      template_name = 'authentication/register/register.html'

      redirect_to = next = request.GET.get('next')
      if not redirect_to or '://' in redirect_to:
        redirect_to = settings.LOGIN_REDIRECT_URL
        next = ''

      if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
          user = form.save()

          # Send email

          activation_key = RegistrationProfile.objects.get(user=user).activation_key
          expiry_date = datetime.date.today() + datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS-1)

          templatename = 'email_sent'
          context = {'next': next}
          try:
            send_mail(user, request,
              subject_template='authentication/register/email_subject.txt',
              message_template='authentication/register/email.txt',
              context={
                'username': user.username,
                'sitename': Site.objects.get_current().name,
                'activation_key': activation_key,
                'expiry_date': expiry_date,
              })
          except NoEmailException, e:
            # This must never occur
            raise e
          except SMTPException, e:
            templatename = 'email_error'
            context['error'] = unicode(e)

          templatename = 'authentication/register/' + templatename + '.html'
          return render_to_response2(request, templatename, context)
Example #6
0
    def login(request):
      '''Replacement for :meth:`django_authopenid.views.signin` written
      to supply the ``forget-password`` form to the template.

      This view displays the login page containing

      * OpenID login form;
      * traditional login form;
      * forget-password form;
      * a link to the registration page.

      **Templates**

      `"authentication/login/login.html"`
        Template of the login page.

        **Context**

        ``msg``
          Form errors for ``form1`` (see below).
        ``form1``
          An :class:`authentication.forms.OpenidLoginForm`.
        ``form2``
          An :class:`django.contrib.auth.forms.AuthenticationForm`.
        ``form_forget_password``
          An :class:`authentication.forms.RegisteredUserForm` to enter username.
        ``next``
          The link for previous page tracking or ``""`` if it is unknown
          (i.e., was not passed).

      `"authentication/login/forget_password/email_*.txt"`
        Templates for subject and body of forget-password emails.

        **Context**

        ``username``
          Username.
        ``sitename``
          Site name (set in admin).
        ``activation_key``
          Activation key.
        ``expiry_date``
          Activation key expiry date.

      `"authentication/login/forget_password/email_*.html"`
        Templates of pages displayed after a login email was sent or
        if an error occured during it.

        **Context**

        ``next``
          The link for previous page tracking or ``''`` if it is unknown
          (i.e., was not passed);
        ``error``
          (only for `"authentication/login/forget_password/email_error.html"` template)
          description of the error occured.
      '''
      from django.contrib.auth.forms import AuthenticationForm
      from forms import OpenidLoginForm, RegisteredUserForm

      template_name = 'authentication/login/login.html'
      openid_form = OpenidLoginForm
      auth_form = AuthenticationForm

      redirect_to = next = request.GET.get('next')
      if not redirect_to or '://' in redirect_to:
        redirect_to = settings.LOGIN_REDIRECT_URL
        next = ''

      form1_msg = ''
      form1 = openid_form()
      form2 = auth_form()
      form_forget_password = RegisteredUserForm()
      if request.POST:

        if 'openid_url' in request.POST.keys():
          form1 = openid_form(data=request.POST)
          if form1.is_valid():
            openid_url = form1.cleaned_data['openid_url']
            #
            # Unfortunately, Django does not provide a way to assign form
            # errors here. That's why we have to pass errors from OpenID
            # processing to separate ``msg`` template context variable.
            #
            # Another solution would be to move the calls below
            # to the ``clean`` method of the class ``form1`` belongs to.
            # The calls are not related to form processing at all, so
            # this solution is even more ugly. Also, it would require
            # much of monkey patching inside :mod:`django_authopenid`.
            #
            redirect_url = "%s?%s" % (
                #
                # Here we send ``openid_url`` GET parameter in order
                # to be able to restore ``openid_url`` form field value
                # if an error occurs and we'll render the same forms again.
                #
                # As we pass URL of this page to OpenID provider as
                # ``complete_url`` (see ``ask_openid`` call below), we will
                # get in this view function again after the user confirms his
                # identity on his OpenID provider's page. In order to know
                # whether to check GET parameters the provider sent back to us,
                # we must know whether we get to this view function at user's
                # will or from an OpenID provider. This is the second purpose
                # of the ``openid_url`` GET parameter: if it is present,
                # we got from a provider.
                #
              request.build_absolute_uri(request.path),
              urllib.urlencode({'next': redirect_to, 'openid_url': openid_url})
            )
            try:
              return Overrides.Authopenid.ask_openid(request, openid_url, redirect_url)
            except Overrides.Authopenid.OpenidError, e:
              form1_msg = unicode(e)

        elif 'password' in request.POST.keys():
          # perform normal Django authentification
          form2 = auth_form(data=request.POST)
          if form2.is_valid():
            auth.login(request, form2.get_user())
            if request.session.test_cookie_worked():
              request.session.delete_test_cookie()
            return HttpResponseRedirect(redirect_to)

        else:
          # forget password
          form_forget_password = RegisteredUserForm(request.POST)
          if form_forget_password.is_valid():
            user = form_forget_password.user()
            email = LoginEmail.objects.create_email(user)

            templatename = 'email_sent'
            context = {'next': next}
            try:
              send_mail(user, request,
                subject_template='authentication/login/forget_password/email_subject.txt',
                message_template='authentication/login/forget_password/email.txt',
                context=email.prepare_send())
            except NoEmailException:
              templatename = 'email_none'
            except SMTPException, e:
              templatename = 'email_error'
              context['error'] = unicode(e)
            templatename = 'authentication/login/forget_password/' + templatename + '.html'
            return render_to_response2(request, templatename, context)
Example #7
0
              urllib.urlencode({ 'next': next }),
            ))
          else:
            user = rel.user
            if user.is_active:
              user = auth.authenticate(username=user.username)
              auth.login(request, user)
              return HttpResponseRedirect(redirect_to)
            else:
              form1_msg = _('This account is disabled.')
              form1 = openid_form(initial={'openid_url': openid.openid})

      return render_to_response2(request, template_name, {
        'msg': form1_msg,
        'form1': form1,
        'form2': form2,
        'form_forget_password': form_forget_password,
        'next': redirect_to,
      })

  class Registration:
    '''Modified view functions from :mod:`django-registration`.'''

      #
      # Replacement for ``registration.views.register``.
      #
      # Use custom form instead of ``registration.forms.RegistrationForm`` and
      # send email manually, as I consider indication of expiration date
      # more convenient than indication of amount of activation days.
      # We can't do such arithmetic directly in the template, and
      # writing a template tag for this is ugly.