[Django] 日本ひげ男協会のサイトを作成する。その8

注意

この記事は、id:SumiTomohiko:20070127:1169916076の続きです。

環境

この記事の内容は、Ubuntu 6.10, Python 2.4, Django 0.95で確認しました。

アクセス制限

前回作成した編集画面は、URLを直に指定すれば、誰でもアクセスできるようになっています。これはセキュリティ上問題なので、本人にしか編集できないようにします。

その実現方法として、デコレータを使用します。日本ひげ男協会のサイトではDjangoの認証システムは使用していませんが、Djangoの認証システムにもデコレータによるアクセス制限があり、これはdjango.contrib.auth.decorators.user_passes_testで以下のように実装されています。

def user_passes_test(test_func, login_url=LOGIN_URL):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """
    def _dec(view_func):
        def _checklogin(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            return HttpResponseRedirect('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path())))
        _checklogin.__doc__ = view_func.__doc__
        _checklogin.__dict__ = view_func.__dict__

        return _checklogin
    return _dec

今回は、これを真似して作ってみました。user/decorators.pyを、以下のように作成しました。

import django.http
import juma.user.http
import juma.user.settings

def allow_by_user_id():
    def _decorator(function):
        def _new_function(request, id):
            try:
                login_id = request.session[juma.user.settings.USER_ID_KEY]
                if login_id != int(id):
                    return juma.user.http.make_forbidden()
            except KeyError, ValueError:
                return juma.user.http.make_forbidden()

            return function(request, id)

        return _new_function

    return _decorator

# vim: tabstop=4 shiftwidth=4 expandtab

アクセス制限をする関数の方は、(importを除いて)ただ1行追加するだけです。

@juma.user.decorators.allow_by_user_id()
def edit(request, id):
(略)

これで、他人の編集画面を開こうとすると、"Forbidden"と表示されるようになりました。