Django : Site Scaffold : djsite : CAPTCHA support for standard login

 

django-registrationでユーザー登録とログインはできているとします。

hdknr@LennyOne:~/django/djsite$ svn checkout http://django-simple-captcha.googlecode.com/svn/trunk/captcha
A    captcha/tests
A    captcha/tests/views.py
A    captcha/tests/__init__.py
A    captcha/tests/urls.py
A    captcha/views.py
A    captcha/conf
A    captcha/conf/__init__.py
A    captcha/conf/settings.py
A    captcha/__init__.py
A    captcha/fonts
A    captcha/fonts/etl14-unicode.pil
A    captcha/fonts/etl24-unicode.pil
A    captcha/fonts/etl16-unicode.pil
A    captcha/fonts/etl14-unicode.bdf
A    captcha/fonts/etl24-unicode.bdf
A    captcha/fonts/etl16-unicode.bdf
A    captcha/fonts/etl14-unicode.pbm
A    captcha/fonts/etl24-unicode.pbm
A    captcha/fonts/etl16-unicode.pbm
A    captcha/fonts/etl-unicode.tar.gz
A    captcha/helpers.py
A    captcha/models.py
A    captcha/urls.py
A    captcha/fields.py
リビジョン 27 をチェックアウトしました。

hdknr@LennyOne:~/django/djsite$ vi settings.py

hdknr@LennyOne:~/django/djsite$ grep HDKNR settings.py
INSTALLED_APPS = (              # HDKNR
    ‘captcha’,                  # HDKNR

hdknr@LennyOne:~/django/djsite$ python manage.py syncdb
Creating table captcha_captchastore

hdknr@LennyOne:~/django/djsite$ vi urls.py

hdknr@LennyOne:~/django/djsite$ grep HDKNR urls.py
urlpatterns = patterns(”,                                                      # HDKNR
    (r’^captcha/’, include(‘captcha.urls’)),                                    # HDKNR

hdknr@LennyOne:~/django/djsite$ python manage.py startapp login

django/contrib/auth/forms.py をコピーしlogin/forms.pyをつくる

hdknr@LennyOne:~/django/djsite$ vi login/forms.py

from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import authenticate
from django import forms                                # CAPTCHA
from captcha.fields import CaptchaField                 # CAPTCHA
class AuthenticationForm(forms.Form):
    username = forms.CharField(label=_("Username"), max_length=30)
    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
    captcha = CaptchaField()                                                            #CAPTCHA
    def __init__(self, request=None, *args, **kwargs):
        self.request = request
        self.user_cache = None
        super(AuthenticationForm, self).__init__(*args, **kwargs)
    def clean(self):
        username = self.cleaned_data.get(‘username’)
        password = self.cleaned_data.get(‘password’)
        if username and password:
            self.user_cache = authenticate(username=username, password=password)
            if self.user_cache is None:
                raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
            elif not self.user_cache.is_active:
                raise forms.ValidationError(_("This account is inactive."))
        # TODO: determine whether this should move to its own method.
        if self.request:
            if not self.request.session.test_cookie_worked():
                raise forms.ValidationError(_("Your Web browser doesn’t appear to have cookies enabled. Cookies are required for logging in."))
        return self.cleaned_data
    def get_user_id(self):
        if self.user_cache:
            return self.user_cache.id
        return None
    def get_user(self):
        return self.user_cache

django/contrib/auth/views.py をコピーしlogin/views.pyをつくる

hdknr@LennyOne:~/django/djsite$ vi login/views.py

# Create your views here.
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.views.decorators.cache import never_cache
from django.contrib.sites.models import Site, RequestSite
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, Http404
from login.forms import AuthenticationForm      #CAPTCHA
def login(request, template_name=’registration/login.html’, redirect_field_name=REDIRECT_FIELD_NAME):
    "Displays the login form and handles the login action."
    redirect_to = request.REQUEST.get(redirect_field_name, ”)
    if request.method == "POST":
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            # Light security check — make sure redirect_to isn’t garbage.
            if not redirect_to or ‘//’ in redirect_to or ‘ ‘ in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            from django.contrib.auth import login
            login(request, form.get_user())
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            return HttpResponseRedirect(redirect_to)
    else:
        form = AuthenticationForm(request)
    request.session.set_test_cookie()
    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)
    return render_to_response(template_name, {
        ‘form’: form,
        redirect_field_name: redirect_to,
        ‘site_name’: current_site.name,
    }, context_instance=RequestContext(request))
login = never_cache(login)

registration/urls.py でhttp://hdknr.deb:9000/accounts/login/  にきたらlogin.views.login に処理をルートさせる。

hdknr@LennyOne:~/django/djsite$ vi registration/urls.py

hdknr@LennyOne:~/django/djsite$ grep HDKNR registration/urls.py
from login import views as login_views                                          #HDKNR CAPTCHA
urlpatterns = patterns(”,                                                      #HDKNR CAPTCHA
                       url(r’^login/$’,                                         #HDKNR CAPTCHA
                           login_views.login,                                   #HDKNR CAPTCHA
                           {’template_name’: ‘registration/login.html’},        #HDKNR CAPTCHA
                           name=’auth_login’),                                  #HDKNR CAPTCHA

実行。

hdknr@LennyOne:~/django/djsite$ python manage.py runserver 0.0.0.0:9000
Validating models…
0 errors found
Django version 1.0.2 final, using settings ‘djsite.settings’
Development server is running at http://0.0.0.0:9000/
Quit the server with CONTROL-C.
[30/Jun/2009 16:10:37] "GET /accounts/login/ HTTP/1.1" 200 1359
[30/Jun/2009 16:10:37] "GET /captcha/image/38967425497873b016adb2143916171721a15be0/ HTTP/1.1" 200 3872
[30/Jun/2009 16:11:05] "POST /accounts/login/ HTTP/1.1" 200 1585
[30/Jun/2009 16:11:05] "GET /captcha/image/9b6dc7833dbf75f37103cbc59e843f8774b715a8/ HTTP/1.1" 200 3788
[30/Jun/2009 16:11:22] "POST /accounts/login/ HTTP/1.1" 200 1533
[30/Jun/2009 16:11:22] "GET /captcha/image/7080772deac1f9623c8f002cd92bcf588a8d8ac3/ HTTP/1.1" 200 3641
[30/Jun/2009 16:11:35] "POST /accounts/login/ HTTP/1.1" 302 0
[30/Jun/2009 16:11:35] "GET / HTTP/1.1" 200 28

WS000009

WS000010

WS000011

WS000011[1]

WS000012

カテゴリー: 未分類 パーマリンク

コメントを残す

以下に詳細を記入するか、アイコンをクリックしてログインしてください。

WordPress.com ロゴ

WordPress.com アカウントを使ってコメントしています。 ログアウト / 変更 )

Twitter 画像

Twitter アカウントを使ってコメントしています。 ログアウト / 変更 )

Facebook の写真

Facebook アカウントを使ってコメントしています。 ログアウト / 変更 )

Google+ フォト

Google+ アカウントを使ってコメントしています。 ログアウト / 変更 )

%s と連携中