def index(self, **kw): feegrouups = DBSession.query(FeeGroup).filter(FeeGroup.active == 0).order_by(FeeGroup.order) companies = DBSession.query(Company, Currency).filter(and_(Company.active == 0, Currency.active == 0, Company.currency_id == Currency.id, )).order_by(Company.name) result = { 'feegroups' : feegrouups, 'companies' : companies, 'is_fin' : has_permission('FIN_VIEW_ALL'), } if has_permission('FIN_VIEW_ALL'): # if FIN team teams = DBSession.query(LogicTeam).filter(LogicTeam.active == 0).order_by(LogicTeam.order).all() else: # get the user's belonging team teams = [] try: mp = DBSession.query(Permission).filter(Permission.permission_name == 'MANAGER_VIEW').one() for g in request.identity["user"].groups: if mp in g.permissions and g.logicteams: teams.extend(g.logicteams) except: traceback.print_exc() pass result['teams'] = teams return result
def __actions__(self, obj): """Override this function to define how action links should be displayed for the given record.""" bool_ultimo = obj.bool_ultimo primary_fields = self.__provider__.get_primary_fields(self.__entity__) pklist = '/'.join(map(lambda x: str(getattr(obj, x)), primary_fields)) if bool_ultimo == 1: cod_item = obj.cod_item value = '<div>' if has_permission('editar_item'): value = value + '<div><a class="edit_link" href="'+pklist+'/edit" style="text-decoration:none">edit</a></div>' if has_permission('eliminar_relacion'): value = value + '<div><form method="POST" action="'+pklist+'" class="button-to"><input type="hidden" name="_method" value="DELETE" /><input class="delete-button" onclick="return confirm(\'Are you sure?\');" value="delete" type="submit" style="background-color: transparent; float:left; border:0; color: #286571; display: inline; margin: 0; padding: 0;"/></form></div>' value = value + '<div><a class="relacion_link" href="../relacions/?iid='+pklist+'">Relaciones </a><br/><a class="versiones_link" href="./?codi='+cod_item+'">Revertir</a></div></div>' else: id_item_rev = DBSession.query(Item).filter_by(cod_item = obj.cod_item, bool_ultimo = 1).one().id_item ids = str(pklist) + "-" + str(id_item_rev) href = "./revertir/?ids=" + ids value = '<div><div><a class="edit_link" href="'+pklist+'/edit" style="text-decoration:none">edit</a>'\ '</div><div>'\ '<form method="POST" action="'+pklist+'" class="button-to">'\ '<input type="hidden" name="_method" value="DELETE" />'\ '<input class="delete-button" onclick="return confirm(\'Are you sure?\');" value="delete" type="submit" '\ 'style="background-color: transparent; float:left; border:0; color: #286571; display: inline; margin: 0; padding: 0;"/>'\ '</form>'\ '<a class="relacion_link" href="../relacions/?iid='+pklist+'">Relaciones </a>'\ '<a class="volver_link" href="'+href+'">Volver a</a>'\ '</div></div>' return value
def __actions__(self, obj): """Override this function to define how action links should be displayed for the given record.""" bool_ultimo = obj.bool_ultimo primary_fields = self.__provider__.get_primary_fields( self.__entity__) pklist = '/'.join( map(lambda x: str(getattr(obj, x)), primary_fields)) if bool_ultimo == 1: cod_item = obj.cod_item value = '<div>' if has_permission('editar_item'): value = value + '<div><a class="edit_link" href="' + pklist + '/edit" style="text-decoration:none">edit</a></div>' if has_permission('eliminar_relacion'): value = value + '<div><form method="POST" action="' + pklist + '" class="button-to"><input type="hidden" name="_method" value="DELETE" /><input class="delete-button" onclick="return confirm(\'Are you sure?\');" value="delete" type="submit" style="background-color: transparent; float:left; border:0; color: #286571; display: inline; margin: 0; padding: 0;"/></form></div>' value = value + '<div><a class="relacion_link" href="../relacions/?iid=' + pklist + '">Relaciones </a><br/><a class="versiones_link" href="./?codi=' + cod_item + '">Revertir</a></div></div>' else: id_item_rev = DBSession.query(Item).filter_by( cod_item=obj.cod_item, bool_ultimo=1).one().id_item ids = str(pklist) + "-" + str(id_item_rev) href = "./revertir/?ids=" + ids value = '<div><div><a class="edit_link" href="'+pklist+'/edit" style="text-decoration:none">edit</a>'\ '</div><div>'\ '<form method="POST" action="'+pklist+'" class="button-to">'\ '<input type="hidden" name="_method" value="DELETE" />'\ '<input class="delete-button" onclick="return confirm(\'Are you sure?\');" value="delete" type="submit" '\ 'style="background-color: transparent; float:left; border:0; color: #286571; display: inline; margin: 0; padding: 0;"/>'\ '</form>'\ '<a class="relacion_link" href="../relacions/?iid='+pklist+'">Relaciones </a>'\ '<a class="volver_link" href="'+href+'">Volver a</a>'\ '</div></div>' return value
def listado(self, page=1): """Metodo para listar todos los Proyectos existentes de la base de datos""" try: proyectos = [] if predicates.has_permission('administracion'): proyectos = DBSession.query(Proyecto).order_by( Proyecto.id_proyecto) elif predicates.has_permission('lider_proyecto'): usuario = DBSession.query(Usuario).filter_by( nombre_usuario=request.identity['repoze.who.userid'] ).first() proyectos = usuario.proyectos currentPage = paginate.Page(proyectos, page, items_per_page=10) except SQLAlchemyError: flash(_("No se pudo acceder a Proyectos! SQLAlchemyError..."), 'error') redirect("/admin") except (AttributeError, NameError): flash( _("No se pudo acceder a Proyectos! Hay Problemas con el servidor..." ), 'error') redirect("/admin") return dict(proyectos=currentPage.items, page='listado_proyecto', currentPage=currentPage)
def __actions__(self, obj): """Override this function to define how action links should be displayed for the given record.""" primary_fields = self.__provider__.get_primary_fields(self.__entity__) pklist = '/'.join(map(lambda x: str(getattr(obj, x)), primary_fields)) value = '<div>' if has_permission('editar_proyecto'): value = value + '<div><a class="edit_link" href="'+pklist+'/edit" style="text-decoration:none">edit</a></div>' if has_permission('eliminar_proyecto'): value = value + '<div><form method="POST" action="'+pklist+'" class="button-to"><input type="hidden" name="_method" value="DELETE" /><input class="delete-button" onclick="return confirm(\'Está seguro que desea eliminar?\');" value="delete" type="submit" style="background-color: transparent; float:left; border:0; color: #286571; display: inline; margin: 0; padding: 0;"/></form></div>' value = value + '<div><a class="fases_link" href="../fases/?pid='+pklist+'">Fases</a></div></div>' return value
def __actions__(self, obj): """Override this function to define how action links should be displayed for the given record.""" primary_fields = self.__provider__.get_primary_fields(self.__entity__) pklist = '/'.join(map(lambda x: str(getattr(obj, x)), primary_fields)) value = '<div>' if has_permission('editar_fase'): value = value + '<div><a class="edit_link" href="'+pklist+'/edit" style="text-decoration:none">edit</a></div>' if has_permission('eliminar_fase'): value = value + '<div><form method="POST" action="'+pklist+'" class="button-to"><input type="hidden" name="_method" value="DELETE" /><input class="delete-button" onclick="return confirm(\'Are you sure?\');" value="delete" type="submit" style="background-color: transparent; float:left; border:0; color: #286571; display: inline; margin: 0; padding: 0;"/></form></div>' value = value + '<div><a class="itmes_link" href="../items/?fid='+pklist+'">Items</a><br/><a class="lineas_link" href="../lineabases/?fid='+pklist+'">Linea Base</a></div></div>' return value
class ResultsController(BaseController): @ActionProtector(has_permission('admin')) def index(self): c.attempts = Session.query(Attempt).order_by(desc(Attempt.date)).all() return render('/admin/results/index.html') @ActionProtector(has_permission('admin')) def show(self, id): attempt = Session.query(Attempt).get(int(id)) if attempt and attempt.is_attempted: c.attempt = attempt return render('/admin/results/show.html') else: redirect(url(controller='results', action='index'))
def check_fase_permiso(self, id_fase, permiso_name,nuleable=False): """ Controla si el usuario que actualmente se encuentra logeado posee el deteminado permiso sobre una fase. @type id_fase : Integer @param id_fase : Identificador de la fase @type permiso_name : String @param permiso_name : Nombre del permiso @type nuleable : Boolean @param nuleable : Variable de control del valor de retorno. Si es True y el usuario no posee permisos retorna None @rtype : Predicates @return : retorna las credenciales del usuario """ current_user = self.get_current_user() #Se obtiene la fase actual fase = DBSession.query(Fase).get(id_fase) #se recupera el rol del lider del proyecto rol = util.get_rol_by_codigo('lider_' + str(fase.proyecto)) #si el usuario es lider del proyecto se salta los controles if util.usuario_has_rol(current_user.usuario_id, rol) : return predicates.has_permission(permiso_name) usuario_permiso_fase = DBSession.query(UsuarioPermisoFase).\ filter(UsuarioPermisoFase.usuario_id == RolUsuario.usuario_id).\ filter(UsuarioPermisoFase.fase_id == id_fase).\ filter(Permiso.permiso_id == UsuarioPermisoFase.permiso_id).\ filter(Permiso.nombre == permiso_name).\ filter(RolUsuario.usuario_id == current_user.usuario_id).\ all() if (len(usuario_permiso_fase) != 0): return predicates.has_permission(permiso_name) elif nuleable == False: #return predicates.has_permission(permiso_name+' '+str(id_proyecto)) return predicates.has_permission('Sin permiso') else: return None
def permission_met(menu): """ This is one of the more complicated methods. It works recursively. When called, it is given the root of the controller hierarchy. It looks for the path to the menu entry, and checks everything that it can along the way: allow_only on all controllers, and the (optional) permission on the method itself (which must be given to the @menu decorator or menu_append, see the README for details why and a workaround). """ global rootcon retval = True if not rootcon: pname = '%s.controllers.root' % (config['package'].__name__) __import__(pname) rootcon = sys.modules[pname].RootController # Check to see if specific menu permission has been set permission = menu._permission if type(permission) is str: try: has_permission(permission).check_authorization(request.environ) return True except NotAuthorizedError: return False elif permission is not None: try: permission.check_authorization(request.environ) return True except: return False else: # No specific menu permission has been set, walk the tree lpath = menu._url.split('/')[1:] currcon = rootcon for component in lpath: if hasattr(currcon, 'allow_only'): try: getattr(currcon, 'allow_only').check_authorization(request.environ) except: return False if hasattr(currcon, component): currcon = getattr(currcon, component) else: break return True
class DebugController(TGController): allow_only = has_permission('manage') @expose('sauce.templates.page') def index(self, *args, **kwargs): content = literal(u'<h2></h2><ul>' '<li><a href="%(url)s/environ">request.environ</a></li>' '<li><a href="%(url)s/identity">request.identity</a></li>' '<li><a href="%(url)s/exception">DebugException</a></li>' '<li><a href="%(url)s/sendmail">sendmail</a></li>' '</ul>' % dict(url=url(self.mount_point))) return dict(page=u'debug', page_title=u'Debugging', page_header=u'Debugging', content=content) @expose('sauce.templates.page') def environ(self, *args, **kwargs): content = literal(u'<pre>') + escape(pformat(request.environ)) + literal(u'</pre>') return dict(page=u'debug', page_title=u'request.environ', page_header=u'request.environ', content=content) @expose('sauce.templates.page') def identity(self, *args, **kwargs): content = literal(u'<pre>') + escape(pformat(dict(request.environ.get('repoze.who.identity', dict()).items()))) + literal(u'</pre>') return dict(page=u'debug', page_title=u'request.identity', page_header=u'request.identity', content=content) @expose() def exception(self, *args, **kwargs): # pragma: no cover raise DebugException(*args, **kwargs) @expose() def sendmail(self, *args, **kwargs): return sendmail('Subject', 'Bödy', ['*****@*****.**', None], '*****@*****.**', cc_managers=True)
class InvisibleArena(TGController): allow_only = has_permission('manage') @navbar('Arena') @expose('genshi:tgext.menu.test.templates.index') def index(self, *p, **kw): return dict()
def protect_obj_modify(protected_obj=None): p = protected_obj if p: if not Any(is_user(p.user.user_name), has_permission('dmirr_admin'), in_group(p.group.group_name)): raise NotAuthorizedError
def get_failures(self): """ Retourne la liste (au format JSON) des collecteurs Vigilo en panne. Déclenche un appel à la méthode flash si cette liste est non vide. """ # On vérifie que l'utilisateurs dispose des permissions appropriées All( not_anonymous(msg=_("You need to be authenticated")), Any( config.is_manager, has_permission('%s-access' % config.app_name.lower()), msg=_("You don't have access to %s") % config.app_name ) ).check_authorization(request.environ) # On récupère la liste des connecteurs en panne failures = self.check_connectors_freshness() # Si cette liste n'est pas vide, on affiche un message à l'utilisateur if failures: flash(_( 'Vigilo has detected a breakdown on the following ' 'collector(s): %(list)s' ) % {'list': ', '.join(failures)}, 'error' ) # Dans les 2 cas (liste vide ou non), on la retourne au format JSON return dict(failures=failures)
def protect_product_release_obj(protected_obj=None): p = protected_obj if p: if not Any(is_user(p.product.project.user.user_name), has_permission('dmirr_admin'), in_group(p.product.project.group.group_name)): raise NotAuthorizedError
def __init__(self, *args, **kw): # /event/url/submissions self.event = kw.get('event', None) # /event/url/lesson/id/submissions self.lesson = kw.get('lesson', None) # /event/url/sheet/id/assignment/id/submissions self.assignment = kw.get('assignment', None) # /event/url/sheet/id/submissions self.sheet = kw.get('sheet', None) if self.event: pass elif self.lesson: self.event = self.lesson.event elif self.assignment: self.event = self.assignment.sheet.event elif self.sheet: self.event = self.sheet.event else: log.warn('SubmissionController without any filter') flash('You can not view Submissions without any constraint.', 'error') abort(400) # Allow access for event teacher and lesson teacher self.allow_only = Any( has('teachers', self.event), has('tutors', self.lesson), # has_teacher(self.event), # has_teachers(self.event), # has_teacher(self.lesson), has_permission('manage'), msg=u'You have no permission to manage this Lesson' ) self.table = SubmissionTable(DBSession) self.table_filler = SubmissionTableFiller(DBSession, lesson=self.lesson)
def _cal(self, context, done_rs, notdone_rs): # handle the cal fields updated_rs = {} while len(notdone_rs) > 0: ids_set = set(map(unicode, done_rs.keys())) tmp = [] for obj in notdone_rs: feeitem = getattr(obj, 'feeitem', DBSession.query(FeeItem).get(obj.feeitem_id)) args_list = map(lambda v: unicode(v.strip()), feeitem.args.split(",")) args_ids = filter(lambda a : a.isdigit(), args_list) args_set = set(args_ids) if not args_set.issubset(ids_set): # if not all the args is ready ,put it to the next round tmp.append(obj) continue # if all the params is fulfill ,the cal the val # 1. get the fomula fun = eval(feeitem.expression.exp) # 2, prepare the args value attrs = ['actual_value', 'budget_value'] if has_permission('FIN_VIEW_ALL') else ['forecast_value'] for attr in attrs: vals = [] for a in args_list: if a.isdigit() : vals.append(float(getattr(done_rs[a], attr) or 0.0)) elif a.startswith('$') : vals.append(context[a[1:]]) # 3. run the exp and set the value setattr(obj, attr, fin_helper.round2int(fun(*vals))) done_rs[unicode(obj.feeitem_id)] = obj updated_rs[unicode(obj.feeitem_id)] = obj notdone_rs = tmp return updated_rs
def index(self, **kw): companies = DBSession.query(Company, Currency).filter(and_(Company.active == 0, Currency.active == 0, Company.currency_id == Currency.id, )).order_by(Company.name) subline = DBSession.query(Subline).filter(and_(Subline.active == 0)).order_by(Subline.label) saletype = DBSession.query(SaleType).filter(and_(SaleType.active == 0)).order_by(SaleType.label) result = { 'companies' : companies, 'subline' : subline, 'saletype' : saletype, } if has_permission('FIN_VIEW_ALL'): # if FIN team teams = DBSession.query(LogicTeam).filter(and_(LogicTeam.active == 0, LogicTeam.for_sale == 0)).order_by(LogicTeam.order).all() result['is_fin'] = True else: # get the user's belonging team result['is_fin'] = False teams = [] try: mp = DBSession.query(Permission).filter(Permission.permission_name == 'MANAGER_VIEW').one() for g in request.identity["user"].groups: if mp in g.permissions and g.logicteams: teams.extend(g.logicteams) except: traceback.print_exc() pass result['teams'] = teams return result
def application(environ, start_response): req = Request(environ) resp = Response() resp.content_type = 'text/plain' resp.body = 'anonymous' if req.path_info == '/auth' and not environ.get('repoze.what.credentials'): return exc.HTTPUnauthorized()(environ, start_response) if req.path_info == '/secure': ident = environ.get('repoze.who.identity', {}) body = 'repoze.who.identity = {\n' for k, v in ident.items(): if k.lower() != 'password': body += ' %r: %r,\n' % (k, v) body += '}\n\n' cred = environ.get('repoze.what.credentials', {}) body += 'repoze.what.credentials = {\n' for k, v in cred.items(): body += ' %r: %r,\n' % (k, v) body += '}\n\n' for group in ('svn', 'bureau', 'other'): body += 'in_group(%r) == %s\n' % (group, in_group(group).is_met(environ)) for perm in ('read', 'write'): body += 'has_permision(%r) == %s\n' % ( perm, has_permission(perm).is_met(environ)) resp.body = body return resp(environ, start_response)
class AccountController(BaseController): def login(self): """ This is where the login form should be rendered. Without the login counter, we won't be able to tell if the user has tried to log in with wrong credentials """ identity = request.environ.get('repoze.who.identity') came_from = str(request.GET.get('came_from', '')) or \ url(controller='account', action='welcome') if identity: redirect(url(came_from)) else: c.came_from = came_from c.login_counter = request.environ['repoze.who.logins'] + 1 return render('/derived/account/login.html') @ActionProtector(not_anonymous()) def welcome(self): """ Greet the user if she logged in successfully or redirect back to the login form otherwise(using ActionProtector decorator). """ identity = request.environ.get('repoze.who.identity') return 'Welcome back %s' % identity['repoze.who.userid'] @ActionProtector(not_anonymous()) def test_user_access(self): return 'You are inside user section' @ActionProtector(has_permission('admin')) def test_admin_access(self): return 'You are inside admin section'
class NetworkController(CrudRestController): # The predicate that must be met for all the actions in this controller: allow_only = has_permission( 'manage', msg=l_('Only for people with the "manage" permission')) model = Network class new_form_type(AddRecordForm): __model__ = Network __omit_fields__ = ['id', 'version', 'timestamp', 'user_id', 'ips'] __field_attrs__ = {'prefix': {'label': 'Prefix/Netmask'}} __base_validator__ = NetworkValidator netaddr = TextField prefix = TextField notes = TextField class edit_form_type(EditableForm): __model__ = Network __omit_fields__ = ['id', 'version', 'timestamp', 'user_id', 'ips'] __field_attrs__ = {'prefix': {'label_text': 'Prefix/Netmask'}} __base_validator__ = NetworkValidator netaddr = TextField prefix = TextField notes = TextField class edit_filler_type(EditFormFiller): __model__ = Network class table_type(TableBase): __model__ = Network __omit_fields__ = ['id', 'version', 'timestamp', 'user_id', 'ips'] class table_filler_type(TableFiller): __model__ = Network
def admin(self,id=None,page=1): def asort(sort,querystr): feilds ={'1':'Invoice.id', '2':'Invoice.customer_id', '3':'Invoice.date_time', '4':'Invoice.total_price', '5':'Invoice.Description',} if sort != '': if session['invoice_sort_togle'][sort]: session['invoice_sort_togle'][sort] = False direction = '.desc()' else: session['invoice_sort_togle'][sort] = True direction = '.asc()' querystr += ".order_by(%s%s)"%(feilds[sort],direction) session['invoice_sort'] = sort session['invoice_sort_direction']=direction session.save() elif 'invoice_sort' in session: sort = session['invoice_sort'] direction = session['invoice_sort_direction'] querystr += ".order_by(%s%s)"%(feilds[sort],direction) return querystr came_from = str(request.GET.get('came_from', '')) identity = request.environ.get('repoze.who.identity') c.menu_items = h.top_menu(self.menu_items,_('Shop online')) if came_from == 'removeproduct': h.flash('To delete a product find it in the table and press on the Delete link') elif came_from == 'editproduct': h.flash('To Edit a product details find it in the table below and press on the Edit link') sort = str(request.GET.get('sort','')) if 'invoice_sort_togle' not in session: session['invoice_sort_togle']={'1':True, '2':True, '3':True, '4':True, '5':True,} session.save() querystr='' if is_met(has_permission('view_invoice')): Uc = aliased(User) Us = aliased(User) if 'invoice_querystr' in session: querystr = asort(sort,querystr) invoices = eval(session['invoice_querystr']+querystr) c.paginator = paginate.Page(invoices, page=int(request.params.get('page', page)), items_per_page = 10) html = render('/derived/invoice/staff/index.html') return htmlfill.render(html, defaults=session['invoice_search_values'], errors={}) else: querystr = "Session.query(Invoice).filter(Invoice.deleted==False)" querystr = asort(sort,querystr) invoices = eval(querystr) c.paginator = paginate.Page(invoices, page=int(request.params.get('page', page)), items_per_page = 10) return render('/derived/invoice/staff/index.html')
def index( self , **kw ): ws = [OrderHeader.active == 0] if kw.get( "no", False ) : ws.append( OrderHeader.no.op( "ilike" )( "%%%s%%" % kw["no"] ) ) if kw.get( "customerpo", False ) : ws.append( OrderHeader.customerpo.op( "ilike" )( "%%%s%%" % kw["customerpo"] ) ) if kw.get( "vendorpo", False ) : ws.append( OrderHeader.vendorpo.op( "ilike" )( "%%%s%%" % kw["vendorpo"] ) ) if kw.get( "status", False ) : ws.append( OrderHeader.status == kw["status"] ) if kw.get( "printShopId", False ) : ws.append( OrderHeader.printShopId == kw["printShopId"] ) if kw.get( "create_time_from", False ) : ws.append( OrderHeader.createTime >= kw["create_time_from"] ) if kw.get( "create_time_to", False ) : ws.append( OrderHeader.createTime <= kw["create_time_from"] ) if kw.get( "divisionId", False ) : ws.extend( [OrderHeader.id == OrderDetail.headerId, OrderDetail.active == ACTIVE, OrderDetail.divisionId == kw['divisionId']] ) if kw.get( "brandId", False ) : ws.extend( [OrderHeader.id == OrderDetail.headerId, OrderDetail.active == ACTIVE, OrderDetail.brandId == kw['brandId']] ) if kw.get( "categoryId", False ) : ws.extend( [OrderHeader.id == OrderDetail.headerId, OrderDetail.active == ACTIVE, OrderDetail.categoryId == kw['categoryId']] ) if not has_permission( "MAIN_ORDERING_CHECKING_ALL" ): ws.append( OrderHeader.createById == request.identity["user"].user_id ) result = qry( OrderHeader ).filter( and_( *ws ) ).order_by( desc( OrderHeader.createTime ) ).all() ps = qry( PrintShop ).filter( and_( PrintShop.active == 0 ) ).order_by( PrintShop.name ) is_admin = False for g in request.identity["user"].groups : if g.flag == 'ADMIN' : is_admin = True break return { "result" : result , "values" : kw, "widget" : order_search_form , "printshops" : ps , "is_admin" : is_admin}
def index(self): admin=False if predicates.not_anonymous(): if predicates.has_permission('admin'): admin=True drivers = DBSession.query(Driver).order_by('name') return dict(drivers=drivers, num_items=drivers.count(), admin=admin)
def edit(self,id): if is_met(has_permission(u'edit_invoice')): return render_edit_form_admin(self.menu_items,id=id) else: #check to see if the user is the owner of the invoice and invoice is pending the show edit form #check to see if staff is editing the form h.flash(_('You don not have enough permission to edit invoice')) return redirect(url(controller='invoice',action='index'))
def index(self): admin=False if predicates.not_anonymous(): if predicates.has_permission('admin'): admin=True arches = DBSession.query(Arch).order_by('name') return dict(arches=arches, num_items=arches.count(), admin=admin)
def index(self): admin=False if predicates.not_anonymous(): if predicates.has_permission('admin'): admin=True kernels = DBSession.query(Kernel).order_by('name') return dict(kernels=kernels, num_items=kernels.count(), admin=admin)
def index(self): admin=False if predicates.not_anonymous(): if predicates.has_permission('admin'): admin=True osfamilies = DBSession.query(OSFamily).order_by('name') return dict(osfamilies=osfamilies, num_items=osfamilies.count(), admin=admin)
def __init__(self, event): self.event = event self.allow_only = Any( user_is_in('teachers', self.event), user_is_in('tutors', self.event), has_permission('manage'), msg=u'You have no permission to manage Lessons for this Event')
def default(self, *args): admin=False if predicates.not_anonymous(): if predicates.has_permission('admin'): admin=True kernel_name = args[0] kernel = Kernel.by_kernel_name(kernel_name) return dict(kernel=kernel, admin=admin)
def default(self, *args): admin=False if predicates.not_anonymous(): if predicates.has_permission('admin'): admin=True arch_name = args[0] arch = Arch.by_arch_name(arch_name) return dict(arch=arch, admin=admin)
def default(self, *args): admin=False if predicates.not_anonymous(): if predicates.has_permission('admin'): admin=True drivertype_name = args[0] drivertype = DriverType.by_drivertype_name(drivertype_name) return dict(drivertype=drivertype, admin=admin)
def new(self): if is_met(has_permission("add_user")): return render_form(self.menu_items, action="create", add_number_of_emails=1) if is_met(is_anonymous()): c.menu_items = h.top_menu(self.menu_items, _("Customers")) c.came_from = str(request.GET.get("came_from", "")) or url(controller="home", action="index") if request.GET.get("came_from", None): h.flash(_("After filling the from you will be sent back to your shopping cart")) return render("/derived/user/new.html")
class AdminController(BaseController): allow_only = has_permission(constants.permission_admin_name) @expose('turbotequila.templates.admin') def index(self, *args, **kw): return { 'page': 'admin', 'admin_items': [m.lower() for m in model.admin_models] }
def __init__(self, event): self.event = event self.allow_only = Any( user_is_in('teachers', self.event), user_is_in('tutors', self.event), has_permission('manage'), msg=u'You have no permission to manage Lessons for this Event' )
def default(self, *args): admin=False if predicates.not_anonymous(): if predicates.has_permission('admin'): admin=True license_name = args[0] license = License.by_license_name(license_name) return dict(license=license, admin=admin)
def listado(self,page=1): """Metodo para listar todos los Proyectos existentes de la base de datos""" try: proyectos=[] if predicates.has_permission('administracion'): proyectos = DBSession.query(Proyecto).order_by(Proyecto.id_proyecto) elif predicates.has_permission('lider_proyecto'): usuario = DBSession.query(Usuario).filter_by(nombre_usuario=request.identity['repoze.who.userid']).first() proyectos = usuario.proyectos currentPage = paginate.Page(proyectos, page, items_per_page=10) except SQLAlchemyError: flash(_("No se pudo acceder a Proyectos! SQLAlchemyError..."), 'error') redirect("/admin") except (AttributeError, NameError): flash(_("No se pudo acceder a Proyectos! Hay Problemas con el servidor..."), 'error') redirect("/admin") return dict(proyectos=currentPage.items, page='listado_proyecto', currentPage=currentPage)
def _expose_wrapper(f, template, request_method=None, permission=None): """Returns a function that will render the passed in function according to the passed in template""" f.exposed = True # Shortcut for simple expose of strings if template == 'string' and not request_method and not permission: return f if request_method: request_method = request_method.upper() def wrapped_f(*args, **kwargs): if request_method and request_method != request.method: raise HTTPMethodNotAllowed().exception result = f(*args, **kwargs) tmpl = template if hasattr(request, 'override_template'): tmpl = request.override_template if tmpl == 'string': return result if tmpl == 'json': if isinstance(result, (list, tuple)): msg = ("JSON responses with Array envelopes are susceptible " "to cross-site data leak attacks, see " "http://wiki.pylonshq.com/display/pylonsfaq/Warnings") if config['debug']: raise TypeError(msg) warnings.warn(msg, Warning, 2) log.warning(msg) response.headers['Content-Type'] = 'application/json' return simplejson.dumps(result) if request.environ.get('paste.testing', False): # Make the vars passed from action to template accessible to tests request.environ['paste.testing_variables']['tmpl_vars'] = result # Serve application/xhtml+xml instead of text/html during testing. # This allows us to query the response xhtml as ElementTree XML # instead of BeautifulSoup HTML. # NOTE: We do not serve true xhtml to all clients that support it # because of a bug in Mootools Swiff as of v1.2.4: # https://mootools.lighthouseapp.com/projects/2706/tickets/758 if response.content_type == 'text/html': response.content_type = 'application/xhtml+xml' return render(tmpl, tmpl_vars=result, method='auto') if permission: wrapped_f = ActionProtector(has_permission(permission))(wrapped_f) return wrapped_f
def default(self, *args): admin=False if predicates.not_anonymous(): if predicates.has_permission('admin'): admin=True osfamily_name = args[0] osfamily = OSFamily.by_osfamily_name(osfamily_name) osreleases = osfamily.osreleases return dict(osfamily=osfamily, osreleases=osreleases, admin=admin)
def update(self): ftype = request.params.get('type',False) if ftype == 'selected': pass else: if is_met(has_permission(u'edit_invoice')): return self._admin_update(request) elif is_met(in_group('customer')): h.flash(_('You can only delete an unconfirmed invoices. If you want to change anything in a shipping order contact us by phone')) return redirect(controller='invoice',action='index')
def delete(self,id): invoice = Session.query(Invoice).filter_by(id=id).one() if is_met(has_permission('delete_invoice')): return self._delete(invoice) else: if invoice.customer == request.environ.get('repoze.who.identity')['user']: return self._delete(invoice) else: h.flash(_('You don not have enough permission to delete invoice')) return redirect(url(controller='invoice',action='index'))
def returnFun(): # if in_group("Admin") or in_group("DBA_AE"): if has_permission("DBA_VIEW_ALL_CUSTOMER"): #update by CL on 2011-06-28 return [("","")] + [(str(r.id),str(r.name)) for r in dbobj.find_all()] else: if request.identity["user"].groups and request.identity["user"].groups[0].dba_profiles: customer=request.identity["user"].groups[0].dba_profiles[0].customer return [("",""), (str(customer.id), str(customer.name))] else: return [("","")]
def __actions__(self, obj): """Override this function to define how action links should be displayed for the given record.""" primary_fields = self.__provider__.get_primary_fields(self.__entity__) pklist = '/'.join(map(lambda x: str(getattr(obj, x)), primary_fields)) if has_permission('manage'): ############ value = '<div><div><a class="edit_link" href="'+pklist+'/edit" style="text-decoration:none">edit</a>'\ '</div><div>'\ '<form method="POST" action="'+pklist+'" class="button-to">'\ '<input type="hidden" name="_method" value="DELETE" />'\ '<input class="delete-button" onclick="return confirm(\'Are you sure?\');" value="delete" type="submit" '\ 'style="background-color: transparent; float:left; border:0; color: #286571; display: inline; margin: 0; padding: 0;"/>'\ '</form>'\ '</div></div>' else: ########## if has_permission('configurar'): value = '<div><a class="edit_link" href="' + pklist + '/edit" style="text-decoration:none">edit</a></div>' else: value = '<div></div>' ###### return value
class EntityController(CrudRestController): requires = has_permission('manager') model = Entity #table = entity_table #table_filler = entity_table_filler #new_form = entity_add_form @expose('mako:moksha.apps.knowledge.templates.get_all') def get_all(self, *args, **kw): return super(EntityController, self).get_all(*args, **kw) @expose('mako:moksha.apps.knowledge.templates.new') def new(self, *args, **kw): return super(EntityController, self).new(*args, **kw) @expose('mako:moksha.apps.knowledge.templates.edit') def edit(self, *args, **kw): return super(EntityController, self).edit(*args, **kw) #@expose() #def post(self, **kw): # print "EntityController.post(%s)" % locals() # return super(EntityController, self).post(**kw) class new_form_type(AddRecordForm): __model__ = Entity __omit_fields__ = ['id', 'parent_id'] class edit_form_type(EditableForm): __model__ = Entity __omit_fields__ = ['id', 'parent_id'] class edit_filler_type(EditFormFiller): __model__ = Entity __omit_fields__ = ['id', 'parent_id'] class table_type(TableBase): __model__ = Entity __omit_fields__ = ['id', 'parent_id'] class table_filler_type(TableFiller): __model__ = Entity __omit_fields__ = ['id', 'parent_id'] __xml_fields__ = ['children', 'facts'] def children(self, entity): return ', '.join([child.name for child in entity.children]) def facts(self, entity, *args, **kw): #print "facts(%s)"% locals() for fact in entity.facts: print fact return entity.name
def __init__(self, sheet): self.sheet = sheet self.event = sheet.event self.assignments = AssignmentsController(sheet=self.sheet) c.sheet = self.sheet self.allow_only = Any(is_public(self.sheet), user_is_in('teachers', self.event), user_is_in('tutors', self.event), has_permission('manage'), msg=u'This Sheet is not public') self.submissions = SubmissionsController(sheet=self.sheet)
def __actions__(self, obj): """Override this function to define how action links should be displayed for the given record.""" primary_fields = self.__provider__.get_primary_fields( self.__entity__) pklist = '/'.join( map(lambda x: str(getattr(obj, x)), primary_fields)) value = '<div>' if has_permission('editar_valores'): value = value + '<div><a class="edit_link" href="' + pklist + '/edit" style="text-decoration:none">edit</a></div>' value = value + '</div>' return value
def __init__(self, assignment): self.assignment = assignment self.sheet = assignment.sheet self.event = self.sheet.event c.assignment = self.assignment self.allow_only = Any(is_public(self.assignment), user_is_in('teachers', self.event), user_is_in('tutors', self.event), has_permission('manage'), msg=u'This Assignment is not public') self.submissions = SubmissionsController(assignment=self.assignment) self.similarity = SimilarityController(assignment=self.assignment)
def __init__(self, event): self.event = event self.sheets = SheetsController(event=self.event) self.lessons = LessonsController(event=self.event) self.admin = EventAdminController(event=self.event) c.event = self.event self.allow_only = Any( is_public(self.event), has_teacher(self.event), has_permission('manage'), msg=u'This Event is not public' ) c.sub_menu = menu(self.event, True)
class PermissionController(BaseController): allow_only = has_permission(gl.perm_admin) model = Permission @expose('genshi:tgext.crud.templates.post_delete') def post_delete(self, *args, **kw): for id in args: permission = DBSession.query(Permission).filter( Permission.id == id).first() if permission.name == gl.perm_admin: flash('Cannot delete admin permission') redirect('/permissions') if permission.name == gl.perm_user: flash('Cannot delete read permission') redirect('/permissions') return CrudRestController.post_delete(self, *args, **kw)
def __init__(self, submission): self.submission = submission self.assignment = submission.assignment self.event = self.assignment.event predicates = (user_is_in('tutors', l) for l in submission.lessons) self.allow_only = Any( is_public(submission), user_is('user', self.submission), user_is_in('team', self.submission), user_is_in('teachers', self.event), has_permission('manage'), msg=u'You are not allowed to view this submission', *predicates )
class SecureController(BaseController): """Sample controller-wide authorization""" # The predicate that must be met for all the actions in this controller: allow_only = has_permission( 'manage', msg=l_('Only for people with the "manage" permission')) @expose('tw2jittg21demo.templates.index') def index(self): """Let the user know that's visiting a protected controller.""" flash(_("Secure Controller here")) return dict(page='index') @expose('tw2jittg21demo.templates.index') def some_where(self): """Let the user know that this action is protected too.""" return dict(page='some_where')
class GroupController(BaseController): allow_only = has_permission(gl.perm_admin) model = Group #edit_form = group_edit_form #new_form = new_group_form @expose('genshi:tgext.crud.templates.post_delete') def post_delete(self, *args, **kw): for id in args: group = DBSession.query(Group).filter(Group.id == id).first() if group.name == gl.group_admins: flash('Cannot delete admin group') redirect('/groups') if group.name == gl.group_users: flash('Cannot delete users group') redirect('/groups') return CrudRestController.post_delete(self, *args, **kw)
def get_one(self, articleid, languageid=None): """Return a single article""" tmpl_context.w_object_title = w_object_title article = DBSession.query(Article).get(articleid.decode()) if languageid: lang = languageid elif tmpl_context.lang: lang = tmpl_context.lang else: lang = article.language_id if not article.published and not has_permission('manage'): raise HTTPNotFound else: return dict(article=article, lang=lang, related=find_related(obj=article))
def __init__(self, assignment): self.assignment = assignment self.submissions = sorted((s for s in self.assignment.submissions if s.source), key=lambda s: s.id) self.key = str(self.assignment.id) if self.submissions: self.key += '_' + '-'.join(str(s.id) for s in self.submissions) self.key += '_' + (max(self.submissions, key=lambda s: s.modified) .modified.strftime('%Y-%m-%d-%H-%M-%S')) self.allow_only = Any( user_is_in('teachers', self.assignment.sheet.event), user_is_in('tutors', self.assignment.sheet.event), has_permission('manage'), msg=u'You are not allowed to access this page.' )
def application(environ, start_response): req = Request(environ) resp = Response() resp.content_type = 'text/plain' resp.body = 'anonymous' if req.path_info == '/secure': body = '' cred = environ.get('repoze.what.credentials', {}) for k, v in cred.items(): body += '%s: %s\n' % (k, v) for group in ('admin', 'others'): body += 'in_group(%r): %s\n' % (group, in_group(group).is_met(environ)) for perm in ('read', 'write'): body += 'has_permision(%r): %s\n' % ( perm, has_permission(perm).is_met(environ)) resp.body = body return resp(environ, start_response)
class SecureController(BaseController): """Sample controller-wide authorization""" # The predicate that must be met for all the actions in this controller: allow_only = has_permission( 'manage', msg=_('Only for people with the "manage" permission')) @expose('sipbmp3web.templates.index') def index(self): flash(_("Secure Controller here")) return dict(page='index') @expose('sipbmp3web.templates.index') def some_where(self): """should be protected because of the require attr at the controller level. """ return dict(page='some_where')
class RootController(BaseController): def index(self): return render('index.mako') @ActionProtector(is_user('test')) def user(self): return render('loggedin.mako') @ActionProtector(is_user('nottest')) def notuser(self): return render('loggedin.mako') @ActionProtector(in_group('admin')) def admin(self): return render('loggedin.mako') @ActionProtector(has_permission('edit')) def edit(self): return render('loggedin.mako')
class ComponentController(CrudRestController): # The predicate that must be met for all the actions in this controller: allow_only = has_permission( 'manage', msg=l_('Only for people with the "manage" permission')) model = Component class new_form_type(AddRecordForm): __model__ = Component __omit_fields__ = ['id'] __field_attrs__ = {'description': {'rows': '2'}} __field_order__ = [ 'type', 'manufacturer', 'model', 'description', 'sanitization', 'media' ] __required_fields__ = ['type', 'manufacturer', 'description'] description = TextField sanitization = TextField media = TextField type = NotEmpty() class edit_form_type(EditableForm): __model__ = Component __omit_fields__ = ['id'] __field_attrs__ = {'description': {'rows': '2'}} __field_order__ = [ 'type', 'manufacturer', 'model', 'description', 'sanitization', 'media' ] __required_fields__ = ['type', 'manufacturer', 'description'] description = TextField sanitization = TextField media = TextField type = NotEmpty() class edit_filler_type(EditFormFiller): __model__ = Component class table_type(TableBase): __model__ = Component __omit_fields__ = ['id', 'type_id'] class table_filler_type(TableFiller): __model__ = Component