# -*- coding: utf-8 -*-
'''
Created on 2010/05/01

@author: katsuhiro Inagaki
'''
from django.utils.safestring import mark_safe

from djanction.item.models import Item
from djanction.appauth import ITEM_KEY_FIELD_NAME
from djanction.appauth import USER_KEY_FIELD_NAME

_ERROR_MSG = mark_safe('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><body><h1>403 Forbidden</h1><p>Permission Denied.</p></body></html>')

# this method needs function has 'user_id' dict arg
def self_page_required(function=None):
    def wrapper(request, *args, **kwargs):
        # precondition: user must be authenticated
        assert request.user.is_authenticated()
        if kwargs.has_key(USER_KEY_FIELD_NAME):
            if kwargs[USER_KEY_FIELD_NAME] == str(request.user.id):
                return function(request, *args, **kwargs)
        else:
            if args[0] == str(request.user.id):
                return function(request, *args, **kwargs)
        from django.http import HttpResponseForbidden
        return HttpResponseForbidden(_ERROR_MSG)
    return wrapper


def self_item_required(function=None):
    def wrapper(request, *args, **kwargs):
        # precondition: user must be authenticated
        assert request.user.is_authenticated()
        if kwargs.has_key(ITEM_KEY_FIELD_NAME):
            item_id = kwargs[ITEM_KEY_FIELD_NAME]
        else:
            item_id = args[0]
        item = Item.objects.get(id=item_id)
        if item is not None:
            if item.user.id == request.user.id:
                return function(request, *args, **kwargs)
        from django.http import HttpResponseForbidden
        return HttpResponseForbidden(_ERROR_MSG)
    return wrapper

