wcs/wcs/roles.py

105 lines
3.3 KiB
Python

# w.c.s. - web application for online forms
# Copyright (C) 2005-2010 Entr'ouvert
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
from quixote import get_publisher
from qommon.storage import StorableObject
import qommon.misc
class Role(StorableObject):
_names = 'roles'
_indexes = ['slug']
name = None
slug = None
details = None
emails = None
emails_to_members = False
allows_backoffice_access = True
def __init__(self, name = None):
StorableObject.__init__(self)
self.name = name
def migrate(self):
changed = False
if not self.slug:
# .store() will take care of setting the slug
changed = True
if changed:
self.store()
def store(self):
if self.slug is None:
# set slug if it's not yet there
self.slug = self.get_new_slug()
super(Role, self).store()
def get_new_slug(self):
new_slug = qommon.misc.simplify(self.name)
base_new_slug = new_slug
suffix_no = 0
while True:
try:
role = self.get_on_index(new_slug, 'slug', ignore_migration=True)
except KeyError:
break
if role.id == self.id:
break
suffix_no += 1
new_slug = '%s-%s' % (base_new_slug, suffix_no)
return new_slug
def get_emails(self):
emails = self.emails or []
if not self.emails_to_members:
return emails
users_with_roles = get_publisher().user_class.get_users_with_role(self.id)
emails.extend([x.email for x in users_with_roles if x.email])
return emails
def get_substitution_variables(self, prefix=''):
data = {}
data[prefix + 'name'] = self.name
if self.emails and not self.emails_to_members:
data[prefix + 'emails'] = ', '.join(self.emails)
return data
def get_json_export_dict(self):
charset = get_publisher().site_charset
return {
'name': unicode(self.name, charset),
'text': unicode(self.name, charset), # generic key
'allows_backoffice_access': self.allows_backoffice_access,
'emails': [unicode(email, charset) for email in self.emails or []],
'details': unicode(self.details or '', charset),
'emails_to_members': self.emails_to_members,
'slug': unicode(self.slug, charset),
'id': self.id}
def logged_users_role():
volatile_role = Role.volatile()
volatile_role.id = 'logged-users'
volatile_role.name = _('Logged Users')
return volatile_role
def get_user_roles():
t = sorted([(qommon.misc.simplify(x.name), x.id, x.name, x.id) for x in Role.select()])
return [x[1:] for x in t]