Beispiel #1
0
def login_page(request):
    """The login view. Served from index()
    """
    User = get_user_model()

    next_page = request.GET.get('next', '/')
    c = {}
    
    if request.method == 'POST':
        form = LogInForm(request.POST)
        if form.is_valid:
            email = request.POST['email']
            p = request.POST['password']

            # We can't actually authenticate with an email address. So, we have
            # to query the User models by email address to find a username,
            # and once we have that we can use the username to log in.
            try:
                user = User.objects.get(email__iexact=email)
            except User.DoesNotExist:
                form = LogInForm()
                form.cleaned_data = {}

                form.add_error('email', "Your login information does not match our records. Try again or click 'I forgot my password' below.")
                c = dict(next=quote(next_page), form=form)
                return render(request, 'accounts/login.html', c)

            user = authenticate(username=user.username, password=p)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect(next_page)
                else:
                    form = LogInForm()
                    form.cleaned_data = {}

                    form.add_error('email', "Your email address is incorrect")
                    form.add_error('password', "Your password is incorrect")
                    c = dict(next=quote(next_page), form=form)
                    return render(request, 'accounts/login.html', c)
            else:
                form = LogInForm()
                form.cleaned_data = {}

                form.add_error('email', "Your login information does not match our records. Try again or click 'I forgot my password' below.")
                c = dict(next=quote(next_page), form=form)
                return render(request, 'accounts/login.html', c)
        else:
            form = LogInForm()
            form.cleaned_data = {}

            form.add_error('email', "Please try again")
            c = dict(next=quote(next_page), form=form)
            return render(request, 'accounts/login.html', c)
    else:
        form = LogInForm()

    # TODO: Fix the else staircase, refactor this as a FormView

    # c = dict(GPLUS_ID=settings.SOCIAL_AUTH_GOOGLE_PLUS_KEY,
    #          GPLUS_SCOPE=' '.join(settings.SOCIAL_AUTH_GOOGLE_PLUS_SCOPES),
    c = dict(next=quote(next_page), form=form)
    
    return render(request, 'accounts/login.html', c)