class BasicPylonsController(WSGIController): """Mock Pylons controller""" sub1 = SubController1() panel = SecurePanel() def index(self, **kwargs): return 'hello world' @ActionProtector(in_group('admins')) def admin(self, *args, **kwargs): return 'got to admin' def troll_detected(reason): # Let's ignore the reason return 'Trolls are banned' @ActionProtector(All(not_anonymous(), Not(is_user('sballmer'))), denial_handler=troll_detected) def leave_comment(self): return 'Comment accepted' @special_require(not_anonymous()) def logout(self): return 'You have been logged out' @special_require(All(not_anonymous(), Not(is_user('sballmer'))), denial_handler=troll_detected) def start_thread(self): return 'You have started a thread' @ActionProtector(Not(not_anonymous())) def get_parameter(self, something): # Checking that parameters are received return 'Parameter received: %s' % something def boolean_predicate(self): p = not_anonymous() return 'The predicate is %s' % bool(p) def is_met_util(self): if is_met(not_anonymous()): return 'You are not anonymous' return 'You are anonymous' def not_met_util(self): if not_met(not_anonymous()): return 'You are anonymous' return 'You are not anonymous'
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
class RootController(TGController): cp = ControlPanel() rest = DaRestController() mounted_app = WSGIAppController(wsgi_app, allow_only=is_user('gustavo')) @expose() def index(self): return "you're in the main page" @expose() @require(is_user('developer')) def commit(self): return 'you can commit'
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
class DaRestController(RestController): """Mock REST controller""" allow_only = is_user('gustavo') @expose() def new(self): return "new here"
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 HRManagementController(TGController): """Mock TG2 protected controller using the .allow_only attribute""" allow_only = is_user('hiring-manager') @expose() def index(self): return 'you can manage Human Resources' @expose() def hire(self, person_name): return "%s was just hired" % person_name
class ControlPanel(TGController): """Mock TG2 protected controller using @allow_only directly.""" hr = HRManagementController() @expose() def index(self): return 'you are in the panel' @expose() @require(is_user('admin')) def add_user(self, user_name): return "%s was just registered" % user_name
class ControllerWithAllowOnlyAttributeAndAuthzDenialHandler(TGController): """Mock TG2 protected controller using the .allow_only attribute""" allow_only = is_user('foobar') @expose() def index(self): return 'Welcome back, foobar!' @classmethod def _failed_authorization(self, reason): # Pay first! abort(402)
class RootController(BaseController): @expose('json') def index(self): return {'foo': 'bar'} @expose() @require(predicates.is_user('manager')) def secure(self): return u'Hello World!' @expose('fedora.wsgi.test.templates.login') def login(self, came_from=url('/')): """Start the user login.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from) @expose() def post_login(self, came_from=url('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 redirect(url('/login', came_from=came_from, __logins=login_counter)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) redirect(came_from) @expose() def post_logout(self, came_from=url('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) redirect(came_from)
def test_user_without_credentials(self): environ = {} p = predicates.is_user('gustavo') self.eval_unmet_predicate(p, environ, 'The current user must be "gustavo"')
class RootController(BaseController): """ The root controller for the GestionItem application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ item = ItemControler() proyecto = ProyectoController() tipoItems = TipoItemControler() secc = SecureController() lb = LineaBaseController() admin = AdminController([User, Rol, Permission], DBSession, config_type=TGAdminConfig) admin.allow_only = in_group('Administrador') error = ErrorController() dict(subtitulo='') @expose('gestionitem.templates.index') def index(self): identity = request.environ.get('repoze.who.identity') """Handle the front-page.""" return dict(page='Indice', subtitulo='Indice') @expose('gestionitem.templates.prueba.demo') def demo(self): """Handle the front-page.""" return dict(page='Indice', subtitulo='Indice') @expose(template='gestionitem.templates.proyectoList') def proyectoList(self, **named): proyectos = DBSession.query(Proyecto).order_by(Proyecto.id) from webhelpers import paginate count = proyectos.count() page = int(named.get('page', '1')) currentPage = paginate.Page( proyectos, page, item_count=count, items_per_page=3, ) proyectos = currentPage.items return dict(page='proyecto', proyectos=proyectos, subtitulo='Proyectos', currentPage=currentPage) @expose(template="gestionitem.templates.proyectoDef") def proyectoDef(self, id): proyecto = DBSession.query(Proyecto).filter_by(id=id).one() return dict(page='Definir Proyecto', id=id, proyecto=proyecto, subtitulo='Definicion de Proyectos') @expose(template="gestionitem.templates.faseList") def faseList(self, id): fases = DBSession.query(Fase).filter_by(proyecto_id=id).order_by( Fase.id).all() proyecto = DBSession.query(Proyecto).filter_by(id=id).one() return dict(page='Lista de Fases', id=id, fases=fases, proyecto=proyecto, subtitulo='Lista de Fases') @expose(template="gestionitem.templates.faseDef") def faseDef(self, id): fases = DBSession.query(Fase).order_by(Fase.id) proyecto = DBSession.query(Proyecto).filter_by(id=id).one() return dict(page='Lista de Fases', id=id, fases=fases, proyecto=proyecto, subtitulo='Lista de Fases') @expose(template='gestionitem.templates.permiso') def permiso(self, **named): permisos = DBSession.query(Permission).order_by(Permission.description) from webhelpers import paginate count = permisos.count() page = int(named.get('page', '1')) currentPage = paginate.Page( permisos, page, item_count=count, items_per_page=5, ) permisos = currentPage.items return dict(page='permiso', permisos=permisos, subtitulo='ABM-Permisos', currentPage=currentPage) @expose('gestionitem.templates.agregar_permiso') def agregar_permiso(self): permiso = Permission permiso.permission_name = '' permiso.description = '' permisos = DBSession.query(Permission) return dict(page='Nuevo Permiso', permisos=permisos, permiso=permiso, subtitulo='ABM-Permiso') @expose() def save_permiso(self, id, name, descripcion, submit): """Crea un nuevo permiso""" new = Permission( permission_name=name, description=descripcion, ) DBSession.add(new) redirect('./permiso') flash('''Permiso Agregado! %s''') @expose() def eliminar_permiso(self, id): #recurso = DBSession.query(Recurso).filter_by(id=id).delete() #permiso=DBSession.query(Permission).filter_by(id=id).one() DBSession.delete( DBSession.query(Permission).filter_by(permission_id=id).one()) redirect('../permiso') @expose(template="gestionitem.templates.permiso_editar") def permiso_editar(self, id): permiso = DBSession.query(Permission).filter_by(permission_id=id).one() return dict(page='Editar Permiso', id=id, permiso=permiso, subtitulo='ABM-Permiso') @expose() def actualizar_permiso(self, id, name, descripcion, submit): """Create a new movie record""" permiso = DBSession.query(Permission).filter_by(permission_id=id).one() permiso.permission_name = name permiso.description = descripcion DBSession.flush() redirect('./permiso') @expose('gestionitem.templates.about') def about(self): """Handle the 'about' page.""" #aux=Recurso() return dict(page='about', aux='hola', subtitulo='About') @expose('gestionitem.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(environment=request.environ, subtitulo='') @expose('gestionitem.templates.data') @expose('json') def data(self, **kw): """This method showcases how you can use the same controller for a data page and a display page""" return dict(params=kw) @expose('gestionitem.templates.authentication') def auth(self): """Display some information about auth* on this application.""" return dict(page='auth', subtitulo='Autenticacion') @expose('gestionitem.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff', subtitulo='') @expose('gestionitem.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('gestionitem.templates.login') def login(self, came_from=url('/')): """Start the user login.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash(_('Error de acceso'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from, subtitulo='Loguin') @expose() def post_login(self, came_from='/'): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 redirect('/login', came_from=came_from, __logins=login_counter) userid = request.identity['repoze.who.userid'] flash(_('Bienvenido, %s!') % userid) redirect(came_from) @expose() def post_logout(self, came_from=url('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('Hasta pronto!')) redirect('/index')
class RootController(BaseController): """ The root controller for the tg2app application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() #admin = Catwalk(model, DBSession) error = ErrorController() @expose('genshi:tg2app.templates.index') def index(self): """Handle the front-page.""" return dict(page='index') @expose('genshi:tg2app.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('genshi:tg2app.templates.authentication') def auth(self): """Display some information about auth* on this application.""" return dict(page='auth') @expose('genshi:tg2app.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('genshi:tg2app.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('genshi:tg2app.templates.login') def login(self, came_from='/'): """Start the user login.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=url(came_from)) @expose() def post_login(self, came_from='/'): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 redirect(url('/login', came_from=came_from, __logins=login_counter)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) redirect(url(came_from)) @expose() def post_logout(self, came_from='/'): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) redirect(url(came_from))
class RootController(BaseController): """ The root controller for the tw2-facemelt-tg2.1 application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() error = ErrorController() @expose('tw2facemelttg21.templates.index') def index(self): """Handle the front-page.""" jqplot_params = self.jqplot() plotwidget = LogPlot(data=jqplot_params['data']) plotwidget.options = recursive_update(plotwidget.options, jqplot_params['options']) colwidth = '50%' class LayoutWidget(p.ColumnLayout): id = 'awesome-layout' class col1(p.Column): width = colwidth class por1(p.Portlet): title = 'DB Entries of Server Hits' widget = LogGrid class col2(p.Column): width = colwidth class por2(p.Portlet): title = 'Hits over the last hour' widget = plotwidget return dict(page='index', layoutwidget=LayoutWidget) @expose('json') def jqgrid(self, *args, **kw): return LogGrid.request(request).body def jqplot(self, days=1 / (24.0)): n_buckets = 15 now = datetime.datetime.now() then = now - datetime.timedelta(days) delta = datetime.timedelta(days) / n_buckets entries = ServerHit.query.filter(ServerHit.timestamp > then).all() t_bounds = [(then + delta * i, then + delta * (i + 1)) for i in range(n_buckets)] # Accumulate into buckets! This is how I like to do it. buckets = dict([(lower, 0) for lower, upper in t_bounds]) for entry in entries: for lower, upper in t_bounds: if entry.timestamp >= lower and entry.timestamp < upper: buckets[lower] += 1 # Only one series for now.. but you could do other stuff! series = [buckets[lower] for lower, upper in t_bounds] data = [ series, # You could add another series here... ] options = { 'axes': { 'xaxis': { 'ticks': [u.strftime("%I:%M:%S") for l, u in t_bounds], } } } return dict(data=data, options=options) @expose('tw2facemelttg21.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('tw2facemelttg21.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(environment=request.environ) @expose('tw2facemelttg21.templates.data') @expose('json') def data(self, **kw): """This method showcases how you can use the same controller for a data page and a display page""" return dict(params=kw) @expose('tw2facemelttg21.templates.authentication') def auth(self): """Display some information about auth* on this application.""" return dict(page='auth') @expose('tw2facemelttg21.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('tw2facemelttg21.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('tw2facemelttg21.templates.login') def login(self, came_from=url('/')): """Start the user login.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from) @expose() def post_login(self, came_from='/'): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 redirect('/login', came_from=came_from, __logins=login_counter) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) redirect(came_from) @expose() def post_logout(self, came_from=url('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) redirect(came_from)
Mock TG2 protected controller using the @allow_only decorator, but also using ._failed_authorization() """ @expose() def index(self): return "Welcome back, foobar!" @classmethod def _failed_authorization(self, reason): # Pay first! abort(402) ControllerWithAllowOnlyDecoratorAndAuthzDenialHandler = allow_only(is_user("foobar"))( ControllerWithAllowOnlyDecoratorAndAuthzDenialHandler ) # { The tests themselves class BaseIntegrationTests(TestCase): """Base test case for the integration tests""" controller = RootController def setUp(self): # Creating the session dir: if not os.path.exists(session_dir):
#return dict(params=kw) return dict(params=dict(args=kw, json=json)) @expose('portal.templates.authentication') def auth(self): """Display some information about auth* on this application.""" return dict(page='auth') @expose('portal.templates.index') @require(predicates.has_permission('manage', msg=l_('Permitido apenas para funcionários'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('portal.templates.index') @require(predicates.is_user('editor', msg=l_('Permitido apenas para editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('portal.templates.login') def login(self, came_from=url('/')): """Start the user login.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash(_('Usuario|Senha invalidos'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from) @expose() def post_login(self, came_from=url('/')):
class RootController(BaseController): ################Administración######################## secc = SecureController() admin = AdminController(model, DBSession, config_type=TGAdminConfig) #admin = AdminController(model, DBSession, config_type=MyAdminConfig) error = ErrorController() proyectos = ProyectoController(DBSession) ##################################################### ################Configuración########################## proyectoconfig = ProyectoConfig(DBSession) fase = FaseController(DBSession) tipodeitem = TipoDeItemController(DBSession) campos = CamposController(DBSession) proyfaseusuario = ProyFaseUsuarioController(DBSession) importartipodeitem = ImportarTipoDeItemController(DBSession) ####################################################### ##################Desarrollo########################### proyectodesarrollo = ProyectoDesarrollo(DBSession) fasedesarrollo = FaseControllerD(DBSession) item = ItemController(DBSession) adjuntos = AdjuntosController(DBSession) lineabase = LineaBaseController(DBSession) relacionitem = RelacionItemController(DBSession) detalleitem = DetalleItemController(DBSession) itemlineabase = ItemLineaBaseController(DBSession) revertir = RevertirController(DBSession) revivir = RevivirController(DBSession) ####################################################### """-----------------------------Adjuntos------------------------------""" error = ErrorController() @expose('sap.templates.desarrollar.fileupload.index') def indexx(self): current_files = DBSession.query(UserFile).all() return dict(current_files=current_files) @expose(content_type=CUSTOM_CONTENT_TYPE) def view(self, fileid): iid = DBSession.query(Adjuntos.idItem).filter_by(id=fileid).first() log.debug("iidssss: %s" % iid) try: userfile = DBSession.query(Adjuntos).filter_by(id=fileid).one() except: redirect("../../adjuntos/new/adjuntos/new") content_types = { 'display': {}, 'download': { '.pdf': 'application/pdf', '.zip': 'application/zip', '.rar': 'application/x-rar-compressed', '.png': 'image/jpeg', '.jpeg': 'image/jpeg', '.jpg': 'image/jpeg', '.gif': 'image/jpeg', '.txt': 'text/plain' } } for file_type in content_types['display']: if userfile.filename.endswith(file_type): response.headers["Content-Type"] = content_types['display'][ file_type] for file_type in content_types['download']: if userfile.filename.endswith(file_type): response.headers["Content-Type"] = content_types['download'][ file_type] response.headers[ "Content-Disposition"] = 'attachment; filename="' + userfile.filename + '"' if userfile.filename.find(".") == -1: response.headers["Content-Type"] = "text/plain" return userfile.filecontent @expose() def delete(self, fileid): #log.debug("Soy Archivo Borrado") """Se extrae el ID del Item que supuestamente se borrará, para crear un nuevo Item """ iid = DBSession.query(Adjuntos.idItem).filter_by(id=fileid).first() """Se crea un nuevo item""" itemeditado = DBSession.query(Item).filter_by(id=iid).first() itemnuevo = Item() itemnuevo.version = itemeditado.version + 1 itemnuevo.idTipoDeItem = itemeditado.idTipoDeItem itemnuevo.idFase = itemeditado.idFase itemnuevo.idLineaBase = itemeditado.idLineaBase itemnuevo.fechaCreacion = itemeditado.fechaCreacion itemnuevo.nrohistorial = itemeditado.nrohistorial itemnuevo.ultimaversion = 1 itemeditado.ultimaversion = 0 itemnuevo.estado = 'modificado' itemnuevo.complejidad = itemeditado.complejidad itemnuevo.nombre = itemeditado.nombre DBSession.add(itemnuevo) """Realiza copia de los valores de los atributos especificos""" atributoeditado = DBSession.query(DetalleItem).filter_by( iditem=itemeditado.id).all() for objeto in atributoeditado: nuevoDetalle = DetalleItem() nuevoDetalle.tipo = objeto.tipo nuevoDetalle.nombrecampo = objeto.nombrecampo nuevoDetalle.valor = objeto.valor nuevoDetalle.iditem = itemnuevo.id DBSession.add(nuevoDetalle) """Realiza copia de los adjuntos""" adjuntositemeditado = DBSession.query(Adjuntos).filter_by( idItem=itemeditado.id).all() for adj in adjuntositemeditado: log.debug("adjuntoBorraado: %s" % adj.id) log.debug("fileid: %s" % fileid) if str(adj.id) != str( fileid): #No se copiará el archivo "supuestamente" borrado log.debug("fileid2: %s" % fileid) itemnuevoadjunto = Adjuntos() itemnuevoadjunto.idItem = itemnuevo.id itemnuevoadjunto.filename = adj.filename itemnuevoadjunto.filecontent = adj.filecontent DBSession.add(itemnuevoadjunto) """Copia las relaciones """ relaciones = DBSession.query( RelacionItem.idItem1, RelacionItem.idItem2).filter( (RelacionItem.idItem2 == itemeditado.id) | (RelacionItem.idItem1 == itemeditado.id)).all() longitud = len(relaciones) for x in range(longitud): newRelation = RelacionItem() log.debug('Creando relaciones') if int(itemeditado.id) == int(relaciones[x][0]): newRelation.idItem1 = int(itemnuevo.id) newRelation.idItem2 = relaciones[x][1] DBSession.add(newRelation) #self.provider.create(RelacionItem, params=newRelation) elif int(itemeditado.id) == int(relaciones[x][1]): newRelation.idItem1 = relaciones[x][0] newRelation.idItem2 = int(itemnuevo.id) DBSession.add(newRelation) return redirect("../../adjuntos/new/?iid=" + str(itemnuevo.id)) """-----------------------------------FIN ADJUNTOS----------------------------- """ @expose('sap.templates.desarrollar.elegirtipo.new') def elegirtipo(self, **kw): tmpl_context.form = create_elegirtipo_form if len(kw) > 1: #return dict(modelname='Item',page='ToscaSample New Movie', tid=kw['tipoitem'] ) redirect('../item/new/?tid=' + str(kw['tipoitem'])) else: tipoitem = [ x for x in (DBSession.query(TipoDeItem.id, TipoDeItem.nombre). filter_by(idFase=kw['fid'])) ] return dict(tipoitem_options=tipoitem, fid=kw['fid']) ############################################################# @expose('sap.templates.desarrollar.abrirlineabase.new') def abrirlineabase(self, **kw): tmpl_context.form = create_abrirlineabase_form if len(kw) > 1: if (int(kw['lineaBase']) == 0): item = DBSession.query(Item).filter_by(id=kw['iid']).first() lineabase = DBSession.query(LineaBase).filter_by( id=item.idLineaBase).first() lineabase.estado = 'abierta' item.estado = 'modificado' faseitemmodificado = DBSession.query(Fase).filter_by( id=item.idFase).first() if str(faseitemmodificado.estado).__eq__('lineaBaseTotal'): faseitemmodificado.estado = 'desarrollo' ids = [] ids.append(item.id) self.recorrerArbolAtrasLB(ids, item.id) self.recorrerArbolAdelanteLB(ids, item.id) ids.remove(item.id) longitudids = len(ids) for x in range(longitudids): itemrevision = DBSession.query(Item).filter_by( id=ids[x], ultimaversion=1).first() if itemrevision != None: if itemrevision.estado != 'modificado': itemrevision.estado = 'revision' if itemrevision.idLineaBase != None: lineabase = DBSession.query( LineaBase).filter_by( id=itemrevision.idLineaBase).first() if lineabase.estado == 'cerrada': lineabase.estado = 'comprometida' listalineabase = DBSession.query( LineaBase).filter_by( idFase=itemrevision.idFase).all() desarrollo = True longitud = len(listalineabase) for y in range(longitud): if str(listalineabase[y].estado ).__eq__('cerrada'): desarrollo = False if desarrollo: fase = DBSession.query(Fase).filter_by( id=itemrevision.idFase).first() fase.estado = 'desarrollo' flash("La linea base \"" + lineabase.nombre + "\" se ha abierto. El item \""+\ item.nombre+"\" paso al estado modificado y los item implicados pasaron al"\ " estado de revision", "warning") redirect("../item/" + kw['iid'] + '/edit') else: fid = DBSession.query( Item.idFase).filter_by(id=kw['iid']).first() flash("Debe abrir la linea base para editar el item", "error") redirect("../item/?fid=" + str(fid[0])) else: lineaBase = [x for x in enumerate(('Abrir', 'No abrir'))] return dict(tipoitem_options=lineaBase) ############################################################# @expose('sap.templates.desarrollar.abrirlineabase.new') def abrirlineabaserelacion(self, **kw): tmpl_context.form = create_abrirlineabase_form if len(kw) > 1: if (int(kw['lineaBase']) == 0): item = DBSession.query(Item).filter_by(id=kw['iid']).first() lineabase = DBSession.query(LineaBase).filter_by( id=item.idLineaBase).first() lineabase.estado = 'abierta' item.estado = 'modificado' faseitemmodificado = DBSession.query(Fase).filter_by( id=item.idFase).first() if str(faseitemmodificado.estado).__eq__('lineaBaseTotal'): faseitemmodificado.estado = 'desarrollo' ids = [] ids.append(item.id) self.recorrerArbolAtrasLB(ids, item.id) self.recorrerArbolAdelanteLB(ids, item.id) ids.remove(item.id) longitudids = len(ids) for x in range(longitudids): itemrevision = DBSession.query(Item).filter_by( id=ids[x], ultimaversion=1).first() if itemrevision != None: if itemrevision.estado != 'modificado': itemrevision.estado = 'revision' if itemrevision.idLineaBase != None: lineabase = DBSession.query( LineaBase).filter_by( id=itemrevision.idLineaBase).first() if lineabase.estado == 'cerrada': lineabase.estado = 'comprometida' listalineabase = DBSession.query( LineaBase).filter_by( idFase=itemrevision.idFase).all() desarrollo = True longitud = len(listalineabase) for y in range(longitud): if str(listalineabase[y].estado ).__eq__('cerrada'): desarrollo = False if desarrollo: fase = DBSession.query(Fase).filter_by( id=itemrevision.idFase).first() fase.estado = 'desarrollo' flash("La linea base \"" + lineabase.nombre + "\" se ha abierto. El item \""+\ item.nombre+"\" paso al estado modificado y los item implicados pasaron al"\ " estado de revision", "warning") redirect("../item/" + kw['iid'] + '/edit') else: fid = DBSession.query( Item.idFase).filter_by(id=kw['iid']).first() flash("Debe abrir la linea base para editar el item", "error") redirect("../item/?fid=" + str(fid[0])) else: lineaBase = [x for x in enumerate(('Abrir', 'No abrir'))] return dict(tipoitem_options=lineaBase) """---------------------- Recorrer Arbol Atras ------------------------------------- Uso: self.recorrerArbol (ids, iid) ids: un vector que contiene primeramente al nodo inicial iid: nodo inicial Todos los nodos del arbol quedaran guardados en ids---------------------------""" def recorrerArbolAtrasLB(self, *args): ids = args[0] itemraiz = args[1] """-------------Obtiene de la BD las relaciones actuales del nodo en cuestion---""" relaciones = DBSession.query(RelacionItem.idItem1,RelacionItem.idItem2).\ filter((RelacionItem.idItem1==itemraiz)).all() """------------------------------------------------------------------------""" for relacion in relaciones: itemrelacion = DBSession.query(Item).filter_by( id=relacion.idItem2).first() if itemrelacion.ultimaversion == 1: if (ids.count(itemrelacion.id) < 1): ids.append(itemrelacion.id) self.recorrerArbolAtrasLB(ids, itemrelacion.id) """------------------- Fin Recorrer Arbol Atras -----------------------------------""" """-------------------- Recorrer Arbol Adelante ------------------------------------- Uso: self.recorrerArbol (ids, iid) ids: un vector que contiene primeramente al nodo inicial iid: nodo inicial Todos los nodos del arbol quedaran guardados en ids---------------------------""" def recorrerArbolAdelanteLB(self, *args): ids = args[0] itemraiz = args[1] """-------------Obtiene de la BD las relaciones actuales del nodo en cuestion---""" relaciones = DBSession.query(RelacionItem.idItem1,RelacionItem.idItem2).\ filter((RelacionItem.idItem2==itemraiz)).all() """------------------------------------------------------------------------""" for relacion in relaciones: itemrelacion = DBSession.query(Item).filter_by( id=relacion.idItem1).first() if itemrelacion.ultimaversion == 1: if (ids.count(itemrelacion.id) < 1): ids.append(itemrelacion.id) self.recorrerArbolAdelanteLB(ids, itemrelacion.id) """---------------------- Fin Recorrer Arbol Adelante -----------------------------""" """------------------------------Calculo de Impacto--------------------------- """ @expose('sap.templates.desarrollar.item.dibujar') def calcularimpacto(self, **kw): """ids[] es un vector en el cual se guardaran los 'id' """ ids = [] itemraiz = DBSession.query(Item).filter_by(id=kw['iid']).first() ids.append(itemraiz) impacto = 0 relacionesTotal = [] self.recorrerArbolAtras(ids, itemraiz, relacionesTotal) self.recorrerArbolAdelante(ids, itemraiz, relacionesTotal) for item in ids: complejidad = int(item.complejidad) impacto = impacto + complejidad nodosporfase = [] while len(ids) != 0: aux = [] for item in ids: if ids[0].idFase == item.idFase: aux.append(item) for item in aux: ids.remove(item) nodosporfase.append(aux) self.dibujar(relacionesTotal, nodosporfase, itemraiz) flash("El impacto de modificar el item \"" + itemraiz.nombre + "\" es: " + str(impacto)) #redirect('/item/?fid='+str(fid[0])) return dict(link={'url': '/item/?fid=' + str(itemraiz.idFase)}) """---------------------- Recorrer Arbol Atras ------------------------------------- Uso: self.recorrerArbol (ids, iid) ids: un vector que contiene primeramente al nodo inicial iid: nodo inicial Todos los nodos del arbol quedaran guardados en ids---------------------------""" def recorrerArbolAtras(self, *args): ids = args[0] itemraiz = args[1] relacionesTotal = args[2] """-------------Obtiene de la BD las relaciones actuales del nodo en cuestion---""" relaciones = DBSession.query(RelacionItem.idItem1,RelacionItem.idItem2).\ filter((RelacionItem.idItem1==itemraiz.id)).all() """------------------------------------------------------------------------""" for relacion in relaciones: itemrelacion = DBSession.query(Item).filter_by( id=relacion.idItem2).first() if itemrelacion.ultimaversion == 1: if (ids.count(itemrelacion) < 1): ids.append(itemrelacion) if (relacionesTotal.count(relacion) < 1): relacionesTotal.append(relacion) self.recorrerArbolAtras(ids, itemrelacion, relacionesTotal) """------------------- Fin Recorrer Arbol Atras -----------------------------------""" """-------------------- Recorrer Arbol Adelante ------------------------------------- Uso: self.recorrerArbol (ids, iid) ids: un vector que contiene primeramente al nodo inicial iid: nodo inicial Todos los nodos del arbol quedaran guardados en ids---------------------------""" def recorrerArbolAdelante(self, *args): ids = args[0] itemraiz = args[1] relacionesTotal = args[2] """-------------Obtiene de la BD las relaciones actuales del nodo en cuestion---""" relaciones = DBSession.query(RelacionItem.idItem1,RelacionItem.idItem2).\ filter((RelacionItem.idItem2==itemraiz.id)).all() """------------------------------------------------------------------------""" for relacion in relaciones: itemrelacion = DBSession.query(Item).filter_by( id=relacion.idItem1).first() if itemrelacion.ultimaversion == 1: if (ids.count(itemrelacion) < 1): ids.append(itemrelacion) if (relacionesTotal.count(relacion) < 1): relacionesTotal.append(relacion) self.recorrerArbolAdelante(ids, itemrelacion, relacionesTotal) """---------------------- Fin Recorrer Arbol Adelante -----------------------------""" """------------------------------ Fin Calculo de Impacto--------------------------- """ def dibujar(self, *args): """Dibuja un grafo dirigido a partir de una matriz de relaciones y una matriz de nodos""" relaciones = args[0] nodosporfase = args[1] itemraiz = args[2] g = self.grafo_de_relaciones(relaciones) for fase in nodosporfase: subg = pydot.Subgraph('', rank='same') nombreFase = DBSession.query( Fase.nombre).filter_by(id=fase[0].idFase).first() subg.add_node(pydot.Node(nombreFase[0],label=nombreFase[0],\ color='white')) for nodo in fase: if nodo == itemraiz: subg.add_node(pydot.Node(nodo.id,\ label=str(nodo.nombre)+"\nPeso: "+str(nodo.complejidad),\ color='PaleGreen3', style='filled')) else: subg.add_node(pydot.Node(nodo.id,\ label=str(nodo.nombre)+"\nPeso: "+str(nodo.complejidad),\ color='NavajoWhite1', style='filled')) g.add_subgraph(subg) g.write_png('sap/public/images/example2_graph.png') def grafo_de_relaciones(self, edge_list, node_prefix=''): """Crea las relaciones en el grafo a partir de una matriz de relaciones. Utilizado por el metodo dibujar(self)""" graph = pydot.Dot(graph_type='digraph', rankdir='RL') for edge in edge_list: if isinstance(edge[0], str): src = node_prefix + edge[0] else: src = node_prefix + str(edge[0]) if isinstance(edge[1], str): dst = node_prefix + edge[1] else: dst = node_prefix + str(edge[1]) e = pydot.Edge(src, dst) graph.add_edge(e) return graph @expose() def aprobaritem(self, **kw): item = DBSession.query(Item).filter_by(id=kw['iid']).first() item.estado = 'aprobado' fid = DBSession.query(Item.idFase, Item.nombre).filter_by(id=kw['iid']).first() if item.idLineaBase != None: listaitem = DBSession.query(Item).filter_by( idLineaBase=item.idLineaBase, ultimaversion=1).all() longitud = len(listaitem) contadoraprob = 0 modificado = False for x in range(longitud): #Verificar si todos los item de la linea base estan aprobados if str(listaitem[x].estado).__eq__('aprobado'): contadoraprob = contadoraprob + 1 #Verificar si existe por lo menos un item en estado modificado elif str(listaitem[x].estado).__eq__('modificado'): modificado = True #Entra si todos los item de la linea base estan aprobados if contadoraprob == longitud: lineabase = DBSession.query(LineaBase).filter_by( id=item.idLineaBase).first() lineabase.estado = 'cerrada' cantItemLB = DBSession.query(Item).filter_by( idLineaBase=lineabase.id, ultimaversion=1).all() cantItemFase = DBSession.query(Item).filter_by( idFase=fid[0], ultimaversion=1).all() fase = DBSession.query(Fase).filter_by(id=fid[0]).first() if len(cantItemLB) == len(cantItemFase): fase.estado = 'lineaBaseTotal' flash("El item \"" +str(fid[1]) +"\" fue aprobado, "\ "la linea base \"" + lineabase.nombre + "\" fue cerrada y "\ "la fase \""+fase.nombre+"\" paso al estado de \"Linea Base Total\"") redirect('/item/?fid=' + str(fid[0])) else: fase.estado = 'lineaBaseParcial' flash("El item \"" +str(fid[1]) +"\" fue aprobado, "\ "la linea base \"" + lineabase.nombre + "\" fue cerrada y "\ "la fase \""+fase.nombre+"\" paso al estado de \"Linea Base Parcial\"") redirect('/item/?fid=' + str(fid[0])) #Entra si no existem item modificados en la linea base""" elif not modificado: lineabase = DBSession.query(LineaBase).filter_by( id=item.idLineaBase).first() lineabase.estado = 'comprometida' flash("El item \"" +str(fid[1]) +"\" fue aprobado y "\ "la linea base \"" + lineabase.nombre + "\" ahora esta comprometida") redirect('/item/?fid=' + str(fid[0])) flash("El item \"" + str(fid[1]) + "\" fue aprobado") redirect('/item/?fid=' + str(fid[0])) @expose('sap.templates.index') def index(self): """Handle the front-page.""" return dict(page='index') @expose("sap.templates.configurar.adjuntos.get_all") def create(self, **kw): adjuntos = Adjuntos() #save the filename to the database #adjuntos.idItem= kw['idItem'] adjuntos.picture_filename = kw['adjuntos_filename'].filename #DBSession.add(adjuntos) DBSession.flush() """#write the picture file to the public directory adjuntos_path = os.path.join(adjuntos_dirname, str(adjuntos.id)) try: os.makedirs(adjuntos_path) except OSError: #ignore if the folder already exists pass adjuntos_path = os.path.join(adjuntos_path, adjuntos.adjuntos_filename) f = file(adjuntos_path, "w") f.write(kw['adjuntos_filename'].value) f.close() """ #flash("adjuntos was successfully created.") redirect("./adjuntos") @expose('sap.templates.user') def usuario(self, **kw): tmpl_context.form = create_user_form return dict(modelname='Usuario', value=kw) @expose('sap.templates.configurar.configuracion') def configuracion(self): """Display some information about auth* on this application.""" return dict(page='configuracion') @expose('sap.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('sap.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(environment=request.environ) @expose('sap.templates.data') @expose('json') def data(self, **kw): """This method showcases how you can use the same controller for a data page and a display page""" return dict(params=kw) @expose('sap.templates.authentication') def auth(self): """Display some information about auth* on this application.""" return dict(page='auth') @expose('sap.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('sap.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('sap.templates.login') def login(self, came_from=url('/')): """Start the user login.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash(_('Autenticacion incorrecta'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from) @expose() def post_login(self, came_from='/'): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 redirect('/login', came_from=came_from, __logins=login_counter) userid = request.identity['repoze.who.userid'] flash(_('Bienvenido %s!') % userid) redirect(came_from) @expose() def post_logout(self, came_from=url('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ redirect('/login')
class RootController(BaseController): """ The root controller for the Wiki-20 application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() admin = AdminController(model, DBSession, config_type=TGAdminConfig) error = ErrorController() @expose('wiki20.templates.page') def _default(self, pagename="FrontPage"): """Handle the front-page.""" try: page = DBSession.query(Page).filter_by(pagename=pagename).one() except InvalidRequestError: raise redirect("notfound", pagename=pagename) content = publish_parts(page.data, writer_name="html")["html_body"] root = url('/') content = wikiwords.sub(r'<a href="%s\1">\1</a>' % root, content) return dict(content=content, wikipage=page) @expose("wiki20.templates.edit") def notfound(self, pagename): page = Page(pagename=pagename, data="") DBSession.add(page) return dict(wikipage=page) @expose(template="wiki20.templates.edit") def edit(self, pagename): page = DBSession.query(Page).filter_by(pagename=pagename).one() return dict(wikipage=page) @expose() def save(self, pagename, data, submit): page = DBSession.query(Page).filter_by(pagename=pagename).one() page.data = data redirect("/" + pagename) @expose("wiki20.templates.pagelist") def pagelist(self): pages = [ page.pagename for page in DBSession.query(Page).order_by(Page.pagename) ] return dict(pages=pages) @expose('wiki20.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('wiki20.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(environment=request.environ) @expose('wiki20.templates.data') @expose('json') def data(self, **kw): """This method showcases how you can use the same controller for a data page and a display page""" return dict(params=kw) @expose('wiki20.templates.authentication') def auth(self): """Display some information about auth* on this application.""" return dict(page='auth') @expose('wiki20.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('wiki20.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('wiki20.templates.login') def login(self, came_from=url('/')): """Start the user login.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from) @expose() def post_login(self, came_from='/'): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) redirect(came_from) @expose() def post_logout(self, came_from=url('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) redirect(came_from)
def protect_group_obj(protected_obj=None): p = protected_obj if p: if not Any(is_user(p.owner.user_name), has_permission('dmirr_admin')): raise NotAuthorizedError
Mock TG2 protected controller using the @allow_only decorator, but also using ._failed_authorization() """ @expose() def index(self): return 'Welcome back, foobar!' @classmethod def _failed_authorization(self, reason): # Pay first! abort(402) ControllerWithAllowOnlyDecoratorAndAuthzDenialHandler = allow_only( is_user('foobar'))(ControllerWithAllowOnlyDecoratorAndAuthzDenialHandler) #{ The tests themselves class BaseIntegrationTests(TestCase): """Base test case for the integration tests""" controller = RootController def setUp(self): # Creating the session dir: if not os.path.exists(session_dir): os.makedirs(session_dir) # Setting TG2 up:
def test_user_without_userid(self): environ = {'repoze.what.credentials': {}} p = predicates.is_user('gustavo') self.eval_unmet_predicate(p, environ, 'The current user must be "gustavo"')
def auth(self): """Display some information about auth* on this application.""" return dict(page='auth') @expose('portal.templates.index') @require( predicates.has_permission('manage', msg=l_('Permitido apenas para funcionários')) ) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('portal.templates.index') @require( predicates.is_user('editor', msg=l_('Permitido apenas para editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('portal.templates.login') def login(self, came_from=url('/')): """Start the user login.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash(_('Usuario|Senha invalidos'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from) @expose()
def test_right_user(self): environ = make_environ('gustavo') p = predicates.is_user('gustavo') self.eval_met_predicate(p, environ)
class RootController(BaseController): @expose('wiki20.templates.index') def index(self, username, password): return { "hello": str("Hello world via template replacement. Username is: " + username + " Password is: " + password), "page": 'index' } """ The root controller for the Wiki-20 application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() admin = AdminController(model, DBSession, config_type=TGAdminConfig) error = ErrorController() @expose('wiki20.templates.index') #def index(self): # """Handle the front-page.""" # return dict(hello='=-)',page='index') @expose('wiki20.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('wiki20.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(environment=request.environ) @expose('wiki20.templates.data') @expose('json') def data(self, **kw): """This method showcases how you can use the same controller for a data page and a display page""" return dict(params=kw) @expose('wiki20.templates.authentication') def auth(self): """Display some information about auth* on this application.""" return dict(page='auth') @expose('wiki20.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('wiki20.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('wiki20.templates.index') def hello(self): return "Hello world from the controller" @expose('wiki20.templates.login') def login(self, came_from=url('/')): """Start the user login.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from) @expose() def post_login(self, came_from='/'): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 redirect('/login', came_from=came_from, __logins=login_counter) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) redirect(came_from) @expose() def post_logout(self, came_from=url('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) redirect(came_from)
def test_wrong_user(self): environ = make_environ('andreina') p = predicates.is_user('gustavo') self.eval_unmet_predicate(p, environ, 'The current user must be "gustavo"')
class RootController(BaseController): """ The root controller for the tw2.jit-tg2.1-demo application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() error = ErrorController() @expose('tw2jittg21demo.templates.index') def index(self): """Handle the front-page.""" return dict(page='index', widget=makeUserGraph()) @expose('json') def jit_data(self, *args, **kw): """ Serve data from the tw2.jit built-in controller """ return makeUserGraph().request(request).body @expose('tw2jittg21demo.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('tw2jittg21demo.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(environment=request.environ) @expose('tw2jittg21demo.templates.data') @expose('json') def data(self, **kw): """This method showcases how you can use the same controller for a data page and a display page""" return dict(params=kw) @expose('tw2jittg21demo.templates.authentication') def auth(self): """Display some information about auth* on this application.""" return dict(page='auth') @expose('tw2jittg21demo.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('tw2jittg21demo.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('tw2jittg21demo.templates.login') def login(self, came_from=url('/')): """Start the user login.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from) @expose() def post_login(self, came_from='/'): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 redirect('/login', came_from=came_from, __logins=login_counter) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) redirect(came_from) @expose() def post_logout(self, came_from=url('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) redirect(came_from)
Mock TG2 protected controller using the @allow_only decorator, but also using ._failed_authorization() """ @expose() def index(self): return 'Welcome back, foobar!' @classmethod def _failed_authorization(self, reason): # Pay first! abort(402) ControllerWithAllowOnlyDecoratorAndAuthzDenialHandler = allow_only( is_user('foobar'))(ControllerWithAllowOnlyDecoratorAndAuthzDenialHandler) #{ The tests themselves class BaseIntegrationTests(TestCase): """Base test case for the integration tests""" controller = RootController def setUp(self): # Creating the session dir: if not os.path.exists(session_dir): os.makedirs(session_dir) # Setting TG2 up: c = ContextObj()
class RootController(BaseController): """ The root controller for the SAIP application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ desarrollo = DesarrolloController() secc = SecureController() admin = AdminController() gestion = GestionController() error = ErrorController() def fase_apta(self, proyecto): fases = proyecto.fases aux = list() for fase in fases: band = False if fase.lineas_base: band = True else: t_items = [t for t in fase.tipos_item] items = list() for t in t_items: items = items + [i for i in t.items] for item in items: if item.estado == u"Aprobado" and not item.revisiones: band = True break if not band: aux.append(fase) fasesaux = [f for f in fases if f not in aux] fases = fasesaux if fases: return True else: return False @expose('saip.templates.index') def index(self): """Handle the front-page.""" p_sis = TieneAlgunPermiso(tipo = u"Sistema").is_met(request.environ) p_proy = TieneAlgunPermiso(tipo = u"Proyecto").is_met(request.environ) p_fic = TieneAlgunPermiso(recurso = u"Ficha").is_met(request.environ) p_t_it = TieneAlgunPermiso(recurso = u"Tipo de Item") \ .is_met(request.environ) proys = DBSession.query(Proyecto).filter(Proyecto.estado != \ u"Nuevo").all() permiso_desarrollo = False if len(proys) != 0: for p in proys: if TieneAlgunPermiso(recurso = u"Item", id_proyecto = p.id) \ .is_met(request.environ): permiso_desarrollo = True d = dict(page='index', direccion_anterior = "../") d["permiso_desarrollo"] = permiso_desarrollo for proyecto in reversed(proys): if not self.fase_apta(proyecto): proys.remove(proyecto) permiso_gestion = False if len(proys) != 0: for p in proys: for f in p.fases: if TieneAlgunPermiso(recurso = u"Linea Base", \ id_fase = f.id).is_met(request.environ): permiso_gestion = True d["permiso_administracion"] = p_sis or p_proy or p_fic or p_t_it d["permiso_gestion"] = permiso_gestion return d @expose('saip.templates.about') def about(self): """Handle the 'about' page.""" return dict(page='about', direccion_anterior = "../") @expose('saip.templates.environ') def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(environment=request.environ, direccion_anterior = "../") @expose('saip.templates.data') @expose('json') def data(self, **kw): """This method showcases how you can use the same controller for a data page and a display page""" return dict(params=kw, direccion_anterior = "../") @expose('saip.templates.authentication') def auth(self): """Display some information about auth* on this application.""" return dict(page='auth', direccion_anterior = "../") @expose('saip.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff', direccion_anterior = "../") @expose('saip.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff', direccion_anterior = "../") @expose('saip.templates.login') def login(self, came_from=url('/')): """Start the user login.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from, direccion_anterior = "../") @expose() def post_login(self, came_from='/'): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 redirect('/login', came_from=came_from, __logins=login_counter) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) redirect(came_from) @expose() def post_logout(self, came_from=url('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) redirect(came_from)
class RootController(BaseController): """ The root controller for the PROYECTO-SAP-TG application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() menu_adm_sys = {} menu_adm_sys[User.__name__.lower()] = User menu_adm_sys[Permission.__name__.lower()] = Permission menu_adm_sys[Group.__name__.lower()] = Group #menu_adm_sys[Proyecto.__name__.lower()] = Proyecto menu_adm_sys[TipoItem.__name__.lower()] = TipoItem menu_adm_sys[Atributo.__name__.lower()] = Atributo menu_gconfig = {} menu_gconfig[Relacion.__name__.lower()] = Relacion menu_gconfig[LineaBase.__name__.lower()] = LineaBase admin= MyAdminSysController(model, DBSession, config_type=MyAdminConfig, menu=menu_adm_sys) gconfig= MyAdminSysController(model, DBSession, config_type=MyAdmin2Config, menu=menu_gconfig) error = ErrorController() @expose('proyectosaptg.templates.index') def index(self): return dict(page='index') @expose('proyectosaptg.templates.about') @require(not_anonymous(msg='Por favor inicia sesion para continuar.')) def about(self): """Handle the 'about' page.""" return dict(page='about') @expose('proyectosaptg.templates.environ') @require(not_anonymous(msg='Por favor inicia sesion para continuar.')) def environ(self): """This method showcases TG's access to the wsgi environment.""" return dict(environment=request.environ) @expose('proyectosaptg.templates.data') @expose('json') def data(self, **kw): """This method showcases how you can use the same controller for a data page and a display page""" return dict(params=kw) @expose('proyectosaptg.templates.authentication') @require(not_anonymous(msg='Por favor inicia sesion para continuar.')) def auth(self): """Display some information about auth* on this application.""" return dict(page='auth') @expose('proyectosaptg.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('proyectosaptg.templates.index') @require(predicates.is_user('editor', msg=l_('Only for the editor'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('proyectosaptg.templates.login') def login(self, came_from=url('/')): """Start the user login.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from) @expose() def post_login(self, came_from='/'): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 redirect('/login', came_from=came_from, __logins=login_counter) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) redirect(came_from) @expose() def post_logout(self, came_from=url('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) redirect(came_from)