summaryrefslogtreecommitdiff
path: root/ishtar_common/models.py
diff options
context:
space:
mode:
authorÉtienne Loks <etienne.loks@iggdrasil.net>2018-11-12 18:33:19 +0100
committerÉtienne Loks <etienne.loks@iggdrasil.net>2018-11-12 18:33:19 +0100
commitfc7c3ae2b3b7042f205c3fa30e869ff66a98bfd9 (patch)
tree98c06a91f3bf17bc02f49d7fc9e67641e9598154 /ishtar_common/models.py
parent5106dc60c2a0a7b9afab95a4c7a0d86c8c6dd908 (diff)
downloadIshtar-fc7c3ae2b3b7042f205c3fa30e869ff66a98bfd9.tar.bz2
Ishtar-fc7c3ae2b3b7042f205c3fa30e869ff66a98bfd9.zip
Sheet: check permissions for qa display
Diffstat (limited to 'ishtar_common/models.py')
-rw-r--r--ishtar_common/models.py175
1 files changed, 97 insertions, 78 deletions
diff --git a/ishtar_common/models.py b/ishtar_common/models.py
index 648280ad2..a1415c8e0 100644
--- a/ishtar_common/models.py
+++ b/ishtar_common/models.py
@@ -133,7 +133,7 @@ class ValueGetter(object):
value_list.append((key, unicode(values[key])))
values['VALUES'] = u'\n'.join(
[u"%s: %s" % (k, v) for k, v in sorted(value_list,
- key=lambda x:x[0])])
+ key=lambda x: x[0])])
for global_var in GlobalVar.objects.all():
values[global_var.slug] = global_var.value or ""
return values
@@ -160,8 +160,8 @@ class HistoricalRecords(BaseHistoricalRecords):
attrs = {}
for field in instance._meta.fields:
attrs[field.attname] = getattr(instance, field.attname)
- q_history = instance.history\
- .filter(history_modifier_id=history_modifier.pk)\
+ q_history = instance.history \
+ .filter(history_modifier_id=history_modifier.pk) \
.order_by('-history_date', '-history_id')
if not q_history.count():
manager.create(history_type=type,
@@ -171,10 +171,10 @@ class HistoricalRecords(BaseHistoricalRecords):
# multiple saving by the same user in a very short time are generaly
# caused by post_save signals it is not relevant to keep them
min_history_date = datetime.datetime.now() \
- - datetime.timedelta(seconds=5)
+ - datetime.timedelta(seconds=5)
q = q_history.filter(history_date__isnull=False,
- history_date__gt=min_history_date)\
- .order_by('-history_date', '-history_id')
+ history_date__gt=min_history_date) \
+ .order_by('-history_date', '-history_id')
if q.count():
return
@@ -194,6 +194,7 @@ def valid_id(cls):
cls.objects.get(pk=value)
except ObjectDoesNotExist:
raise ValidationError(_(u"Not a valid item."))
+
return func
@@ -209,6 +210,7 @@ def valid_ids(cls):
except ObjectDoesNotExist:
raise ValidationError(
_(u"A selected item is not a valid item."))
+
return func
@@ -220,6 +222,7 @@ def is_unique(cls, field):
assert cls.objects.filter(**query).count() == 0
except AssertionError:
raise ValidationError(_(u"This item already exists."))
+
return func
@@ -227,6 +230,7 @@ class OwnPerms(object):
"""
Manage special permissions for object's owner
"""
+
@classmethod
def get_query_owns(cls, ishtaruser):
"""
@@ -234,6 +238,22 @@ class OwnPerms(object):
"""
return None # implement for each object
+ def can_do(self, request, action_name):
+ """
+ Check permission availability for the current object.
+ :param request: request object
+ :param action_name: action name eg: "change_find" - "own" declinaison is
+ checked
+ :return: boolean
+ """
+ splited = action_name.split('_')
+ action_own_name = splited[0] + '_' + '_'.join(splited[1:])
+ return request.user.ishtaruser.has_right(
+ action_name, request.session) or \
+ (request.user.ishtaruser.has_right(
+ action_own_name, request.session)
+ and self.is_own(request.user.ishtaruser))
+
def is_own(self, user):
"""
Check if the current object is owned by the user
@@ -482,7 +502,7 @@ class GeneralType(Cached, models.Model):
return self.label
def natural_key(self):
- return (self.txt_idx, )
+ return (self.txt_idx,)
@property
def explicit_label(self):
@@ -635,7 +655,7 @@ class GeneralType(Cached, models.Model):
if not instances:
keys = ['__get_types']
keys += [u"{}".format(ex) for ex in exclude] + \
- [u"{}".format(default)]
+ [u"{}".format(default)]
keys += [u'{}-{}'.format(unicode(k), dct[k]) for k in dct]
cache_key, value = get_cache(cls, keys)
if value and not force:
@@ -647,8 +667,8 @@ class GeneralType(Cached, models.Model):
base_dct, instances, exclude=exclude,
default=default)
vals = [v for v in cls._get_parent_types(
- base_dct, instances, exclude=exclude,
- default=default)]
+ base_dct, instances, exclude=exclude,
+ default=default)]
cache.set(cache_key, vals, settings.CACHE_TIMEOUT)
return vals
@@ -689,7 +709,7 @@ class GeneralType(Cached, models.Model):
yield item
else:
yield (item.pk, _(unicode(item))
- if item and unicode(item) else '')
+ if item and unicode(item) else '')
@classmethod
def _get_childs_list(cls, dct=None, exclude=None, instances=False):
@@ -779,7 +799,6 @@ class GeneralType(Cached, models.Model):
lst.append(sub_child)
return lst
-
@classmethod
def _get_parent_types(cls, dct={}, instances=False, exclude=[],
default=None):
@@ -1129,7 +1148,7 @@ class JsonData(models.Model):
except ContentType.DoesNotExists:
return sections
fields = list(JsonDataField.objects.filter(
- content_type=content_type, display=True, section__isnull=True
+ content_type=content_type, display=True, section__isnull=True
).all()) # no section fields
fields += list(JsonDataField.objects.filter(
@@ -1378,12 +1397,7 @@ class DocumentItem(object):
if not hasattr(self, 'SLUG'):
return actions
- can_add_doc = request.user.ishtaruser.has_right(
- 'add_document', request.session) or (
- request.user.ishtaruser.has_right(
- 'add_own_document', request.session) and
- self.is_own(request.user.ishtaruser)
- )
+ can_add_doc = self.can_do(request, 'add_document')
if can_add_doc:
actions = [
(
@@ -1485,7 +1499,7 @@ class BaseHistorizedItem(DocumentItem, FullSearch, Imported, JsonData,
except ObjectDoesNotExist:
if strict:
raise HistoryError(u"The class %s has no pk %d" % (
- unicode(field.rel.to), val))
+ unicode(field.rel.to), val))
setattr(item, k, None)
item.pk = self.pk
return item
@@ -1629,8 +1643,8 @@ class GeneralRelationType(GeneralType):
# after saving check that the inverse_relation of the inverse_relation
# point to the saved object
if self.inverse_relation \
- and (not self.inverse_relation.inverse_relation
- or self.inverse_relation.inverse_relation != self):
+ and (not self.inverse_relation.inverse_relation
+ or self.inverse_relation.inverse_relation != self):
self.inverse_relation.inverse_relation = self
self.inverse_relation.symmetrical = False
self.inverse_relation.save()
@@ -1714,6 +1728,7 @@ class QuickAction(object):
"""
Quick action available from tables
"""
+
def __init__(self, url, icon_class='', text='', target=None, rights=None,
module=None):
self.url = url
@@ -2228,8 +2243,8 @@ class UserDashboard:
def __init__(self):
types = IshtarUser.objects.values('person__person_types',
'person__person_types__label')
- self.types = types.annotate(number=Count('pk'))\
- .order_by('person__person_types')
+ self.types = types.annotate(number=Count('pk')) \
+ .order_by('person__person_types')
class DashboardFormItem(object):
@@ -2254,11 +2269,12 @@ class DashboardFormItem(object):
q = q.filter(**fltr)
if slice == 'year':
return [res[date_var].year for res in list(q.values(date_var)
- .annotate(Count("id")).order_by())]
+ .annotate(
+ Count("id")).order_by())]
elif slice == 'month':
return [(res[date_var].year, res[date_var].month)
for res in list(q.values(date_var)
- .annotate(Count("id")).order_by())]
+ .annotate(Count("id")).order_by())]
return []
@classmethod
@@ -2301,8 +2317,8 @@ class Dashboard(object):
# last edited - created
self.recents, self.lasts = [], []
for last_lst, modif_type in ((self.lasts, '+'), (self.recents, '~')):
- last_ids = history_model.objects.values('id')\
- .annotate(hd=Max('history_date'))
+ last_ids = history_model.objects.values('id') \
+ .annotate(hd=Max('history_date'))
last_ids = last_ids.filter(history_type=modif_type)
from archaeological_finds.models import Find
if self.model == Find:
@@ -2336,15 +2352,15 @@ class Dashboard(object):
# numbers
if slice == 'year':
self.values = [('year', "",
- list(reversed(self.periods)))]
+ list(reversed(self.periods)))]
self.numbers = [model.get_by_year(year, **kwargs_num).count()
for year in self.periods]
self.values += [('number', _(u"Number"),
- list(reversed(self.numbers)))]
+ list(reversed(self.numbers)))]
if slice == 'month':
periods = list(reversed(self.periods))
self.periods = ["%d-%s-01" % (p[0], ('0' + str(p[1]))
- if len(str(p[1])) == 1 else p[1]) for p in periods]
+ if len(str(p[1])) == 1 else p[1]) for p in periods]
self.values = [('month', "", self.periods)]
if show_detail:
for dpt, lbl in settings.ISHTAR_DPTS:
@@ -2363,7 +2379,7 @@ class Dashboard(object):
**kwargs_num).count()
for p in self.periods]
self.values += [('number', _(u"Total"),
- list(self.numbers))]
+ list(self.numbers))]
# calculate
self.average = self.get_average()
self.variance = self.get_variance()
@@ -2387,7 +2403,7 @@ class Dashboard(object):
if operation_mode_pk:
from archaeological_operations.models import Operation
self.operation_mode = unicode(Operation.objects
- .get(pk=operation_mode_pk))
+ .get(pk=operation_mode_pk))
def get_average(self, vals=[]):
if not vals:
@@ -2426,7 +2442,7 @@ class Dashboard(object):
class DocumentTemplate(models.Model):
CLASSNAMES = (('archaeological_operations.models.AdministrativeAct',
- _(u"Administrative Act")),)
+ _(u"Administrative Act")),)
name = models.CharField(_(u"Name"), max_length=100)
slug = models.SlugField(_(u"Slug"), blank=True, null=True, max_length=100,
unique=True)
@@ -2446,7 +2462,7 @@ class DocumentTemplate(models.Model):
return self.name
def natural_key(self):
- return (self.slug, )
+ return (self.slug,)
def save(self, *args, **kwargs):
if not self.slug:
@@ -2465,9 +2481,9 @@ class DocumentTemplate(models.Model):
def publish(self, c_object):
tempdir = tempfile.mkdtemp("-ishtardocs")
output_name = tempdir + os.path.sep + \
- slugify(self.name.replace(' ', '_').lower()) + u'-' +\
- datetime.date.today().strftime('%Y-%m-%d') +\
- u"." + self.template.name.split('.')[-1]
+ slugify(self.name.replace(' ', '_').lower()) + u'-' + \
+ datetime.date.today().strftime('%Y-%m-%d') + \
+ u"." + self.template.name.split('.')[-1]
values = c_object.get_values()
engine = SecretaryRenderer()
try:
@@ -2537,7 +2553,7 @@ class State(models.Model):
return self.label
def natural_key(self):
- return (self.number, )
+ return (self.number,)
class Department(models.Model):
@@ -2556,7 +2572,7 @@ class Department(models.Model):
return self.label
def natural_key(self):
- return (self.number, )
+ return (self.number,)
class Address(BaseHistorizedItem):
@@ -2675,11 +2691,11 @@ class Merge(models.Model):
self.save(merge_key_generated=True)
if not self.pk or self.merge_key == self.EMPTY_MERGE_KEY:
return
- q = self.__class__.objects\
- .exclude(pk=self.pk)\
- .exclude(merge_exclusion=self)\
- .exclude(merge_candidate=self)\
- .exclude(archived=True)
+ q = self.__class__.objects \
+ .exclude(pk=self.pk) \
+ .exclude(merge_exclusion=self) \
+ .exclude(merge_candidate=self) \
+ .exclude(archived=True)
if not self.MERGE_CLEMENCY:
q = q.filter(merge_key=self.merge_key)
else:
@@ -2785,6 +2801,7 @@ class Organization(Address, Merge, OwnPerms, ValueGetter):
return self.name
return u"{} - {}".format(self.organization_type,
self.town or "")
+
def natural_key(self):
return (self.name, self.organization_type.txt_idx)
@@ -3045,8 +3062,8 @@ class Person(Address, Merge, OwnPerms, ValueGetter):
def generate_merge_key(self):
if self.name and self.name.strip():
self.merge_key = slugify(self.name.strip()) + \
- ((u'-' + slugify(self.surname.strip()))
- if self.surname else u'')
+ ((u'-' + slugify(self.surname.strip()))
+ if self.surname else u'')
elif self.raw_name and self.raw_name.strip():
self.merge_key = slugify(self.raw_name.strip())
elif self.attached_to:
@@ -3075,31 +3092,31 @@ class Person(Address, Merge, OwnPerms, ValueGetter):
cache.set(cache_key_list, key_list, settings.CACHE_TIMEOUT)
if type(right_name) in (list, tuple):
res = bool(self.profiles.filter(
- current=True,
- profile_type__txt_idx__in=right_name).count()) or \
- bool(self.profiles.filter(
- current=True,
- profile_type__groups__permissions__codename__in=right_name
- ).count()) or \
- bool(self.ishtaruser.user_ptr.groups.filter(
- permissions__codename__in=right_name
- ).count()) or\
- bool(self.ishtaruser.user_ptr.user_permissions.filter(
- codename__in=right_name).count())
+ current=True,
+ profile_type__txt_idx__in=right_name).count()) or \
+ bool(self.profiles.filter(
+ current=True,
+ profile_type__groups__permissions__codename__in=right_name
+ ).count()) or \
+ bool(self.ishtaruser.user_ptr.groups.filter(
+ permissions__codename__in=right_name
+ ).count()) or \
+ bool(self.ishtaruser.user_ptr.user_permissions.filter(
+ codename__in=right_name).count())
else:
res = bool(
- self.profiles.filter(
- current=True,
- profile_type__txt_idx=right_name).count()) or \
- bool(self.profiles.filter(
+ self.profiles.filter(
current=True,
- profile_type__groups__permissions__codename=right_name
- ).count()) or \
- bool(self.ishtaruser.user_ptr.groups.filter(
- permissions__codename__in=[right_name]
- ).count()) or \
- bool(self.ishtaruser.user_ptr.user_permissions.filter(
- codename__in=[right_name]).count())
+ profile_type__txt_idx=right_name).count()) or \
+ bool(self.profiles.filter(
+ current=True,
+ profile_type__groups__permissions__codename=right_name
+ ).count()) or \
+ bool(self.ishtaruser.user_ptr.groups.filter(
+ permissions__codename__in=[right_name]
+ ).count()) or \
+ bool(self.ishtaruser.user_ptr.user_permissions.filter(
+ codename__in=[right_name]).count())
if session:
cache.set(cache_key, res, settings.CACHE_TIMEOUT)
return res
@@ -3518,21 +3535,21 @@ class Author(FullSearch):
return self.cached_label
def natural_key(self):
- return self.person.natural_key() + (self.author_type.txt_idx, )
+ return self.person.natural_key() + (self.author_type.txt_idx,)
def _generate_cached_label(self):
return unicode(self.person) + settings.JOINT + \
- unicode(self.author_type)
+ unicode(self.author_type)
def fancy_str(self):
return self.person.fancy_str() + settings.JOINT + \
- unicode(self.author_type)
+ unicode(self.author_type)
def related_sources(self):
return list(self.treatmentsource_related.all()) + \
- list(self.operationsource_related.all()) + \
- list(self.findsource_related.all()) + \
- list(self.contextrecordsource_related.all())
+ list(self.operationsource_related.all()) + \
+ list(self.findsource_related.all()) + \
+ list(self.contextrecordsource_related.all())
post_save.connect(cached_label_changed, sender=Author)
@@ -3740,9 +3757,9 @@ class Document(OwnPerms, ImageModel, FullSearch, Imported):
licenses = models.ManyToManyField(LicenseType, verbose_name=_(u"License"),
blank=True)
support_type = models.ForeignKey(SupportType, verbose_name=_(u"Support"),
- blank=True, null=True,)
+ blank=True, null=True, )
format_type = models.ForeignKey(Format, verbose_name=_(u"Format"),
- blank=True, null=True,)
+ blank=True, null=True, )
scale = models.CharField(_(u"Scale"), max_length=30, null=True,
blank=True)
authors = models.ManyToManyField(Author, verbose_name=_(u"Authors"),
@@ -3793,7 +3810,7 @@ class Document(OwnPerms, ImageModel, FullSearch, Imported):
return self.title
def natural_key(self):
- return (self.external_id, )
+ return (self.external_id,)
"""
@property
@@ -4253,6 +4270,8 @@ class SpatialReferenceSystem(GeneralType):
verbose_name = _(u"Spatial reference system")
verbose_name_plural = _(u"Spatial reference systems")
ordering = ('label',)
+
+
post_save.connect(post_save_cache, sender=SpatialReferenceSystem)
post_delete.connect(post_save_cache, sender=SpatialReferenceSystem)