def index(self, sc_type='list', sc_parent=None): curr_lang = get_lang() # connected user user = dbs.query(SapnsUser).get(request.identity['user'].user_id) # get children shortcuts (shortcuts.parent_id = sc_parent) of the this user shortcuts = user.get_shortcuts(id_parent=sc_parent) params = {} if sc_parent: params = dict(sc_parent=sc_parent) came_from = url('/dashboard/', params=params) if sc_parent: sc_parent = dbs.query(SapnsShortcut).get(sc_parent).parent_id else: sc_parent = None return dict(page='dashboard', shortcuts=shortcuts, sc_type=sc_type, sc_parent=sc_parent, _came_from=came_from)
def users(self, id_role, **kw): logger = logging.getLogger('RolesController.roles') try: role = dbs.query(SapnsRole).get(int(id_role)) users = [] for u in dbs.query(SapnsUser): has_role = dbs.query(SapnsUserRole).\ filter(and_(SapnsUserRole.role_id == role.group_id, SapnsUserRole.user_id == u.user_id, )).\ first() users.append( dict( id=u.user_id, name=u.user_name, selected=has_role != None, )) return dict(page='Role users', came_from=kw.get('came_from'), role=dict(id=role.group_id, name=role.group_name), users=users) except Exception, e: logger.error(e)
def roles(self, id_user, **kw): logger = logging.getLogger('UsersController.roles') try: user = dbs.query(SapnsUser).get(int(id_user)) roles = [] for r in dbs.query(SapnsRole).order_by(SapnsRole.group_name): #r = SapnsRole() has_role = dbs.query(SapnsUserRole).\ filter(and_(SapnsUserRole.role_id == r.group_id, SapnsUserRole.user_id == user.user_id, )).\ first() roles.append( dict( id=r.group_id, name=r.group_name, selected=has_role != None, )) return dict(page='User roles', came_from=kw.get('came_from'), user=dict(id=user.user_id, name=user.user_name), roles=roles) except Exception, e: logger.error(e)
def roles(self, id_user, **kw): logger = logging.getLogger('UsersController.roles') try: user = dbs.query(SapnsUser).get(int(id_user)) roles = [] for r in dbs.query(SapnsRole).order_by(SapnsRole.group_name): #r = SapnsRole() has_role = dbs.query(SapnsUserRole).\ filter(and_(SapnsUserRole.role_id == r.group_id, SapnsUserRole.user_id == user.user_id, )).\ first() roles.append(dict(id=r.group_id, name=r.group_name, selected=has_role != None, )) return dict(page='User roles', came_from=kw.get('came_from'), user=dict(id=user.user_id, name=user.user_name), roles=roles) except Exception, e: logger.error(e)
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 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 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 ref_order_save(self, attributes='', came_from=''): # save reference order attributes = sj.loads(attributes) cls_title = None for attr in attributes: attribute = dbs.query(SapnsAttribute).get(attr['id']) if not cls_title: cls_title = attribute.class_.title attribute.reference_order = attr['order'] dbs.add(attribute) dbs.flush() if came_from: redirect(url(came_from)) else: redirect( url('/message', params=dict(message=_( 'Reference order for "%s" has been successfully updated' ) % cls_title, came_from='')))
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 add_update(code, description): # save "update" new_u = SapnsUpdates() new_u.code = code new_u.description = description new_u.exec_date = dt.datetime.now() dbs.add(new_u) dbs.flush()
def edit(self, cls, id_, **params): user = dbs.query(SapnsUser).get(request.identity['user'].user_id) id_user = int(id_) is_manager = u'managers' in request.identity['groups'] if user.user_id != id_user and not is_manager: redirect(url('/error')) user = dbs.query(SapnsUser).get(id_user) return dict(user=user, came_from=params.get('came_from'))
def user_groups(self, user_id): user = dbs.query(SapnsUser).get(int(user_id)) def _children_shortcuts(parent_id): sc_groups = [] for sc in dbs.query(SapnsShortcut).\ filter(and_(SapnsShortcut.user_id == user.user_id, SapnsShortcut.parent_id == parent_id, SapnsShortcut.permission_id == None, )).\ order_by(SapnsShortcut.order): sc_groups.append(dict(id=sc.shortcut_id, title=sc.title, children=_children_shortcuts(sc.shortcut_id))) return sc_groups db = user.get_dashboard() sc_groups = [dict(id=db.shortcut_id, title=db.title, children=_children_shortcuts(db.shortcut_id), )] return dict(sc_groups=sc_groups)
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 _all(): #logger.info('Getting all users...') users = [] for user in dbs.query(SapnsUser).order_by(SapnsUser.user_id): users.append(dict(id=user.user_id, display_name=user.display_name, user_name=user.user_name)) return users
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 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 _all(): #logger.info('Getting all users...') users = [] for user in dbs.query(SapnsUser).order_by(SapnsUser.user_id): users.append( dict(id=user.user_id, display_name=user.display_name, user_name=user.user_name)) return users
def __init__(self, username_or_email): #logger = logging.getLogger('ForgotPassword.__init__') self.u = dbs.query(SapnsUser).\ filter(or_(func.upper(SapnsUser.user_name) == func.upper(username_or_email), func.upper(SapnsUser.email_address) == func.upper(username_or_email), )).\ first() if not self.u: raise EUserDoesNotExist # generate a random password random.seed() s1 = hl.sha1('%6.6d' % random.randint(0, 999999)) self.new_password = '' for c in s1.hexdigest()[:random.randint(10, 15)]: if random.randint(0, 1): self.new_password += c.upper() else: self.new_password += c self.u.password = self.new_password dbs.add(self.u) dbs.flush() self.dst = [( self.u.email_address.encode('utf-8'), self.u.user_name.encode('utf-8'), )] # e-mail settings self.remitente = ( config.get('mail.e_mail'), config.get('mail.name'), ) # get e-mail templates self.env = Environment(loader=PackageLoader('sapns', 'templates'))
def copy(self, id, **kw): id_role = int(id) this_role = dbs.query(SapnsRole).get(id_role) came_from = kw.get('came_from', '/') roles = [] for r in dbs.query(SapnsRole).\ filter(SapnsRole.group_id != id_role).\ order_by(SapnsRole.display_name): #r = SapnsRole() roles.append(dict(id=r.group_id, name=r.group_name )) return dict(this_role=dict(id=this_role.group_id, name=this_role.group_name), roles=roles, page=_('Role privileges copy'), came_from=came_from)
def create_shortcuts(self, permission_id, **kw): permission = dbs.query(SapnsPermission).get(permission_id) return dict(page=_(u'Create shortcuts from permissions'), came_from=kw.get('came_from'), permission=dict(id=permission.permission_id, title=permission.display_name, name=permission.permission_name, ), )
def from_list(self, title, link): logger = logging.getLogger('shortcuts/from_list') try: # connected user user = dbs.query(SapnsUser).get(request.identity['user'].user_id) user.from_list(title, link) return dict(status=True) except Exception, 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 _children_shortcuts(parent_id): sc_groups = [] for sc in dbs.query(SapnsShortcut).\ filter(and_(SapnsShortcut.user_id == user.user_id, SapnsShortcut.parent_id == parent_id, SapnsShortcut.permission_id == None, )).\ order_by(SapnsShortcut.order): sc_groups.append(dict(id=sc.shortcut_id, title=sc.title, children=_children_shortcuts(sc.shortcut_id))) return sc_groups
def delete(self, id_shortcut, **params): logger = logging.getLogger(__name__ + '/delete') try: logger.info('Deleting shortcut [%s]' % id_shortcut) # the shortcut to be deleted sc = dbs.query(SapnsShortcut).get(id_shortcut) dbs.query(SapnsShortcut).\ filter(SapnsShortcut.shortcut_id == id_shortcut).\ delete() dbs.flush() _key = '%d_%d' % (sc.user_id, sc.parent_id) cache.get_cache('user_get_shortcuts').remove_value(key=_key) return dict(status=True) except Exception, e: logger.error(e) return dict(status=False)
def ins_order(self, cls, came_from='/'): user = dbs.query(SapnsUser).get(request.identity['user'].user_id) # check privilege on this class if not user.has_privilege(cls): redirect(url('/message', params=dict(message=_('Sorry, you do not have privilege on this class'), came_from=came_from))) class_ = SapnsClass.by_name(cls) return dict(page='insertion order', insertion=class_.insertion(), title=class_.title, came_from=url(came_from))
def reorder(self, id_sc, type_): logger = logging.getLogger('ShortcutsController.reorder') try: sc = dbs.query(SapnsShortcut).get(id_sc) logger.info('Reordering shortcut (%s %s)' % (sc, type)) sc.reorder(type_) return dict(status=True) except Exception, e: logger.error(e) return dict(status=False)
def ref_order_save(self, attributes='', came_from=''): # save reference order attributes = sj.loads(attributes) cls_title = None for attr in attributes: attribute = dbs.query(SapnsAttribute).get(attr['id']) if not cls_title: cls_title = attribute.class_.title attribute.reference_order = attr['order'] dbs.add(attribute) dbs.flush() if came_from: redirect(url(came_from)) else: redirect(url('/message', params=dict(message=_('Reference order for "%s" has been successfully updated') % cls_title, came_from='')))
def ref_order(self, cls, came_from='/'): user = dbs.query(SapnsUser).get(request.identity['user'].user_id) # check privilege on this class if not user.has_privilege(cls): redirect(url('/message', params=dict(message=_('Sorry, you do not have privilege on this class'), came_from=came_from))) class_ = SapnsClass.by_name(cls) return dict(page='reference order', reference=class_.reference(all=True), came_from=came_from)
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 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 __init__(self, username_or_email): #logger = logging.getLogger('ForgotPassword.__init__') self.u = dbs.query(SapnsUser).\ filter(or_(func.upper(SapnsUser.user_name) == func.upper(username_or_email), func.upper(SapnsUser.email_address) == func.upper(username_or_email), )).\ first() if not self.u: raise EUserDoesNotExist # generate a random password random.seed() s1 = hl.sha1('%6.6d' % random.randint(0, 999999)) self.new_password = '' for c in s1.hexdigest()[:random.randint(10, 15)]: if random.randint(0, 1): self.new_password += c.upper() else: self.new_password += c self.u.password = self.new_password dbs.add(self.u) dbs.flush() self.dst = [(self.u.email_address.encode('utf-8'), self.u.user_name.encode('utf-8'),)] # e-mail settings self.remitente = (config.get('mail.e_mail'), config.get('mail.name'),) # get e-mail templates self.env = Environment(loader=PackageLoader('sapns', 'templates'))
def __call__(self): logger = logging.getLogger('TM_Test') managers = SapnsRole.by_name(u'managers') for usuario in managers.users_: logger.info(usuario.display_name) db = usuario.get_dashboard() for sc in db.children: logger.info(sc.title) sc.title = '_%s' % sc.title dbs.add(sc) dbs.flush() def attributes(cls): for attr in cls.attributes: logger.info(attr.name) attr.title = '*%s' % attr.title dbs.add(attr) dbs.flush() attributes(SapnsClass.by_name(u'alumnos')) attributes(SapnsClass.by_name(u'clientes'))
def share(self, id_sc=None, id_user=None, **params): logger = logging.getLogger(__name__ + '/share') try: logger.info('Sharing shortcut [%s]' % id) user = dbs.query(SapnsUser).get(id_user) if not user: raise Exception('User [%s] does not exist' % id_user) user.get_dashboard().add_child(id_sc) return dict(status=True) except Exception, e: logger.error(e) return dict(status=False)
def index(self): logger = logging.getLogger('RootController.index') if request.identity: user = dbs.query(SapnsUser).get(request.identity['user'].user_id) ep = user.entry_point() logger.info('entry-point: %s' % ep) if ep and ep != '/': redirect(url(ep)) # there is no "entry_point" defined home = config.get('app.home') if home and home != '/': redirect(url(home)) return dict()
def bookmark(self, id_shortcut, **params): logger = logging.getLogger(__name__ + '/bookmark') try: logger.info('Bookmarking shortcut [%s]' % id_shortcut) user = dbs.query(SapnsUser).get(request.identity['user'].user_id) dboard = user.get_dashboard() dboard.add_child(id_shortcut) _key = '%d_%d' % (user.user_id, dboard.shortcut_id) cache.get_cache('user_get_shortcuts').remove_value(key=_key) return dict(status=True) except Exception, e: logger.error(e) return dict(status=False) #, message=str(e).decode('utf-8'))
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 ref_order(self, cls, came_from='/'): user = dbs.query(SapnsUser).get(request.identity['user'].user_id) # check privilege on this class if not user.has_privilege(cls): redirect( url('/message', params=dict(message=_( 'Sorry, you do not have privilege on this class'), came_from=came_from))) class_ = SapnsClass.by_name(cls) return dict(page='reference order', reference=class_.reference(all=True), came_from=came_from)
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 ins_order(self, cls, came_from='/'): user = dbs.query(SapnsUser).get(request.identity['user'].user_id) # check privilege on this class if not user.has_privilege(cls): redirect( url('/message', params=dict(message=_( 'Sorry, you do not have privilege on this class'), came_from=came_from))) class_ = SapnsClass.by_name(cls) return dict(page='insertion order', insertion=class_.insertion(), title=class_.title, came_from=url(came_from))
def setUp(self): """Prepare model test fixture.""" try: new_attrs = {} new_attrs.update(self.attrs) new_attrs.update(self.do_get_dependencies()) self.obj = self.klass(**new_attrs) DBSession.add(self.obj) DBSession.flush() return self.obj except: DBSession.rollback() raise
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 grid_actions(self, cls, **kw): user = dbs.query(SapnsUser).get(int(request.identity['user'].user_id)) # actions for this class cls_ = SapnsClass.by_name(cls) actions_ = {} for action in cls_.sorted_actions(user.user_id): if action['type'] in [SapnsPermission.TYPE_NEW, SapnsPermission.TYPE_EDIT, SapnsPermission.TYPE_DELETE, SapnsPermission.TYPE_DOCS, SapnsPermission.TYPE_PROCESS, ]: actions_[action['name']] = action ch_cls_ = SapnsClass.by_name(cls, parent=False) for action_ch in ch_cls_.sorted_actions(user.user_id): if action_ch['type'] in [SapnsPermission.TYPE_NEW, SapnsPermission.TYPE_EDIT, SapnsPermission.TYPE_DELETE, SapnsPermission.TYPE_DOCS, SapnsPermission.TYPE_PROCESS, ]: actions_.update({action_ch['name']: action_ch}) def cmp_act(x, y): if x.pos == y.pos: return cmp(x.title, y.title) else: return cmp(x.pos, y.pos) return dict(status=True, actions=sorted(actions_.values(), cmp=cmp_act))
def ins_order_save(self, attributes='', title='', came_from=''): # save insertion order attributes = sj.loads(attributes) title_saved = False cls_title = None for attr in attributes: attribute = dbs.query(SapnsAttribute).get(attr['id']) if not cls_title: cls_title = attribute.class_.title attribute.title = attr['title'] attribute.insertion_order = attr['order'] attribute.required = attr['required'] attribute.visible = attr['visible'] dbs.add(attribute) if not title_saved: title_saved = True attribute.class_.title = title dbs.add(attribute.class_) dbs.flush() if came_from: redirect(url(came_from)) else: redirect(url('/message', params=dict(message=_('Insertion order for "%s" has been successfully updated') % cls_title, came_from='')))
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 create_data_exploration(): managers = SapnsRole.by_name(ROLE_MANAGERS) #managers = SapnsRole() logger = logging.getLogger('lib.sapns.util.create_data_exploration') tables = extract_model(all=True) #['tables'] for us in dbs.query(SapnsUser).\ join((SapnsUserRole, and_(SapnsUserRole.user_id == SapnsUser.user_id, SapnsUserRole.role_id == managers.group_id, ))): create_dashboards(us) data_ex = us.get_dataexploration() sc_sapns = data_ex.by_order(0) sc_project = data_ex.by_order(1) # data exploration/project for i, tbl in enumerate(tables): cls = dbs.query(SapnsClass).\ filter(SapnsClass.name == tbl['name']).\ first() # look for this table "list" action act_table = dbs.query(SapnsPermission).\ filter(and_(SapnsPermission.type == SapnsPermission.TYPE_LIST, SapnsPermission.class_id == cls.class_id)).\ first() if not act_table: act_table = SapnsPermission() act_table.permission_name = '%s#%s' % (cls.name, SapnsPermission.TYPE_LIST) act_table.display_name = unicode(l_('List')) act_table.type = SapnsPermission.TYPE_LIST act_table.class_id = cls.class_id dbs.add(act_table) dbs.flush() # add to "managers" role managers.permissions_.append(act_table) dbs.flush() # project sc_parent = sc_project.shortcut_id if cls.name.startswith('sp_'): # sapns sc_parent = sc_sapns.shortcut_id sc_table = dbs.query(SapnsShortcut).\ filter(and_(SapnsShortcut.parent_id == sc_parent, SapnsShortcut.permission_id == act_table.permission_id, SapnsShortcut.user_id == us.user_id, )).\ first() # does this user have this class shortcut? if not sc_table: sc_table = SapnsShortcut() sc_table.title = tbl['name'] sc_table.parent_id = sc_parent sc_table.user_id = us.user_id sc_table.permission_id = act_table.permission_id sc_table.order = i dbs.add(sc_table) dbs.flush() else: logger.info('Shortcut for "%s" already exists' % cls.title) # TODO: sort (alphabetically) shortcuts inside "data exploration" logger.info('Sorting shortcuts inside "data exploration"') i = 0 for sc in dbs.query(SapnsShortcut).\ filter(SapnsShortcut.parent_id == sc_project.shortcut_id).\ order_by(SapnsShortcut.title): sc.order = i dbs.add(sc) dbs.flush() i += 1
def create_dashboards(us): logger = logging.getLogger('lib.sapns.util.create_dashboards') #us = dbs.query(SapnsUser).get(id_user) logger.info('Creating dashboard for "%s"' % us.display_name) # user's dashboard dboard = us.get_dashboard() if not dboard: dboard = SapnsShortcut() dboard.user_id = us.user_id dboard.parent_id = None dboard.title = unicode(l_('Dashboard')) dboard.order = 0 dbs.add(dboard) dbs.flush() # data exploration data_ex = SapnsShortcut() data_ex.title = unicode(l_('Data exploration')) data_ex.parent_id = dboard.shortcut_id data_ex.user_id = us.user_id data_ex.order = 0 dbs.add(data_ex) dbs.flush() # Data exploration/Sapns sc_sapns = SapnsShortcut() sc_sapns.title = 'Sapns' sc_sapns.parent_id = data_ex.shortcut_id sc_sapns.user_id = us.user_id sc_sapns.order = 0 dbs.add(sc_sapns) # Data exploration/Project sc_project = SapnsShortcut() sc_project.title = config.get('app.name', unicode(l_('Project'))) sc_project.parent_id = data_ex.shortcut_id sc_project.user_id = us.user_id sc_project.order = 1 dbs.add(sc_project) dbs.flush() else: logger.info('Dashboard already exists')
def create_action(name, type_): action = dbs.query(SapnsPermission).\ filter(and_(SapnsPermission.class_id == klass.class_id, SapnsPermission.type == type_)).\ first() if not action: action = SapnsPermission() action.permission_name = '%s#%s' % (klass.name, name.lower()) action.display_name = name action.type = type_ action.class_id = klass.class_id dbs.add(action) dbs.flush() # add this action to "managers" role managers.permissions_.append(action) dbs.flush() elif action.type == SapnsPermission.TYPE_LIST: for s in action.shortcuts: s.title = action.class_.title dbs.add(s) dbs.flush()