Source

django-publicauth / openauth / views.py

Full commit
import time
from datetime import datetime, timedelta, date

from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.contrib import auth 
from django.shortcuts import get_object_or_404, redirect
from django.utils.translation import ugettext as _
from django.http import HttpResponseRedirect
from django.db.models import Q

from annoying.decorators import ajax_request, render_to

import openauth
from openauth.forms import ResetPasswordForm, NewPasswordForm, LoginForm, NewEmailForm, EditUserForm
from openauth.utils import email_template, build_redirect_url, str_to_class, \
    generate_hash, activation_required, message
from openauth.models import Confirmation


@render_to()
def confirm(request):
    """
    Check confirmation key, proccess confirmation and delete key.
    """
    key = request.GET.get("key")
    try:
        confirmation_type = int(request.GET.get("type", 1))
    except ValueError:
        return message(request, _("Confirmation error: incorrect type"), "error", "/")
    confirmation = get_object_or_404(Confirmation, key=key, confirmation_type=confirmation_type)
    if confirmation_type == openauth.settings.ACTIVATION_CONFIRMATION_TYPE:
        user = confirmation.user
        user.is_active = True
        user.save()
        if openauth.settings.ACTIVATION_AUTO_LOGIN:
            confirmation.user.backend = 'django.contrib.auth.backends.ModelBackend'
            auth.login(request, user)

        confirmation.delete()
        return message(request, _('Your account successfully activated'), 'success', 'openauth-show-user', args=[user.id])
    elif confirmation_type == openauth.settings.PASSWORD_RESET_CONFIRMATION_TYPE:
        confirmation.user.backend = 'django.contrib.auth.backends.ModelBackend'
        auth.login(request, confirmation.user)      
        confirmation.delete()
        return message(request, _("Now you can change your password"), "notice", "openauth-change-password")
    else:
        return openauth.settings.CUSTOM_CONFIRMATION(request)


@render_to('openauth/registration.html')
def registration(request):
    """
    Only anonymous users can view this page
    Registration should be allowed in REGISTRATION_ALLOWED setting
    """
    if request.user.is_authenticated():
            return message(request, _('You have to logout before registration'), 'notice', '/')
    if not openauth.settings.REGISTRATION_ALLOWED:
        request.flash['notice'] = _('Sorry. Registration is disabled.')
        return message(request, _('We are sorry, but registration is disabled. Come back later'), 'notice', '/')
    if request.POST:
        form = str_to_class(openauth.settings.REGISTRATION_FORM)(request.POST)
        if form.is_valid():
            user = form.save()
            if openauth.settings.ACTIVATION_REQUIRED:
                user.is_active = False
            user.save()

            if openauth.settings.ACTIVATION_REQUIRED:
                confirmation = Confirmation(user=user, key=generate_hash(), confirmation_type=openauth.settings.ACTIVATION_CONFIRMATION_TYPE)
                confirmation.save()
                url = request.build_absolute_uri(reverse('openauth-confirm'))
                url += '?key=%s&type=%s' % (confirmation.key, confirmation.confirmation_type)
                params = {'domain': request.get_host(), 'email': user.email, 'url': url}
                if email_template(user.email, 'openauth/mail/registration.txt', **params):
                    return message(request, _("You have successfully registered. Check your inbox for email with activation link."), "success", "/")
                else:
                    user.delete()
                    return message(request, _('The error was occuried while sending email with activation code. Account was not created. Please, try later.'), "error", "/")
            else:
                return message(request, _("You have successfully registered. You can login now"), "success", "login")

    else:
        form = str_to_class(openauth.settings.REGISTRATION_FORM)()
    return {'form': form}


@render_to('openauth/reset_password.html')
def reset_password(request):
    if request.POST:
        form = ResetPasswordForm(request.POST)
        if form.is_valid():
            user = User.objects.get(email=form.cleaned_data['email'].lower())
            confirmation = Confirmation(user=user, key=generate_hash(), confirmation_type=openauth.settings.PASSWORD_RESET_CONFIRMATION_TYPE)
            confirmation.save()
            url = request.build_absolute_uri(reverse('openauth-confirm'))
            url += '?key=%s&type=%s' % (confirmation.key, openauth.settings.PASSWORD_RESET_CONFIRMATION_TYPE)
            args = {'domain': request.get_host(), 'url': url}
            if email_template(user.email, 'openauth/mail/reset_password.txt', **args):
                return message(request, _('Check your email please'), 'notice', '/')
            else:
                return message(request, _('Unfortunately we could not send you email in current time. Please, try later'), 'error', '/')
    else:
        form = ResetPasswordForm()
    return {'form': form}


@render_to('openauth/login.html')
def login(request):
    #TODO correct next url redirect
    if request.user.is_authenticated():
        return message(request, _('You are already authenticated'), 'notice', '/')
    if request.POST:
        form = LoginForm(request, request.POST)
        request.session['login_redirect_url'] = request.GET.get('next')
        if form.is_valid():
            redirect_url = build_redirect_url(request, openauth.settings.LOGIN_REDIRECT_URL)
            return message(request, _('You have successfully logged-in'), 'success', redirect_url)
    else:
        form = LoginForm(request=request)
    return {'form': form}


@activation_required
@render_to('openauth/change_password.html')
def change_password(request):
    if request.POST:
        form = NewPasswordForm(request.POST)
    else:
        form = NewPasswordForm()

    if form.is_valid():
        form.save(request.user)
        return message(request, _('Password was changed'), 'success', 'openauth-show-user', [request.user.id])
    return {'form': form}


@render_to('account/message.html')
def logout(request):
    auth.logout(request)
    request.flash['notice'] = "You have been logged out"
    return redirect("index")


@render_to('account/edit_user.html')
def edit_user(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    if not request.user.is_authenticated() or user != request.user and not request.user.is_staff:
        return HttpResponseReload(request)
    if request.POST:
        form = EditUserForm(user, request.POST, request.FILES)
        if form.is_valid():
            form.save()
            request.flash['notice'] = "User details successfully changed"
            return HttpResponseRedirect(reverse('openauth-show-user', args=[user.id]))
    else:
        initial = {'username': user.username, 
                    'country': user.profile.country,
                    'jabber': user.profile.jabber,
                    'about': user.profile.about}
        form = EditUserForm(user, initial=initial)
    return {'form': form, 'user': user}


@render_to('openauth/profile.html')
def show_user(request, user_id):
    """
    Show user profile 
    """

    user = get_object_or_404(User, pk=user_id)
    return {'user': user}


@render_to('openauth/users.html')
def users(request):
    users = User.objects.filter(is_active=True).all()
    return {'users': users}