def classp_update(self, **kw): logger = logging.getLogger('PrivilegesController.classp_update') try: id_class = get_paramw(kw, 'id_class', int) granted = get_paramw(kw, 'granted', strtobool, opcional=True) id_role = get_paramw(kw, 'id_role', int, opcional=True) if id_role: logger.info('role=%d' % id_role) who = dbs.query(SapnsRole).get(id_role) else: id_user = get_paramw(kw, 'id_user', int, opcional=True) who = dbs.query(SapnsUser).get(id_user) #who = SapnsUser() if granted: who.add_privilege(id_class) else: who.remove_privilege(id_class) #, delete=granted is None) return dict(status=True) except Exception, e: logger.error(e) return dict(status=False, message=str(e).decode('utf-8'))
def grid(self, cls, **params): rp = get_paramw(params, 'rp', int, opcional=True, por_defecto=int(config.get('grid.default_rp', 10))) pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1) ds = self.grid_data(cls, **params) # Reading global settings ds.date_fmt = date_fmt ds.time_fmt = config.get('formats.time', default='%H:%M') ds.datetime_fmt = config.get('formats.datetime', default='%m/%d/%Y %H:%M') ds.true_const = _('Yes') ds.false_const = _('No') ds.float_fmt = app_cfg.format_float cols = [] for col in ds.labels: w = 850 / len(ds.labels) if col == 'id': w = 60 cols.append(dict(title=col, width=w, align='center')) this_page, total_pag = pagination(rp, pag_n, ds.count) return dict(status=True, cols=cols, data=ds.to_data(), this_page=this_page, total_count=ds.count, total_pag=total_pag)
def attrp_update(self, **kw): logger = logging.getLogger('PrivilegesController.attrp_update') try: logger.info(kw) id_attribute = get_paramw(kw, 'id_attribute', int) access = get_paramw(kw, 'access', str) id_role = get_paramw(kw, 'id_role', int, opcional=True) id_user = get_paramw(kw, 'id_user', int, opcional=True) if id_role: who = dbs.query(SapnsRole).get(id_role) else: who = dbs.query(SapnsUser).get(id_user) if access: who.add_attr_privilege(id_attribute, access) elif isinstance(who, SapnsUser): who.remove_attr_privilege(id_attribute) return dict(status=True) except Exception, e: logger.error(e) return dict(status=False, message=str(e).decode('utf-8'))
def grid_data(self, cls, **params): _logger = logging.getLogger('DashboardController.grid_data') # picking up parameters q = get_paramw(params, 'q', unicode, opcional=True, por_defecto='') rp = get_paramw(params, 'rp', int, opcional=True, por_defecto=int(config.get('grid.default_rp', 10))) pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1) pos = (pag_n - 1) * rp # collections ch_attr = params.get('ch_attr') parent_id = params.get('parent_id') # filters filters = get_paramw(params, 'filters', sj.loads, opcional=True) cls_ = SapnsClass.by_name(cls) ch_cls_ = SapnsClass.by_name(cls, parent=False) #logger.info('Parent class: %s' % cls_.name) #logger.info('Child class: %s' % ch_cls_.name) # does this user have permission on this table? user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id)) permissions = request.identity['permissions'] if not (user.has_privilege(ch_cls_.name) or user.has_privilege(cls_.name)) or \ not ('%s#%s' % (ch_cls_.name, SapnsPermission.TYPE_LIST) in permissions or \ '%s#%s' % (cls_.name, SapnsPermission.TYPE_LIST) in permissions): return dict( status=False, message=_('Sorry, you do not have privilege on this class')) # get view name view = user.get_view_name(ch_cls_.name) #logger.info('search...%s / q=%s' % (view, q)) # collection col = None if ch_attr and parent_id: col = ( cls, ch_attr, parent_id, ) # get dataset _search = Search(dbs, view, strtodatef=_strtodate) _search.apply_qry(q.encode('utf-8')) _search.apply_filters(filters) return _search(rp=rp, offset=pos, collection=col)
def list(self, cls, **params): _logger = logging.getLogger('DashboardController.list') q = get_paramw(params, 'q', unicode, opcional=True, por_defecto='') rp = get_paramw(params, 'rp', int, opcional=True, por_defecto=int(config.get('grid.default_rp', 10))) pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1) came_from = params.get('came_from', '') if came_from: came_from = url(came_from) # collections ch_attr = params.get('ch_attr') parent_id = params.get('parent_id') # does this user have permission on this table? user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id)) permissions = request.identity['permissions'] cls_ = SapnsClass.by_name(cls) ch_cls_ = SapnsClass.by_name(cls, parent=False) # _logger.info('Parent class: %s' % cls_.name) # _logger.info('Child class: %s' % ch_cls_.name) if not (user.has_privilege(ch_cls_.name) or user.has_privilege(cls_.name)) or \ not ('%s#%s' % (ch_cls_.name, SapnsPermission.TYPE_LIST) in permissions or \ '%s#%s' % (cls_.name, SapnsPermission.TYPE_LIST) in permissions): redirect(url('/message', params=dict(message=_('Sorry, you do not have privilege on this class'), came_from=came_from))) # related classes rel_classes = cls_.related_classes() # collection caption = ch_cls_.title if ch_attr and parent_id: p_cls = cls_.attr_by_name(ch_attr).related_class p_title = SapnsClass.object_title(p_cls.name, parent_id) caption = _('%s of [%s]') % (ch_cls_.title, p_title) return dict(page=_('list of %s') % ch_cls_.title.lower(), came_from=came_from, grid=dict(cls=ch_cls_.name, caption=caption, q=q.replace('"', '\\\"'), rp=rp, pag_n=pag_n, # collection ch_attr=ch_attr, parent_id=parent_id, # related classes rel_classes=rel_classes))
def remove_file(self, **kw): logger = logging.getLogger('DocsController.remove_file') try: file_name = get_paramw(kw, 'file_name', unicode) id_repo = get_paramw(kw, 'id_repo', int) SapnsDoc.remove_file(id_repo, file_name) return dict(status=True) except Exception, e: logger.error(e) return dict(status=False, message=str(e).decode('utf-8'))
def grid_data(self, cls, **params): _logger = logging.getLogger('DashboardController.grid_data') # picking up parameters q = get_paramw(params, 'q', unicode, opcional=True, por_defecto='') rp = get_paramw(params, 'rp', int, opcional=True, por_defecto=int(config.get('grid.default_rp', 10))) pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1) pos = (pag_n-1) * rp # collections ch_attr = params.get('ch_attr') parent_id = params.get('parent_id') # filters filters = get_paramw(params, 'filters', sj.loads, opcional=True) cls_ = SapnsClass.by_name(cls) ch_cls_ = SapnsClass.by_name(cls, parent=False) #logger.info('Parent class: %s' % cls_.name) #logger.info('Child class: %s' % ch_cls_.name) # does this user have permission on this table? user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id)) permissions = request.identity['permissions'] if not (user.has_privilege(ch_cls_.name) or user.has_privilege(cls_.name)) or \ not ('%s#%s' % (ch_cls_.name, SapnsPermission.TYPE_LIST) in permissions or \ '%s#%s' % (cls_.name, SapnsPermission.TYPE_LIST) in permissions): return dict(status=False, message=_('Sorry, you do not have privilege on this class')) # get view name view = user.get_view_name(ch_cls_.name) #logger.info('search...%s / q=%s' % (view, q)) # collection col = None if ch_attr and parent_id: col = (cls, ch_attr, parent_id,) # get dataset _search = Search(dbs, view, strtodatef=_strtodate) _search.apply_qry(q.encode('utf-8')) _search.apply_filters(filters) return _search(rp=rp, offset=pos, collection=col)
def edit(self, **kw): id_doc = get_paramw(kw, 'id_doc', int, opcional=True) #id_class = get_paramw(kw, 'id_class', int) #id_object = get_paramw(kw, 'id_object', int) doc = Dict(repo=None) # lookup repositories repos = dbs.query(SapnsRepo).all() if len(repos) == 1: doc.id_repo = repos[0].repo_id if id_doc: # edit doc doc_ = dbs.query(SapnsDoc).get(id_doc) doc.id_author = doc_.author_id else: # new doc doc_ = SapnsDoc() doc.id_author = request.identity['user'].user_id doc.title = doc_.title doc.id_type = doc_.doctype_id doc.id_format = doc_.docformat_id doc.filename = doc_.filename doc.id_repo = doc_.repo_id return dict(doc=doc)
def search(self, cls, id, **kw): class_ = SapnsClass.by_name(cls) id_object = int(id) # picking up parameters q = get_paramw(kw, 'q', unicode, opcional=True, por_defecto='') rp = get_paramw(kw, 'rp', int, opcional=True, por_defecto=int(config.get('grid.default_rp', 10))) pag_n = get_paramw(kw, 'pag_n', int, opcional=True, por_defecto=1) pos = (pag_n-1) * rp filters = [('id_class', class_.class_id), ('id_object', id_object)] view_name = '%ssp_docs' % config.get('views_prefix', '_view_') ds = search(dbs, view_name, q=q.encode('utf-8'), rp=rp, offset=pos, filters=filters) cols = [] for col in ds.labels: w = 125 if col == 'id': w = 60 cols.append(dict(title=col, width=w, align='center')) # total number of pages total_pag = 1 if rp > 0: total_pag = ds.count / rp if ds.count % rp != 0: total_pag += 1 if total_pag == 0: total_pag = 1 # rows in this page totalp = ds.count - pos if rp and totalp > rp: totalp = rp # rows in this page this_page = ds.count - pos if rp and this_page > rp: this_page = rp return dict(status=True, cols=cols, data=ds.to_data(), this_page=this_page, total_count=ds.count, total_pag=total_pag)
def actions(self, id_class, **kw): logger = logging.getLogger('PrivilegesController.actions') try: id_class = int(id_class) #id_user = get_paramw(kw, 'id_user', int, opcional=True) id_role = get_paramw(kw, 'id_role', int, opcional=True) if id_role: who = dbs.query(SapnsRole).get(id_role) # else: # who = dbs.query(SapnsUser).get(id_user) # class cls = dbs.query(SapnsClass).get(id_class) if cls: permissions = cls.permissions else: permissions = dbs.query(SapnsPermission).\ filter(SapnsPermission.class_id == None) actions = [] for action in permissions: if action.type == SapnsPermission.TYPE_NEW: pos = 1 elif action.type == SapnsPermission.TYPE_EDIT: pos = 2 elif action.type == SapnsPermission.TYPE_DELETE: pos = 3 elif action.type == SapnsPermission.TYPE_DOCS: pos = 4 else: pos = 100 actions.append(Dict(id_action=action.permission_id, display_name=_(action.display_name), name=action.permission_name, granted=who.has_permission(action.permission_id), pos=pos, )) def cmp_action(x, y): if x.pos == y.pos: return cmp(x.name, y.name) else: return cmp(x.pos, y.pos) return dict(actions=sorted(actions, cmp=cmp_action)) except Exception, e: logger.error(e) return dict(status=False)
def index(self, **kw): logger = logging.getLogger('PrivilegesController.index') try: id_role = get_paramw(kw, 'id_role', int, opcional=True) id_user = get_paramw(kw, 'id_user', int, opcional=True) role = dbs.query(SapnsRole).get(id_role) came_from = kw.get('came_from', '/') page = _('Privilege management for "%s"') % role.group_name return dict(page=page, id_role=id_role, id_user=id_user, came_from=came_from) except Exception, e: logger.error(e)
def _copy(self, **kw): logger = logging.getLogger('PrivilegesController._copy') try: to = get_paramw(kw, 'to', int) role_to = dbs.query(SapnsRole).get(to) from_roles = get_paramw(kw, 'from', sj.loads) for id_from in from_roles: role_to.copy_privileges_from(id_from) return dict(status=True) except Exception, e: logger.error(e) return dict(status=False)
def attributes(self, id_class, **kw): def _attr_privilege(cond, id_attribute): return dbs.query(SapnsAttrPrivilege).\ filter(and_(cond, SapnsAttrPrivilege.attribute_id == id_attribute)).\ first() id_class = int(id_class) if id_class == -1: return dict(attributes=[]) id_user = get_paramw(kw, 'id_user', int, opcional=True) id_role = get_paramw(kw, 'id_role', int, opcional=True) if id_role: #who = dbs.query(SapnsRole).get(id_role) attr_privilege = lambda id: \ _attr_privilege(SapnsAttrPrivilege.role_id == id_role, id) else: #who = dbs.query(SapnsUser).get(id_user) attr_privilege = lambda id: \ _attr_privilege(SapnsAttrPrivilege.user_id == id_user, id) # class cls = dbs.query(SapnsClass).get(id_class) attributes = [] for attr in cls.attributes: attr_p = attr_privilege(attr.attribute_id) if not attr_p: attr_p = Dict(access='') #SapnsAttrPrivilege.ACCESS_DENIED) attributes.append(Dict(id=attr_p.attr_privilege_id, access=attr_p.access, name=attr.name, title=attr.title, id_attr=attr.attribute_id, ins_order=attr.insertion_order, )) return dict(attributes=sorted(attributes, cmp=lambda x,y: cmp(x.ins_order, y.ins_order)), show_none=id_user != None)
def classes(self, **kw): logger = logging.getLogger('PrivilegesController.classes') try: id_user = get_paramw(kw, 'id_user', int, opcional=True) id_role = get_paramw(kw, 'id_role', int, opcional=True) if id_role: logger.info('role') who = dbs.query(SapnsRole).get(id_role) def has_privilege(id_class): return who.has_privilege(id_class, no_cache=True) else: who = dbs.query(SapnsUser).get(id_user) #who = SapnsUser() def has_privilege(id_class): priv = who.get_privilege(id_class) if priv: return priv.granted return None #cls = dbs.query(SapnsClass).get(id_class) #return who.has_privilege(cls.name, no_cache=True) classes = [] classes.append(Dict(id=-1, id_class_p=None, name='*', granted=True )) for cls in dbs.query(SapnsClass).order_by(SapnsClass.title): classes.append(Dict(id=cls.class_id, id_class_p=None, name=cls.title, granted=has_privilege(cls.class_id), )) return dict(classes=classes, show_none=id_user != None) except Exception, e: logger.error(e)
def update_role(self, **kw): logger = logging.getLogger('UsersController.roles') try: id_user = get_paramw(kw, 'id_user', int) id_role = get_paramw(kw, 'id_role', int) selected = get_paramw(kw, 'selected', strtobool) if id_user == 1 and id_role == 1: raise Exception( 'It is not possible to remove "managers" privilege from "superuser"' ) user_role = dbs.query(SapnsUserRole).\ filter(and_(SapnsUserRole.role_id == id_role, SapnsUserRole.user_id == id_user, )).\ first() if selected: if not user_role: user_role = SapnsUserRole() user_role.role_id = id_role user_role.user_id = id_user dbs.add(user_role) dbs.flush() else: if user_role: user_role = dbs.query(SapnsUserRole).\ filter(and_(SapnsUserRole.role_id == id_role, SapnsUserRole.user_id == id_user, )).\ delete() dbs.flush() return sj.dumps(dict(status=True)) except Exception, e: logger.error(e) return sj.dumps(dict(status=False))
def update_role(self, **kw): logger = logging.getLogger('UsersController.roles') try: id_user = get_paramw(kw, 'id_user', int) id_role = get_paramw(kw, 'id_role', int) selected = get_paramw(kw, 'selected', strtobool) if id_user == 1 and id_role == 1: raise Exception('It is not possible to remove "managers" privilege from "superuser"') user_role = dbs.query(SapnsUserRole).\ filter(and_(SapnsUserRole.role_id == id_role, SapnsUserRole.user_id == id_user, )).\ first() if selected: if not user_role: user_role = SapnsUserRole() user_role.role_id = id_role user_role.user_id = id_user dbs.add(user_role) dbs.flush() else: if user_role: user_role = dbs.query(SapnsUserRole).\ filter(and_(SapnsUserRole.role_id == id_role, SapnsUserRole.user_id == id_user, )).\ delete() dbs.flush() return sj.dumps(dict(status=True)) except Exception, e: logger.error(e) return sj.dumps(dict(status=False))
def create_shortcut_(self, **kw): logger = logging.getLogger('PermissionsController.create_shortcut_') try: user_id = get_paramw(kw, 'user_id', int) permission_id = get_paramw(kw, 'permission_id', int) groups = get_paramw(kw, 'groups', sj.loads) p = dbs.query(SapnsPermission).get(permission_id) if p.type not in [SapnsPermission.TYPE_LIST, SapnsPermission.TYPE_PROCESS] or \ p.type == SapnsPermission.TYPE_PROCESS and p.requires_id: raise EPermissions(_(u'Shortcuts can only be created from LIST and PROCESS (no required id) type permissions')) title = p.display_name if p.type == SapnsPermission.TYPE_LIST: title = p.class_.title for id_group in groups: group = dbs.query(SapnsShortcut).get(id_group) sc = SapnsShortcut() sc.user_id = user_id sc.parent_id = id_group sc.permission_id = permission_id sc.title = title sc.order = group.next_order() dbs.add(sc) dbs.flush() _key = '%d_%d' % (user_id, id_group) cache.get_cache('user_get_shortcuts').remove_value(key=_key) return dict(status=True) except EPermissions, e: logger.error(e) return dict(status=False, msg=unicode(e))
def actionp_update(self, **kw): logger = logging.getLogger('PrivilegesController.actionp_update') try: id_action = get_paramw(kw, 'id_action', int) granted = get_paramw(kw, 'granted', strtobool) id_role = get_paramw(kw, 'id_role', int, opcional=True) #id_user = get_paramw(kw, 'id_user', int, opcional=True) #if id_role: who = dbs.query(SapnsRole).get(id_role) # else: # who = dbs.query(SapnsUser).get(id_user) action = dbs.query(SapnsPermission).get(id_action) if granted: logger.info('Creating action privilege') who.permissions_.append(action) else: logger.info('Deleting action privilege') who.permissions_.remove(action) dbs.flush() # reset cache _cache = cache.get_cache(SapnsPermission.CACHE_ID) for user in who.users_: _cache.remove_value(key='%d_%d' % (user.user_id, action.class_id)) return dict(status=True) except Exception, e: logger.error(e) return dict(status=False, message=str(e).decode('utf-8'))
def save(self, **kw): logger = logging.getLogger('DocsController.save') try: # collect params id_author = request.identity['user'].user_id id_object = get_paramw(kw, 'id_object', int) id_class = get_paramw(kw, 'id_class', int) title = get_paramw(kw, 'title', unicode) id_type = get_paramw(kw, 'id_type', int, opcional=True) id_format = get_paramw(kw, 'id_format', int) id_repo = get_paramw(kw, 'id_repo', int) file_name = get_paramw(kw, 'file_name', unicode) id_doc = get_paramw(kw, 'id_doc', int, opcional=True) # create doc if id_doc: # edit new_doc = dbs.query(SapnsDoc).get(id_doc) else: # create new_doc = SapnsDoc() new_doc.repo_id = id_repo new_doc.doctype_id = id_type new_doc.docformat_id = id_format new_doc.author_id = id_author new_doc.filename = file_name new_doc.title = title dbs.add(new_doc) dbs.flush() if not id_doc: # (only at creation) new_doc.register(id_class, id_object) return dict(status=True) except Exception, e: logger.error(e) return dict(status=False, message=str(e).decode('utf-8'))
def upload_file(self, f, **kw): logger = logging.getLogger('DocsController.upload_file') try: id_repo = get_paramw(kw, 'id_repo', int) r = SapnsDoc.upload(f, id_repo) return sj.dumps(dict(status=True, uploaded_file=r['uploaded_file'], file_name=r['file_name'], file_size=r['file_size'], )) except Exception, e: logger.error(e) return sj.dumps(dict(status=False, message=str(e).decode('utf-8')))
def search(self, **params): logger = logging.getLogger('DashboardController.search') try: import random random.seed() #params['caption'] = '' g = self.list(**params) g['grid']['name'] = '_%6.6d' % random.randint(0, 999999) g['grid']['q'] = get_paramw(params, 'q', unicode, opcional=True) g['grid']['filters'] = params.get('filters') return g except Exception, e: logger.error(e) raise
def grid(self, cls, **params): #logger = logging.getLogger('DashboardController.grid') # picking up parameters q = get_paramw(params, 'q', unicode, opcional=True, por_defecto='') rp = get_paramw(params, 'rp', int, opcional=True, por_defecto=int(config.get('grid.default_rp', 10))) pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1) pos = (pag_n-1) * rp # does this user have permission on this table? user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id)) permissions = request.identity['permissions'] cls_ = SapnsClass.by_name(cls) ch_cls_ = SapnsClass.by_name(cls, parent=False) if not user.has_privilege(cls_.name) or \ not '%s#%s' % (cls_.name, SapnsPermission.TYPE_LIST) in permissions: return dict(status=False, message=_('Sorry, you do not have privilege on this class')) # get view name view = user.get_view_name(ch_cls_.name) # get dataset s = Search(dbs, view, strtodatef=_strtodate) # TODO: joins meta = MetaData(bind=dbs.bind) t_logs = Table('sp_logs', meta, autoload=True) table_name = get_paramw(params, 'table_name', unicode) row_id = get_paramw(params, 'row_id', int) s.join(t_logs, and_(t_logs.c.id == s.tbl.c.id, t_logs.c.table_name == table_name, t_logs.c.row_id == row_id, )) # q s.apply_qry(q.encode('utf-8')) # ordenar #s.order_by(desc(s.tbl.c.id)) ds = s(rp=rp, offset=pos) # Reading global settings ds.date_fmt = date_fmt ds.time_fmt = config.get('formats.time', default='%H:%M') ds.datetime_fmt = config.get('formats.datetime', default='%m/%d/%Y %H:%M') ds.true_const = _('Yes') ds.false_const = _('No') ds.float_fmt = app_cfg.format_float cols = [] for col in ds.labels: w = 125 if col == 'id': w = 60 cols.append(dict(title=col, width=w, align='center')) this_page, total_pag = pagination(rp, pag_n, ds.count) return dict(status=True, cols=cols, data=ds.to_data(), this_page=this_page, total_count=ds.count, total_pag=total_pag)
def save(self, **params): logger = logging.getLogger('UsersController.save') try: #logger.info(params) id_ = get_paramw(params, 'id', int, opcional=True) display_name = get_paramw(params, 'display_name', unicode) user_name = get_paramw(params, 'user_name', unicode) email_address = get_paramw(params, 'email_address', unicode) password = get_paramw(params, 'password', unicode, opcional=True) copy_from = get_paramw(params, 'copy_from', int, opcional=True) new_user = False if id_: user = dbs.query(SapnsUser).get(id_) else: new_user = True user = SapnsUser() user.display_name = display_name # user_name another = dbs.query(SapnsUser).\ filter(and_(SapnsUser.user_id != user.user_id, SapnsUser.user_name == user_name, )).\ first() if another: raise EUser(_('"User name" is already in use')) # email_address another = dbs.query(SapnsUser).\ filter(and_(SapnsUser.user_id != user.user_id, SapnsUser.email_address == email_address, )).\ first() if another: raise EUser(_('"E-mail address" is already in use')) # user_name user.user_name = user_name # email_address user.email_address = email_address if password: user.password = password dbs.add(user) dbs.flush() # copy shortcuts and privileges form another user if new_user: user.copy_from(copy_from) return dict(status=True) except EUser, e: logger.error(e) return dict(status=False, message=unicode(e))
def list(self, cls, **params): _logger = logging.getLogger('DashboardController.list') q = get_paramw(params, 'q', unicode, opcional=True, por_defecto='') rp = get_paramw(params, 'rp', int, opcional=True, por_defecto=int(config.get('grid.default_rp', 10))) pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1) came_from = params.get('came_from', '') if came_from: came_from = url(came_from) # collections ch_attr = params.get('ch_attr') parent_id = params.get('parent_id') # does this user have permission on this table? user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id)) permissions = request.identity['permissions'] cls_ = SapnsClass.by_name(cls) ch_cls_ = SapnsClass.by_name(cls, parent=False) # _logger.info('Parent class: %s' % cls_.name) # _logger.info('Child class: %s' % ch_cls_.name) if not (user.has_privilege(ch_cls_.name) or user.has_privilege(cls_.name)) or \ not ('%s#%s' % (ch_cls_.name, SapnsPermission.TYPE_LIST) in permissions or \ '%s#%s' % (cls_.name, SapnsPermission.TYPE_LIST) in permissions): redirect( url('/message', params=dict(message=_( 'Sorry, you do not have privilege on this class'), came_from=came_from))) # related classes rel_classes = cls_.related_classes() # collection caption = ch_cls_.title if ch_attr and parent_id: p_cls = cls_.attr_by_name(ch_attr).related_class p_title = SapnsClass.object_title(p_cls.name, parent_id) caption = _('%s of [%s]') % (ch_cls_.title, p_title) return dict( page=_('list of %s') % ch_cls_.title.lower(), came_from=came_from, grid=dict( cls=ch_cls_.name, caption=caption, q=q.replace('"', '\\\"'), rp=rp, pag_n=pag_n, # collection ch_attr=ch_attr, parent_id=parent_id, # related classes rel_classes=rel_classes))
def edit(self, cls, id='', **params): _logger = logging.getLogger('DashboardController.edit') came_from = get_paramw(params, 'came_from', unicode, opcional=True, por_defecto='/') user = dbs.query(SapnsUser).get(request.identity['user'].user_id) permissions = request.identity['permissions'] class_ = SapnsClass.by_name(cls) ch_class_ = SapnsClass.by_name(cls, parent=False) # log _what = _('edit record') if not id: _what = _('new record') _id = None else: _id = int(id) SapnsLog.register( table_name=ch_class_.name, row_id=_id, who=user.user_id, what=_what, ) if id: id = int(id) perm = '%s#%s' % (ch_class_.name, SapnsPermission.TYPE_EDIT) in permissions or \ '%s#%s' % (class_.name, SapnsPermission.TYPE_EDIT) in permissions else: perm = '%s#%s' % (class_.name, SapnsPermission.TYPE_NEW) in permissions or \ '%s#%s' % (class_.name, SapnsPermission.TYPE_NEW) in permissions if not (user.has_privilege(ch_class_.name) or user.has_privilege(class_.name)) or not perm: redirect( url('/message', params=dict(message=_( 'Sorry, you do not have privilege on this class'), came_from=came_from))) # actions actions = [ action for action in class_.sorted_actions(user.user_id) if action['type'] == 'process' ] meta = MetaData(dbs.bind) try: tbl = Table(class_.name, meta, autoload=True) except NoSuchTableError: redirect( url('/message', params=dict(message=_('This class does not exist'), came_from=came_from))) default_values_ro = {} default_values = {} for field_name, value in params.iteritems(): # default read-only values (_xxxx) m = re.search(r'^_([a-z]\w+)$', field_name, re.I | re.U) if m: #logger.info('Default value (read-only): %s = %s' % (m.group(1), params[field_name])) default_values_ro[m.group(1)] = params[field_name] else: # default read/write values (__xxxx) # depends on privilege of this attribute m = re.search(r'^__([a-z]\w+)$', field_name, re.I | re.U) if m: #logger.info('Default value (read/write*): %s = %s' % (m.group(1), params[field_name])) default_values[m.group(1)] = params[field_name] _created = None _updated = None ref = None row = None if id: row = dbs.execute(tbl.select(tbl.c.id == id)).fetchone() if not row: # row does not exist redirect( url('/message', params=dict(message=_('Record does not exist'), came_from=came_from))) # reference ref = SapnsClass.object_title(class_.name, id) if class_.name != u'sp_logs': _created = row['_created'].strftime( datetime_fmt) if row['_created'] else None _updated = row['_updated'].strftime( datetime_fmt) if row['_updated'] else None #logger.info(row) # get attributes attributes = [] for attr, attr_priv in SapnsClass.by_name(cls).get_attributes( user.user_id): #logger.info('%s [%s]' % (attr.name, attr_priv.access)) value = '' read_only = attr_priv.access == SapnsAttrPrivilege.ACCESS_READONLY if attr.name in default_values_ro: value = default_values_ro[attr.name] read_only = True elif attr.name in default_values: value = default_values[attr.name] elif row: #logger.info(row[attr.name]) #logger.info(attr) if row[attr.name] != None: # date if attr.type == SapnsAttribute.TYPE_DATE: value = datetostr(row[attr.name], fmt=date_fmt) # datetime elif attr.type == SapnsAttribute.TYPE_DATETIME: value = row[attr.name].strftime(datetime_fmt) if row[ attr.name] else '' # numeric (int, float) elif attr.type in [ SapnsAttribute.TYPE_INTEGER, SapnsAttribute.TYPE_FLOAT ]: value = row[attr.name] # rest of types else: value = row[attr.name] or '' attribute = dict( name=attr.name, title=attr.title, type=attr.type, value=value, required=attr.required, related_class=None, related_class_title='', read_only=read_only, vals=None, field_regex=attr.field_regex, ) #logger.info('%s = %s' % (attr.name, repr(value))) attributes.append(attribute) if attr.related_class_id: # vals try: rel_class = dbs.query(SapnsClass).get( attr.related_class_id) # related_class attribute['related_class'] = rel_class.name attribute['related_class_title'] = rel_class.title attribute['related_title'] = SapnsClass.object_title( rel_class.name, value) except Exception, e: _logger.error(e) attribute['vals'] = None
def save(self, cls, **params): """ IN cls <unicode> params id <int> came_from <unicode> fld_* ??? Fields to be saved """ logger = logging.getLogger(__name__ + '/save') try: #logger.info(params) ch_cls = SapnsClass.by_name(cls, parent=False) cls = SapnsClass.by_name(cls) id_ = get_paramw(params, 'id', int, opcional=True) # does this user have permission on this table? user = dbs.query(SapnsUser).get(request.identity['user'].user_id) permissions = request.identity['permissions'] if not user.has_privilege(cls.name) or \ not '%s#%s' % (cls.name, SapnsPermission.TYPE_EDIT) in permissions: return dict(status=False) # init "update" dictionary update = {} if id_: update['id'] = int(id_) READONLY_DENIED = [ SapnsAttrPrivilege.ACCESS_READONLY, SapnsAttrPrivilege.ACCESS_DENIED ] def _strtodatetime(s, fmt): # build regex regex = r'^\s*%s\s*$' % (fmt.replace('%d', r'(?P<day>([0-2]?[1-9]|3[0-1]))').\ replace('%m', r'(?P<month>(0?[1-9]|1[0-2]))').\ replace('%Y', r'(?P<year>\d{4})').\ replace('%H', r'(?P<hour>([0-1]?[0-9]|2[0-3]))').\ replace('%M', r'(?P<minute>[0-5][0-9])').\ replace('%S', r'(?P<second>[0-5][0-9])').\ replace(' ', r'\s')) m1 = re.search(regex, s) if m1: try: day = int(m1.groupdict().get('day') or 1) month = int(m1.groupdict().get('month') or 1) year = int(m1.groupdict().get('year') or 1900) hour = int(m1.groupdict().get('hour') or 0) min_ = int(m1.groupdict().get('minute') or 0) sec = int(m1.groupdict().get('second') or 0) return dt.datetime(year, month, day, hour, min_, sec) except Exception, e: logger.error(e) raise else:
def save(self, cls, **params): """ IN cls <unicode> params id <int> came_from <unicode> fld_* ??? Fields to be saved """ logger = logging.getLogger(__name__ + '/save') try: #logger.info(params) ch_cls = SapnsClass.by_name(cls, parent=False) cls = SapnsClass.by_name(cls) id_ = get_paramw(params, 'id', int, opcional=True) # does this user have permission on this table? user = dbs.query(SapnsUser).get(request.identity['user'].user_id) permissions = request.identity['permissions'] if not user.has_privilege(cls.name) or \ not '%s#%s' % (cls.name, SapnsPermission.TYPE_EDIT) in permissions: return dict(status=False) # init "update" dictionary update = {} if id_: update['id'] = int(id_) READONLY_DENIED = [SapnsAttrPrivilege.ACCESS_READONLY, SapnsAttrPrivilege.ACCESS_DENIED] def _strtodatetime(s, fmt): # build regex regex = r'^\s*%s\s*$' % (fmt.replace('%d', r'(?P<day>([0-2]?[1-9]|3[0-1]))').\ replace('%m', r'(?P<month>(0?[1-9]|1[0-2]))').\ replace('%Y', r'(?P<year>\d{4})').\ replace('%H', r'(?P<hour>([0-1]?[0-9]|2[0-3]))').\ replace('%M', r'(?P<minute>[0-5][0-9])').\ replace('%S', r'(?P<second>[0-5][0-9])').\ replace(' ', r'\s')) m1 = re.search(regex, s) if m1: try: day = int(m1.groupdict().get('day') or 1) month = int(m1.groupdict().get('month') or 1) year = int(m1.groupdict().get('year') or 1900) hour = int(m1.groupdict().get('hour') or 0) min_ = int(m1.groupdict().get('minute') or 0) sec = int(m1.groupdict().get('second') or 0) return dt.datetime(year, month, day, hour, min_, sec) except Exception, e: logger.error(e) raise else:
def edit(self, cls, id='', **params): _logger = logging.getLogger('DashboardController.edit') came_from = get_paramw(params, 'came_from', unicode, opcional=True, por_defecto='/') user = dbs.query(SapnsUser).get(request.identity['user'].user_id) permissions = request.identity['permissions'] class_ = SapnsClass.by_name(cls) ch_class_ = SapnsClass.by_name(cls, parent=False) # log _what = _('edit record') if not id: _what = _('new record') _id = None else: _id = int(id) SapnsLog.register(table_name=ch_class_.name, row_id=_id, who=user.user_id, what=_what, ) if id: id = int(id) perm = '%s#%s' % (ch_class_.name, SapnsPermission.TYPE_EDIT) in permissions or \ '%s#%s' % (class_.name, SapnsPermission.TYPE_EDIT) in permissions else: perm = '%s#%s' % (class_.name, SapnsPermission.TYPE_NEW) in permissions or \ '%s#%s' % (class_.name, SapnsPermission.TYPE_NEW) in permissions if not (user.has_privilege(ch_class_.name) or user.has_privilege(class_.name)) or not perm: redirect(url('/message', params=dict(message=_('Sorry, you do not have privilege on this class'), came_from=came_from))) # actions actions = [action for action in class_.sorted_actions(user.user_id) if action['type'] == 'process'] meta = MetaData(dbs.bind) try: tbl = Table(class_.name, meta, autoload=True) except NoSuchTableError: redirect(url('/message', params=dict(message=_('This class does not exist'), came_from=came_from))) default_values_ro = {} default_values = {} for field_name, value in params.iteritems(): # default read-only values (_xxxx) m = re.search(r'^_([a-z]\w+)$', field_name, re.I | re.U) if m: #logger.info('Default value (read-only): %s = %s' % (m.group(1), params[field_name])) default_values_ro[m.group(1)] = params[field_name] else: # default read/write values (__xxxx) # depends on privilege of this attribute m = re.search(r'^__([a-z]\w+)$', field_name, re.I | re.U) if m: #logger.info('Default value (read/write*): %s = %s' % (m.group(1), params[field_name])) default_values[m.group(1)] = params[field_name] _created = None _updated = None ref = None row = None if id: row = dbs.execute(tbl.select(tbl.c.id == id)).fetchone() if not row: # row does not exist redirect(url('/message', params=dict(message=_('Record does not exist'), came_from=came_from))) # reference ref = SapnsClass.object_title(class_.name, id) if class_.name != u'sp_logs': _created = row['_created'].strftime(datetime_fmt) if row['_created'] else None _updated = row['_updated'].strftime(datetime_fmt) if row['_updated'] else None #logger.info(row) # get attributes attributes = [] for attr, attr_priv in SapnsClass.by_name(cls).get_attributes(user.user_id): #logger.info('%s [%s]' % (attr.name, attr_priv.access)) value = '' read_only = attr_priv.access == SapnsAttrPrivilege.ACCESS_READONLY if attr.name in default_values_ro: value = default_values_ro[attr.name] read_only = True elif attr.name in default_values: value = default_values[attr.name] elif row: #logger.info(row[attr.name]) #logger.info(attr) if row[attr.name] != None: # date if attr.type == SapnsAttribute.TYPE_DATE: value = datetostr(row[attr.name], fmt=date_fmt) # datetime elif attr.type == SapnsAttribute.TYPE_DATETIME: value = row[attr.name].strftime(datetime_fmt) if row[attr.name] else '' # numeric (int, float) elif attr.type in [SapnsAttribute.TYPE_INTEGER, SapnsAttribute.TYPE_FLOAT]: value = row[attr.name] # rest of types else: value = row[attr.name] or '' attribute = dict(name=attr.name, title=attr.title, type=attr.type, value=value, required=attr.required, related_class=None, related_class_title='', read_only=read_only, vals=None, field_regex=attr.field_regex,) #logger.info('%s = %s' % (attr.name, repr(value))) attributes.append(attribute) if attr.related_class_id: # vals try: rel_class = dbs.query(SapnsClass).get(attr.related_class_id) # related_class attribute['related_class'] = rel_class.name attribute['related_class_title'] = rel_class.title attribute['related_title'] = SapnsClass.object_title(rel_class.name, value) except Exception, e: _logger.error(e) attribute['vals'] = None
def grid(self, cls, **params): #logger = logging.getLogger('DashboardController.grid') # picking up parameters q = get_paramw(params, 'q', unicode, opcional=True, por_defecto='') rp = get_paramw(params, 'rp', int, opcional=True, por_defecto=int(config.get('grid.default_rp', 10))) pag_n = get_paramw(params, 'pag_n', int, opcional=True, por_defecto=1) pos = (pag_n - 1) * rp # does this user have permission on this table? user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id)) permissions = request.identity['permissions'] cls_ = SapnsClass.by_name(cls) ch_cls_ = SapnsClass.by_name(cls, parent=False) if not user.has_privilege(cls_.name) or \ not '%s#%s' % (cls_.name, SapnsPermission.TYPE_LIST) in permissions: return dict( status=False, message=_('Sorry, you do not have privilege on this class')) # get view name view = user.get_view_name(ch_cls_.name) # get dataset s = Search(dbs, view, strtodatef=_strtodate) # TODO: joins meta = MetaData(bind=dbs.bind) t_logs = Table('sp_logs', meta, autoload=True) table_name = get_paramw(params, 'table_name', unicode) row_id = get_paramw(params, 'row_id', int) s.join( t_logs, and_( t_logs.c.id == s.tbl.c.id, t_logs.c.table_name == table_name, t_logs.c.row_id == row_id, )) # q s.apply_qry(q.encode('utf-8')) # ordenar #s.order_by(desc(s.tbl.c.id)) ds = s(rp=rp, offset=pos) # Reading global settings ds.date_fmt = date_fmt ds.time_fmt = config.get('formats.time', default='%H:%M') ds.datetime_fmt = config.get('formats.datetime', default='%m/%d/%Y %H:%M') ds.true_const = _('Yes') ds.false_const = _('No') ds.float_fmt = app_cfg.format_float cols = [] for col in ds.labels: w = 125 if col == 'id': w = 60 cols.append(dict(title=col, width=w, align='center')) this_page, total_pag = pagination(rp, pag_n, ds.count) return dict(status=True, cols=cols, data=ds.to_data(), this_page=this_page, total_count=ds.count, total_pag=total_pag)