coding utf-8 from django contrib contenttypes models import ContentTyp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# -*- coding: utf-8
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
import flash
import variables
class Permissions(object):
def __init__(self, model, field=None, delete=None, edit=None, create=None, owner_field='user'):
self.model = model
self.field = field
self.delete = delete
self.edit = edit
self.create = create
self.owner_field = owner_field
self.content_type = ContentType.objects.get_for_model(self.model)
self.activation = getattr(variables, "ACTIVATION", None)
self.notice_handler = getattr(variables, "NOTICE_HANDLER")
self.error_handler = getattr(variables, "ERROR_HANDLER")
def __call__(self, func):
self.func = func
return self.decorate
def decorate(self, request, *args, **kwargs):
self.request = request
self.args = args
self.kwargs = kwargs
self.is_authorized()
self.is_banned()
self.is_moderator()
if self.create:
return self._create()
self.obj = get_object_or_404(self.model, **{self.field: self.args[0]})
if self.delete:
return self._delete()
if self.edit:
return self._edit()
return self.func(self.request, *self.args, **self.kwargs)
def _redirect_url(self):
#redirect_url = self.request.META['HTTP_REFERER']
#if referer == self.request.path:
redirect_url = "/"
return redirect_url
def is_authorized(self):
if self.activation and not self.request.user.is_active:
self.error_handler(u"Please activate your account")
return HttpResponseRedirect(self._redirect_url())
if not self.request.user.is_authenticated():
self.error_handler(u"Please authorize")
return HttpResponseRedirect(self._redirect_url())
def is_banned(self):
if self.content_type in self.request.user.ban.sections.all():
self.error_handler(u"You are banned from this section")
return HttpResponseRedirect(self._redirect_url())
def is_moderator(self):
if self.content_type in self.request.user.moderator.sections.all():
return self.func(self.request, *self.args, **self.kwargs)
def _create(self):
return self.func(self.request, *self.args, **self.kwargs)
def _delete(self):
if getattr(self.obj, self.owner_field) == self.request.user:
return self.func(self.request, *self.args, **self.kwargs)
self.notice_handler(u"You can't delete others records")
return HttpResponseRedirect(self._redirect_url())
def _edit(self):
if getattr(self.obj, self.owner_field) == self.request.user:
return self.func(self.request, *self.args, **self.kwargs)
self.notice_handler(u"You can't edit others records")
return HttpResponseRedirect(self._redirect_url())