def create_dashboards(us): logger = logging.getLogger('lib.sapns.util.create_dashboards') #us = dbs.query(SapnsUser).get(id_user) logger.info('Creating dashboard for "%s"' % us.display_name) # user's dashboard dboard = us.get_dashboard() if not dboard: dboard = SapnsShortcut() dboard.user_id = us.user_id dboard.parent_id = None dboard.title = unicode(l_('Dashboard')) dboard.order = 0 dbs.add(dboard) dbs.flush() # data exploration data_ex = SapnsShortcut() data_ex.title = unicode(l_('Data exploration')) data_ex.parent_id = dboard.shortcut_id data_ex.user_id = us.user_id data_ex.order = 0 dbs.add(data_ex) dbs.flush() # Data exploration/Sapns sc_sapns = SapnsShortcut() sc_sapns.title = 'Sapns' sc_sapns.parent_id = data_ex.shortcut_id sc_sapns.user_id = us.user_id sc_sapns.order = 0 dbs.add(sc_sapns) # Data exploration/Project sc_project = SapnsShortcut() sc_project.title = config.get('app.name', unicode(l_('Project'))) sc_project.parent_id = data_ex.shortcut_id sc_project.user_id = us.user_id sc_project.order = 1 dbs.add(sc_project) dbs.flush() else: logger.info('Dashboard already exists')
def get_search_fields(self): return [ twf.TextField( 'output', label_text=l_('Output'), validator=twf.validators.String(if_missing=None), ) ]
def get_search_fields(self): return [ GroupSelector( 'supitemgroup', label_text=l_('Group'), validator=twf.validators.Int(if_invalid=None, if_missing=None), ) ]
def get_search_fields(self): options = [ ('', l_('All alerts')), # On doit passer un type basestring pour les options. # Donc, on convertit les constantes (entiers) en type str. (str(CorrEvent.ACK_NONE), l_('New alerts')), (str(CorrEvent.ACK_KNOWN), l_('Alerts marked as Acknowledged')), (str(CorrEvent.ACK_CLOSED), l_('Alerts marked as Closed')), ] return [ twf.TextField( 'trouble_ticket', label_text=l_('Trouble Ticket'), validator=twf.validators.String(if_missing=None), ), twf.SingleSelectField( 'ack', label_text=l_('Acknowledgement Status'), options=options, validator=twf.validators.OneOf( dict(options).keys(), if_invalid=None, if_missing=None, ), ), ]
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('sap.templates.index') def index(self): """Let the user know that's visiting a protected controller.""" flash(_("Secure Controller here")) return dict(page='index') @expose('sap.templates.index') def some_where(self): """Let the user know that this action is protected too.""" return dict(page='some_where')
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
class fields(WidgetsList): mediatype = HidingSingleSelectField(label_text=l_('Type'), size=SF_SIZE, options=[''] + media_types, mapping={'image': ['uploadfile'], 'video': ['uploadfile', 'fallbackfile'], 'youtube': ['uri'], 'vimeo': ['uri'], }, validator=All(NotEmpty, OneOf(media_types)), ) uri = TextField(label_text='URI', size=TF_SIZE, validator=All(UnicodeString, MaxLength(255))) uploadfile = FileField(label_text=l_('File to upload')) fallbackfile = FileField(label_text=l_('Fallback file')) languageid = SingleSelectField(label_text=l_('Language'), size=SF_SIZE) name = TextField(label_text=l_('Name'), size=TF_SIZE, validator=All(UnicodeString, NotEmpty, MaxLength(255))) description = TextArea(label_text=l_('Description'), rows=TA_ROWS, cols=TA_COLS) tagids = TextField(label_text=l_('Tags'), size=TF_SIZE, attrs=dict(title=l_('Comma separated list of tags')))
class fields(WidgetsList): _method = HiddenField(default='PUT', validator=None) mediaid = HiddenField(validator=NotEmpty) id_ = TextField(size=TF_SIZE, validator=None, disabled=True) mediatype_ = TextField(label_text=l_('Type'), size=TF_SIZE, validator=None, disabled=True) uri = TextField(label_text='URI', size=TF_SIZE, validator=All(UnicodeString, MaxLength(255))) languageid = CascadingSingleSelectField(label_text=l_('Language'), size=SF_SIZE, cascadeurl=tg.url('/media/translation'), extra=['mediaid']) version = CascadingSingleSelectField(label_text=l_('Version'), size=SF_SIZE, cascadeurl=tg.url('/media/version'), extra=['mediaid', 'languageid']) modified = TextField(disabled=True, label_text=l_('Last Modified'), validator=None) name = TextField(label_text=l_('Name'), size=TF_SIZE, validator=All(UnicodeString, NotEmpty, MaxLength(255))) description = TextArea(label_text=l_('Description'), rows=TA_ROWS, cols=TA_COLS) tagids = TextField(label_text=l_('Tags'), size=TF_SIZE, attrs=dict(title=l_('Comma separated list of tags')))
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('moksha.templates.index') def index(self): """Let the user know that's visiting a protected controller.""" flash(_("Secure Controller here")) if 'default_menu' in moksha.menus: tmpl_context.menu_widget = moksha.menus['default_menu'] else: tmpl_context.menu_widget = lambda: '' return dict(title='Moksha Administrator Controller') @expose('moksha.templates.index') def some_where(self): """Let the user know that this action is protected too.""" return dict(page='some_where')
class ComponentTypeController(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 = ComponentType class new_form_type(AddRecordForm): __model__ = ComponentType __omit_fields__ = ['components'] class edit_form_type(EditableForm): __model__ = ComponentType __omit_fields__ = ['id', 'components'] class edit_filler_type(EditFormFiller): __model__ = ComponentType class table_type(TableBase): __model__ = ComponentType __omit_fields__ = ['id', 'components'] class table_filler_type(TableFiller): __model__ = ComponentType
def update(self, id, last_modification, trouble_ticket, ack): """ Mise à jour d'un événement suivant les arguments passés. Cela peut être un changement de ticket ou un changement de statut. @param id: Le ou les identifiants des événements à traiter @param last_modification: La date de la dernière modification dont l'utilisateur est au courant. @param trouble_ticket: Nouveau numéro du ticket associé. @param ack: Nouvel état d'acquittement des événements sélectionnés. Cette méthode permet de satisfaire les exigences suivantes : - VIGILO_EXIG_VIGILO_BAC_0020, - VIGILO_EXIG_VIGILO_BAC_0060, - VIGILO_EXIG_VIGILO_BAC_0110. """ # On vérifie que des identifiants ont bien été transmis via # le formulaire, et on informe l'utilisateur le cas échéant. if id is None: flash(_('No event has been selected'), 'warning') raise redirect(request.environ.get('HTTP_REFERER', '/')) # On récupère la liste de tous les identifiants des événements # à mettre à jour. ids = [ int(i) for i in id.strip(',').split(',') ] user = get_current_user() events = VigiboardRequest(user) events.add_table( CorrEvent, Event, events.items.c.hostname, events.items.c.servicename, ) events.add_join((Event, CorrEvent.idcause == Event.idevent)) events.add_join((events.items, Event.idsupitem == events.items.c.idsupitem)) events.add_filter(CorrEvent.idcorrevent.in_(ids)) events.generate_request() idevents = [event[0].idcause for event in events.req] # Si des changements sont survenus depuis que la # page est affichée, on en informe l'utilisateur. last_modification = datetime.fromtimestamp(last_modification) cur_last_modification = get_last_modification_timestamp(idevents, None) if cur_last_modification and last_modification < cur_last_modification: flash(_('Changes have occurred since the page was last displayed, ' 'your changes HAVE NOT been saved.'), 'warning') raise redirect(request.environ.get('HTTP_REFERER', '/')) # Vérification que au moins un des identifiants existe et est éditable if not events.num_rows(): flash(_('No access to this event'), 'error') redirect('/') if ack == u'Forced': condition = Any( config.is_manager, has_permission('vigiboard-admin'), msg=l_("You don't have administrative access " "to VigiBoard")) try: condition.check_authorization(request.environ) except NotAuthorizedError, e: reason = unicode(e) flash(reason, 'error') raise redirect(request.environ.get('HTTP_REFERER', '/'))
class RootController(BaseController): """ The root controller for the IS2SAP application. """ #secc = SecureController() admin = AdminController(model, DBSession) item = ItemController() relacion = RelacionController() otros = OtrosController() error = ErrorController() @expose('is2sap.templates.index') def index(self): """Handle the front-page.""" return dict(page='index') @expose('is2sap.templates.despedida') def despedida(self): """Handle the front-page.""" return dict(page='despedida') @expose('is2sap.templates.configura') def configura(self): """Handle the 'about' page.""" return dict(page='config') @expose('is2sap.templates.desa') def desa(self): """Display some information about auth* on this application.""" return dict(page='desa') @expose('is2sap.templates.otros') def otras_op(self): """Display some information about auth* on this application.""" return dict(page='otros') @expose('is2sap.templates.index') @require( predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) #@require(predicates.in_group('Administrador', msg=l_('Solo para el administrador'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff') @expose('is2sap.templates.index') @require(predicates.in_group('editor', msg=l_('Solo para editores'))) def editor_user_only(self, **kw): """Illustrate how a page exclusive for the editor works.""" return dict(page='editor stuff') @expose('is2sap.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(_('Bienvenido, %s!') % userid) redirect("/index") @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 luego!')) redirect("/despedida")
class RolController(BaseController): @expose() def index(self): """Muestra la pantalla inicial""" return dict(nombre_modelo='Rol', page='index_rol') @expose('is2sap.templates.rol.nuevo') @require(predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def nuevo(self, **kw): """Despliega el formulario para añadir un nuevo Rol.""" try: tmpl_context.form = crear_rol_form except SQLAlchemyError: flash(_("No se pudo acceder a Creacion de Roles! SQLAlchemyError..."), 'error') redirect("/admin/rol/listado") except (AttributeError, NameError): flash(_("No se pudo acceder a Creacion de Roles! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/listado") return dict(nombre_modelo='Rol', page='nuevo_rol', value=kw) @validate(crear_rol_form, error_handler=nuevo) @expose() @require(predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def add(self, **kw): """Metodo para agregar un registro a la base de datos """ try: rol = Rol() rol.tipo = kw['tipo'] rol.nombre_rol = kw['nombre_rol'] rol.descripcion = kw['descripcion'] DBSession.add(rol) DBSession.flush() transaction.commit() except IntegrityError: transaction.abort() flash(_("No se ha guardado! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/listado") except SQLAlchemyError: flash(_("No se ha guardado! SQLAlchemyError..."), 'error') redirect("/admin/rol/listado") except (AttributeError, NameError): flash(_("No se ha guardado! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/listado") else: flash(_("Rol creado!"), 'ok') redirect("/admin/rol/listado") @expose("is2sap.templates.rol.listado") @require(predicates.has_any_permission('administracion')) def listado(self,page=1): """Metodo para listar todos los Roles existentes de la base de datos""" try: roles = DBSession.query(Rol).order_by(Rol.id_rol) currentPage = paginate.Page(roles, page, items_per_page=10) except SQLAlchemyError: flash(_("No se pudo acceder a Roles! SQLAlchemyError..."), 'error') redirect("/admin") except (AttributeError, NameError): flash(_("No se pudo acceder a Roles! Hay Problemas con el servidor..."), 'error') redirect("/admin") return dict(roles=currentPage.items, page='listado_rol', currentPage=currentPage) @expose('is2sap.templates.rol.editar') @require(predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def editar(self, id_rol, **kw): """Metodo que rellena el formulario para editar los datos de un Rol""" try: tmpl_context.form = editar_rol_form traerRol = DBSession.query(Rol).get(id_rol) kw['id_rol'] = traerRol.id_rol kw['tipo'] = traerRol.tipo kw['nombre_rol'] = traerRol.nombre_rol kw['descripcion'] = traerRol.descripcion except SQLAlchemyError: flash(_("No se pudo acceder a Edicion de Roles! SQLAlchemyError..."), 'error') redirect("/admin/rol/listado") except (AttributeError, NameError): flash(_("No se pudo acceder a Edicion de Roles! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/listado") return dict(nombre_modelo='Rol', page='editar_rol', value=traerRol) @validate(editar_rol_form, error_handler=editar) @expose() @require(predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def update(self, **kw): """Metodo que actualizar la base de datos""" try: rol = DBSession.query(Rol).get(kw['id_rol']) rol.tipo=kw['tipo'] rol.nombre_rol=kw['nombre_rol'] rol.descripcion = kw['descripcion'] DBSession.flush() transaction.commit() except IntegrityError: transaction.abort() flash(_("No se han guardado los cambios! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/listado") except SQLAlchemyError: flash(_("No se han guardado los cambios! SQLAlchemyError..."), 'error') redirect("/admin/rol/listado") except (AttributeError, NameError): flash(_("No se han guardado los cambios! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/listado") else: flash(_("Se han guardado los cambios!"), 'ok') redirect("/admin/rol/listado") @expose('is2sap.templates.rol.confirmar_eliminar') @require(predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def confirmar_eliminar(self, id_rol, **kw): """Despliega confirmacion de eliminacion""" try: rol=DBSession.query(Rol).get(id_rol) except SQLAlchemyError: flash(_("No se pudo acceder a Eliminacion de Roles! SQLAlchemyError..."), 'error') redirect("/admin/rol/listado") except (AttributeError, NameError): flash(_("No se pudo acceder a Eliminacion de Roles! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/listado") return dict(nombre_modelo='Rol', page='eliminar_rol', value=rol) @expose() @require(predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def delete(self, id_rol, **kw): """Metodo que elimina un registro de la base de datos""" try: DBSession.delete(DBSession.query(Rol).get(id_rol)) DBSession.flush() transaction.commit() except IntegrityError: transaction.abort() flash(_("No se ha eliminado! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/listado") except SQLAlchemyError: flash(_("No se ha eliminado! SQLAlchemyError..."), 'error') redirect("/admin/rol/listado") except (AttributeError, NameError): flash(_("No se ha eliminado! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/listado") else: flash(_("Rol eliminado!"), 'ok') redirect("/admin/rol/listado") @expose("is2sap.templates.rol.listar_permisos") @require(predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def permisos(self, id_rol, page=1): """Metodo para listar todos los permisos que tiene el rol seleccionado""" try: rol = DBSession.query(Rol).get(id_rol) permisos = rol.permisos currentPage = paginate.Page(permisos, page, items_per_page=10) except SQLAlchemyError: flash(_("No se pudo acceder a Permisos de Roles! SQLAlchemyError..."), 'error') redirect("/admin/rol/listado") except (AttributeError, NameError): flash(_("No se pudo acceder a Permisos de Roles! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/listado") return dict(permisos=currentPage.items, page='listar_permisos', currentPage=currentPage, rol=rol) @expose() @require(predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def eliminar_rol_permiso(self, id_rol, id_permiso, **kw): """Metodo que elimina un permiso al rol seleccionado""" try: permiso = DBSession.query(Permiso).get(id_permiso) rol = DBSession.query(Rol).get(id_rol) if permiso.roles.count(rol) >= 1: permiso.roles.remove(rol) DBSession.flush() transaction.commit() except IntegrityError: transaction.abort() flash(_("No se pudo desasignar el Permiso! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/permisos", id_rol=id_rol) except SQLAlchemyError: flash(_("No se pudo desasignar el Permiso! SQLAlchemyError..."), 'error') redirect("/admin/rol/permisos", id_rol=id_rol) except (AttributeError, NameError): flash(_("No se pudo desasignar el Permiso! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/permisos", id_rol=id_rol) except (ValueError): redirect("/admin/rol/permisos", id_rol=id_rol) else: flash(_("Permiso desasignado!"), 'ok') redirect("/admin/rol/permisos", id_rol=id_rol) @expose("is2sap.templates.rol.agregar_permisos") @require(predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def rolPermiso(self, id_rol, page=1): """Metodo que permite listar los permisos que se pueden agregar al rol seleccionado""" try: rol = DBSession.query(Rol).get(id_rol) permisosRol = rol.permisos permisos = DBSession.query(Permiso).all() for permiso in permisosRol: if permisos.count(permiso) >= 1: permisos.remove(permiso) currentPage = paginate.Page(permisos, page, items_per_page=10) except SQLAlchemyError: flash(_("No se pudo acceder a Asignar Permisos! SQLAlchemyError..."), 'error') redirect("/admin/rol/permisos", id_rol=id_rol) except (AttributeError, NameError): flash(_("No se pudo acceder a Asignar Permisos! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/permisos", id_rol=id_rol) return dict(permisos=currentPage.items, page='agregar_permisos', currentPage=currentPage, id_rol=id_rol, rol=rol) @expose() @require(predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def agregarPermiso(self, id_rol, id_permiso): """Metodo que realiza la agregacion de un permiso al rol selecccionado""" try: permiso = DBSession.query(Permiso).get(id_permiso) rol = DBSession.query(Rol).get(id_rol) permiso.roles.append(rol) DBSession.flush() transaction.commit() except IntegrityError: redirect("/admin/rol/rolPermiso",id_rol=id_rol) except SQLAlchemyError: flash(_("No se pudo asignar el Permiso! SQLAlchemyError..."), 'error') redirect("/admin/rol/rolPermiso",id_rol=id_rol) except (AttributeError, NameError): flash(_("No se pudo asignar el Permiso! Hay Problemas con el servidor..."), 'error') redirect("/admin/rol/rolPermiso",id_rol=id_rol) else: flash(_("Permiso asignado!"), 'ok') redirect("/admin/rol/rolPermiso",id_rol=id_rol)
class fields(WidgetsList): came_from = HiddenField() logins = HiddenField() login = TextField(label_text=l_('User Name')) password = PasswordField(label_text=l_('Password'))
class fields(WidgetsList): languageid = SingleSelectField(label_text=l_('Language'), size=SF_SIZE) name = TextField(label_text=l_('Name'), size=TF_SIZE, validator=All(UnicodeString, NotEmpty, MaxLength(50))) description = TextArea(label_text=l_('Description'), rows=TA_ROWS, cols=TA_COLS)
class fields(WidgetsList): _method = HiddenField(default='DELETE', validator=None) categoryid = HiddenField(validator=NotEmpty) id_ = TextField(size=TF_SIZE, validator=None, disabled=True) name_ = TextField(label_text=l_('Name'), size=TF_SIZE, validator=None, disabled=True)
class fields(WidgetsList): languageid = SingleSelectField(label_text=l_('Language'), size=SF_SIZE) name = TextField(label_text=l_('Name'), size=TF_SIZE, validator=All(UnicodeString, NotEmpty, MaxLength(255)))
class fields(WidgetsList): languageid = TextField(label_text='ID', validator=All(UnicodeString, NotEmpty, MaxLength(5))) name = TextField(label_text=l_('Name'), size=TF_SIZE, validator=All(UnicodeString, NotEmpty, MaxLength(50)))
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')
'SearchForm', 'create_search_form', ) class SearchForm(twf.TableForm): """ Formulaire de recherche dans les événements Affiche un champ texte pour l'hôte, le service, la sortie, le ticket d'incidence, et la date. Ce widget permet de répondre aux exigences suivantes : - VIGILO_EXIG_VIGILO_BAC_0070 - VIGILO_EXIG_VIGILO_BAC_0100 """ method = 'GET' style = 'display: none' fields = [ twf.HiddenField('page'), twf.HiddenField('sort'), twf.HiddenField('order') ] for plugin, instance in tg.config.get('columns_plugins', []): fields.extend(instance.get_search_fields()) create_search_form = SearchForm("search_form", submit_text=l_('Search'), action=tg.url('/'), )
class MiAdminConfig(AdminConfig): allow_only = has_permission( 'administracion', msg=l_('Only for people with the "administrador" permission')) default_index_template = "genshi:is2sap.templates.admin_principal"
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)
class UsuarioController(BaseController): @expose() def index(self): """Muestra la pantalla inicial""" return dict(nombre_modelo='Usuario', page='index_usuario') @expose('is2sap.templates.usuario.nuevo') @require( predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def nuevo(self, **kw): """Despliega el formulario para añadir un nuevo Usuario.""" try: tmpl_context.form = crear_usuario_form except SQLAlchemyError: flash( _("No se pudo acceder a Creacion de Usuarios! SQLAlchemyError..." ), 'error') redirect("/admin/usuario/listado") except (AttributeError, NameError): flash( _("No se pudo acceder a Creacion de Usuarios! Hay Problemas con el servidor..." ), 'error') redirect("/admin/usuario/listado") return dict(nombre_modelo='Usuario', page='nuevo_usuario', value=kw) @validate(crear_usuario_form, error_handler=nuevo) @expose() @require( predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def add(self, **kw): """Metodo para agregar un registro a la base de datos """ try: usuario = Usuario() usuario.nombre = kw['nombre'] usuario.apellido = kw['apellido'] usuario.nombre_usuario = kw['nombre_usuario'] usuario.password = kw['password'] usuario.direccion = kw['direccion'] usuario.telefono = kw['telefono'] usuario.email = kw['email'] DBSession.add(usuario) DBSession.flush() transaction.commit() except IntegrityError: transaction.abort() flash(_("No se ha guardado! Hay Problemas con el servidor..."), 'error') redirect("/admin/usuario/listado") except SQLAlchemyError: flash(_("No se ha guardado! SQLAlchemyError..."), 'error') redirect("/admin/usuario/listado") except (AttributeError, NameError): flash(_("No se ha guardado! Hay Problemas con el servidor..."), 'error') redirect("/admin/usuario/listado") else: flash(_("Usuario creado!"), 'ok') redirect("/admin/usuario/listado") @expose("is2sap.templates.usuario.listado") @require( predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def listado(self, page=1): """Metodo para listar todos los usuarios de la base de datos""" try: usuarios = DBSession.query(Usuario).order_by(Usuario.id_usuario) currentPage = paginate.Page(usuarios, page, items_per_page=10) except SQLAlchemyError: flash(_("No se pudo acceder a Usuarios! SQLAlchemyError..."), 'error') redirect("/admin") except (AttributeError, NameError): flash( _("No se pudo acceder a Usuarios! Hay Problemas con el servidor..." ), 'error') redirect("/admin") return dict(usuarios=currentPage.items, page='listado_usuario', currentPage=currentPage) @expose('is2sap.templates.usuario.editar') @require( predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def editar(self, id_usuario, **kw): """Metodo que rellena el formulario para editar los datos de un usuario""" try: tmpl_context.form = editar_usuario_form traerUsuario = DBSession.query(Usuario).get(id_usuario) kw['id_usuario'] = traerUsuario.id_usuario kw['nombre'] = traerUsuario.nombre kw['apellido'] = traerUsuario.apellido kw['nombre_usuario'] = traerUsuario.nombre_usuario kw['direccion'] = traerUsuario.direccion kw['telefono'] = traerUsuario.telefono kw['email'] = traerUsuario.email except SQLAlchemyError: flash( _("No se pudo acceder a Edicion de Usuarios! SQLAlchemyError..." ), 'error') redirect("/admin/usuario/listado") except (AttributeError, NameError): flash( _("No se pudo acceder a Edicion de Usuarios! Hay Problemas con el servidor..." ), 'error') redirect("/admin/usuario/listado") return dict(nombre_modelo='Usuario', page='editar_usuario', value=kw) @validate(editar_usuario_form, error_handler=editar) @expose() @require( predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def update(self, **kw): """Metodo que actualiza la base de datos""" try: usuario = DBSession.query(Usuario).get(kw['id_usuario']) usuario.nombre = kw['nombre'] usuario.apellido = kw['apellido'] usuario.nombre_usuario = kw['nombre_usuario'] usuario.direccion = kw['direccion'] usuario.telefono = kw['telefono'] usuario.email = kw['email'] DBSession.flush() transaction.commit() except IntegrityError: transaction.abort() flash( _("No se han guardado los cambios! Hay Problemas con el servidor..." ), 'error') redirect("/admin/usuario/listado") except SQLAlchemyError: flash(_("No se han guardado los cambios! SQLAlchemyError..."), 'error') redirect("/admin/usuario/listado") except (AttributeError, NameError): flash( _("No se han guardado los cambios! Hay Problemas con el servidor..." ), 'error') redirect("/admin/usuario/listado") else: flash(_("Se han guardado los cambios!"), 'ok') redirect("/admin/usuario/listado") @expose('is2sap.templates.usuario.confirmar_eliminar') @require( predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def confirmar_eliminar(self, id_usuario, **kw): """Despliega confirmacion de eliminacion""" try: usuario = DBSession.query(Usuario).get(id_usuario) except SQLAlchemyError: flash( _("No se pudo acceder a Eliminacion de Usuarios! SQLAlchemyError..." ), 'error') redirect("/admin/usuario/listado") except (AttributeError, NameError): flash( _("No se pudo acceder a Eliminacion de Usuarios! Hay Problemas con el servidor..." ), 'error') redirect("/admin/usuario/listado") return dict(nombre_modelo='Usuario', page='eliminar_usuario', value=usuario) @expose() @require( predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def delete(self, id_usuario, **kw): """Metodo que elimina un registro de la base de datos""" try: DBSession.delete(DBSession.query(Usuario).get(id_usuario)) DBSession.flush() transaction.commit() except IntegrityError: transaction.abort() flash(_("No se ha eliminado! Hay Problemas con el servidor..."), 'error') redirect("/admin/usuario/listado") except SQLAlchemyError: flash(_("No se ha eliminado! SQLAlchemyError..."), 'error') redirect("/admin/usuario/listado") except (AttributeError, NameError): flash(_("No se ha eliminado! Hay Problemas con el servidor..."), 'error') redirect("/admin/usuario/listado") else: flash(_("Usuario eliminado!"), 'ok') redirect("/admin/usuario/listado") @expose("is2sap.templates.usuario.listar_roles") @require( predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def roles(self, id_usuario, page=1): """Metodo para listar todos los roles que tiene el usuario seleccionado""" try: usuario = DBSession.query(Usuario).get(id_usuario) #roles = usuario.roles roles = [] rolesSistema = DBSession.query(Rol).filter_by(tipo="Sistema").all() for rol in rolesSistema: if usuario.roles.count(rol) == 1: roles.append(rol) currentPage = paginate.Page(roles, page, items_per_page=10) except SQLAlchemyError: flash( _("No se pudo acceder a Roles de Usuario! SQLAlchemyError..."), 'error') redirect("/admin/usuario/listado") except (AttributeError, NameError): flash( _("No se pudo acceder a Roles de Usuario! Hay Problemas con el servidor..." ), 'error') redirect("/admin/usuario/listado") return dict(roles=currentPage.items, page='listar_roles', currentPage=currentPage, usuario=usuario) @expose() @require( predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def eliminar_rol_usuario(self, id_usuario, id_rol, **kw): """Metodo que elimina un rol al usuario seleccionado""" try: rol = DBSession.query(Rol).get(id_rol) usuario = DBSession.query(Usuario).get(id_usuario) if rol.usuarios.count(usuario) >= 1: rol.usuarios.remove(usuario) DBSession.flush() transaction.commit() except IntegrityError: transaction.abort() flash( _("No se pudo Desasignar Rol! Hay Problemas con el servidor..." ), 'error') redirect("/admin/usuario/roles", id_usuario=id_usuario) except SQLAlchemyError: flash(_("No se pudo Desasignar Rol! SQLAlchemyError..."), 'error') redirect("/admin/usuario/roles", id_usuario=id_usuario) except (AttributeError, NameError): flash( _("No se pudo Desasignar Rol! Hay Problemas con el servidor..." ), 'error') redirect("/admin/usuario/roles", id_usuario=id_usuario) else: flash(_("Rol desasignado!"), 'ok') redirect("/admin/usuario/roles", id_usuario=id_usuario) @expose("is2sap.templates.usuario.agregar_roles") @require( predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def rolUsuario(self, id_usuario, page=1): """Metodo que permite listar los roles que se pueden agregar al usuario seleccionado""" try: usuario = DBSession.query(Usuario).get(id_usuario) rolesUsuario = usuario.roles roles = DBSession.query(Rol).filter_by(tipo="Sistema").all() for rol in rolesUsuario: if roles.count(rol) >= 1: roles.remove(rol) currentPage = paginate.Page(roles, page, items_per_page=10) except SQLAlchemyError: flash(_("No se pudo acceder a Agregar Roles! SQLAlchemyError..."), 'error') redirect("/admin/usuario/roles", id_usuario=id_usuario) except (AttributeError, NameError): flash( _("No se pudo acceder a Agregar Roles! Hay Problemas con el servidor..." ), 'error') redirect("/admin/usuario/roles", id_usuario=id_usuario) return dict(roles=currentPage.items, page='agregar_roles', currentPage=currentPage, id_usuario=id_usuario, usuario=usuario) @expose() @require( predicates.has_permission('administracion', msg=l_('Solo para el Administrador'))) def agregarRol(self, id_usuario, id_rol): """Metodo que realiza la agregacion de un rol al usuario selecccionado""" try: rol = DBSession.query(Rol).get(id_rol) usuario = DBSession.query(Usuario).get(id_usuario) rol.usuarios.append(usuario) DBSession.flush() transaction.commit() except IntegrityError: transaction.abort() flash( _("No se pudo Asignar Rol! Hay Problemas con el servidor..."), 'error') redirect("/admin/usuario/rolUsuario", id_usuario=id_usuario) except SQLAlchemyError: flash(_("No se pudo Asignar Rol! SQLAlchemyError..."), 'error') redirect("/admin/usuario/rolUsuario", id_usuario=id_usuario) except (AttributeError, NameError): flash( _("No se pudo Asignar Rol! Hay Problemas con el servidor..."), 'error') redirect("/admin/usuario/rolUsuario", id_usuario=id_usuario) else: flash(_("Rol asignado!"), 'ok') redirect("/admin/usuario/rolUsuario", id_usuario=id_usuario)
class fields(WidgetsList): _method = HiddenField(default='PUT', validator=None) languageid = HiddenField(validator=NotEmpty) id_ = TextField(validator=None, disabled=True) name = TextField(label_text=l_('Name'), size=TF_SIZE, validator=All(UnicodeString, NotEmpty, MaxLength(50)))
class fields(WidgetsList): _method = HiddenField(default='DELETE', validator=None) articleid = HiddenField(validator=NotEmpty) id_ = TextField(size=TF_SIZE, validator=None, disabled=True) title_ = TextField(label_text=l_('Title'), size=TF_SIZE, validator=None, disabled=True)
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 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)
################################################################################ """Le formulaire d'édition d'un événement.""" from pylons.i18n import lazy_ugettext as l_ from tw.api import WidgetsList from tw.forms import TableForm, SingleSelectField, TextField, \ HiddenField, Label __all__ = ( 'edit_event_status_options', 'EditEventForm', ) edit_event_status_options = [ ['NoChange', l_('No change')], ['None', l_('Change to None')], ['Acknowledged', l_('Change to Acknowledged')], ['AAClosed', l_('Change to Closed')], ['Forced', l_('Force to Closed')], ] # Énumère les valeurs possibles pour le champ "type_action" # dans la base de données et les marque comme nécessitant une traduction. valid_action_types = { u'Ticket change': l_('Ticket change'), u'Forced change state': l_('Forced change state'), u'Acknowledgement change state': l_('Acknowledgement change state'), u'Ticket change notification': l_('Ticket change notification'), u'New occurrence': l_('New occurrence'), u'Nagios update state': l_('Nagios update state'),
class ConfiguracionController(TGController): #linea_base = LineaBaseController() """ A basic controller that handles User Groups and Permissions for a TG application. """ #allow_only = in_group('managers') allow_only = has_permission('configuracion', msg=l_('Solo para usuarios con permiso "configuracion"')) default_index_template = "genshi:is2sap.templates.configura" def __init__(self, models, session, config_type=None, translations=None): super(ConfiguracionController, self).__init__() #if translations is None: # translations = {} # if config_type is None: # config = AdminConfig(models, translations) #else: #config = config_type(models, translations) #if config.allow_only: #self.allow_only = config.allow_only #self.config = config #self.session = session #self.default_index_template = ':'.join((tg_config.default_renderer, self.index.decoration.engines.get('text/html')[1])) #if self.config.default_index_template: #self.default_index_template = self.config.default_index_template @with_trailing_slash @expose('tgext.configura.templates.index') def index(self): #overrides the template for this method original_index_template = self.index.decoration.engines['text/html'] new_engine = self.default_index_template.split(':') new_engine.extend(original_index_template[2:]) self.index.decoration.engines['text/html'] = new_engine return dict(models=[model.__name__ for model in self.config.models.values()]) def _make_controller(self, config, session): m = config.model Controller = config.defaultCrudRestController class ModelController(Controller): model = m table = config.table_type(session) table_filler = config.table_filler_type(session) new_form = config.new_form_type(session) new_filler = config.new_filler_type(session) edit_form = config.edit_form_type(session) edit_filler = config.edit_filler_type(session) allow_only = config.allow_only menu_items = None if self.config.include_left_menu: menu_items = self.config.models return ModelController(session, menu_items) @expose() def _lookup(self, model_name, *args): model_name = model_name[:-1] try: model = self.config.models[model_name] except KeyError: raise HTTPNotFound().exception config = self.config.lookup_controller_config(model_name) controller = self._make_controller(config, self.session) return controller, args @expose() def lookup(self, model_name, *args): return self._lookup(model_name, *args)
def update_metadata(): logger = logging.getLogger('lib.sapns.update_metadata') managers = SapnsRole.by_name(ROLE_MANAGERS) #managers = SapnsRole() tables = extract_model(all=True) tables_id = {} pending_attr = {} for tbl in tables: logger.info('Table: %s' % tbl['name']) klass = dbs.query(SapnsClass).\ filter(SapnsClass.name == tbl['name']).\ first() if not klass: logger.warning('.....creating') klass = SapnsClass() klass.name = tbl['name'] klass.title = tbl['name'].title() desc = unicode(l_('Class: %s')) klass.description = desc % tbl['name'] dbs.add(klass) dbs.flush() # # grant access (r/w) to managers managers.add_privilege(klass.class_id) else: logger.warning('.....already exists') tables_id[tbl['name']] = klass.class_id # create an action def create_action(name, type_): action = dbs.query(SapnsPermission).\ filter(and_(SapnsPermission.class_id == klass.class_id, SapnsPermission.type == type_)).\ first() if not action: action = SapnsPermission() action.permission_name = '%s#%s' % (klass.name, name.lower()) action.display_name = name action.type = type_ action.class_id = klass.class_id dbs.add(action) dbs.flush() # add this action to "managers" role managers.permissions_.append(action) dbs.flush() elif action.type == SapnsPermission.TYPE_LIST: for s in action.shortcuts: s.title = action.class_.title dbs.add(s) dbs.flush() # create standard actions create_action(unicode(l_('New')), SapnsPermission.TYPE_NEW) create_action(unicode(l_('Edit')), SapnsPermission.TYPE_EDIT) create_action(unicode(l_('Delete')), SapnsPermission.TYPE_DELETE) create_action(unicode(l_('List')), SapnsPermission.TYPE_LIST) create_action(unicode(l_('Docs')), SapnsPermission.TYPE_DOCS) first_ref = False for i, col in enumerate(tbl['columns']): logger.info('Column: %s' % col['name']) attr = dbs.query(SapnsAttribute).\ filter(and_(SapnsAttribute.name == col['name'], SapnsAttribute.class_id == klass.class_id, )).\ first() if not attr and col['name'] != 'id': logger.warning('.....creating') attr = SapnsAttribute() attr.name = col['name'] attr.title = col['name'].replace('_', ' ').title() attr.class_id = klass.class_id attr.type = col['type_name'] if attr.type == SapnsAttribute.TYPE_STRING and not first_ref: attr.reference_order = 0 first_ref = True attr.visible = True attr.insertion_order = i if attr.type == SapnsAttribute.TYPE_INTEGER and \ not attr.name.startswith('id_'): # signed attr.field_regex = r'^\s*(\+|\-)?\d+\s*$' elif attr.type == SapnsAttribute.TYPE_FLOAT: # signed # col['prec'] # col['scale'] attr.field_regex = r'^\s*(\+|\-)?\d{1,%d}(\.\d{1,%d})?\s*$' % \ (col['prec']-col['scale'], col['scale']) elif attr.type == SapnsAttribute.TYPE_TIME: attr.field_regex = r'^\s*([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?\s*$' dbs.add(attr) dbs.flush() # grant access (r/w) to managers rw_access = SapnsAttrPrivilege.ACCESS_READWRITE managers.add_attr_privilege(attr.attribute_id, rw_access) else: logger.warning('.....already exists') # fill the "field_regex" if attr and not attr.field_regex: if attr.type == SapnsAttribute.TYPE_INTEGER and \ not attr.name.startswith('id_'): # signed attr.field_regex = r'^\s*(\+|\-)?\d+\s*$' elif attr.type == SapnsAttribute.TYPE_FLOAT: # signed attr.field_regex = r'^\s*(\+|\-)?\d{1,%d}(\.\d{1,%d})?\s*$' % \ (col['prec'] - col['scale'], col['scale']) elif attr.type == SapnsAttribute.TYPE_TIME: attr.field_regex = r'^\s*([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?\s*$' # foreign key if col['fk_table'] != None: pending_attr[attr.attribute_id] = col['fk_table'].name # update related classes for attr_id, fk_table in pending_attr.iteritems(): attr = dbs.query(SapnsAttribute).get(attr_id) attr.related_class_id = tables_id[fk_table] dbs.add(attr) dbs.flush()
def create_data_exploration(): managers = SapnsRole.by_name(ROLE_MANAGERS) #managers = SapnsRole() logger = logging.getLogger('lib.sapns.util.create_data_exploration') tables = extract_model(all=True) #['tables'] for us in dbs.query(SapnsUser).\ join((SapnsUserRole, and_(SapnsUserRole.user_id == SapnsUser.user_id, SapnsUserRole.role_id == managers.group_id, ))): create_dashboards(us) data_ex = us.get_dataexploration() sc_sapns = data_ex.by_order(0) sc_project = data_ex.by_order(1) # data exploration/project for i, tbl in enumerate(tables): cls = dbs.query(SapnsClass).\ filter(SapnsClass.name == tbl['name']).\ first() # look for this table "list" action act_table = dbs.query(SapnsPermission).\ filter(and_(SapnsPermission.type == SapnsPermission.TYPE_LIST, SapnsPermission.class_id == cls.class_id)).\ first() if not act_table: act_table = SapnsPermission() act_table.permission_name = '%s#%s' % (cls.name, SapnsPermission.TYPE_LIST) act_table.display_name = unicode(l_('List')) act_table.type = SapnsPermission.TYPE_LIST act_table.class_id = cls.class_id dbs.add(act_table) dbs.flush() # add to "managers" role managers.permissions_.append(act_table) dbs.flush() # project sc_parent = sc_project.shortcut_id if cls.name.startswith('sp_'): # sapns sc_parent = sc_sapns.shortcut_id sc_table = dbs.query(SapnsShortcut).\ filter(and_(SapnsShortcut.parent_id == sc_parent, SapnsShortcut.permission_id == act_table.permission_id, SapnsShortcut.user_id == us.user_id, )).\ first() # does this user have this class shortcut? if not sc_table: sc_table = SapnsShortcut() sc_table.title = tbl['name'] sc_table.parent_id = sc_parent sc_table.user_id = us.user_id sc_table.permission_id = act_table.permission_id sc_table.order = i dbs.add(sc_table) dbs.flush() else: logger.info('Shortcut for "%s" already exists' % cls.title) # TODO: sort (alphabetically) shortcuts inside "data exploration" logger.info('Sorting shortcuts inside "data exploration"') i = 0 for sc in dbs.query(SapnsShortcut).\ filter(SapnsShortcut.parent_id == sc_project.shortcut_id).\ order_by(SapnsShortcut.title): sc.order = i dbs.add(sc) dbs.flush() i += 1
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): @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)
class fields(WidgetsList): articleid = HiddenField(validator=All(UnicodeString, NotEmpty)) languageid = SingleSelectField(label_text=l_('Language'), size=SF_SIZE) name = TextField(label_text=l_('Name'), size=TF_SIZE, validator=All(UnicodeString, NotEmpty, MaxLength(255))) text = TextArea(label_text=l_('Text'), rows=TA_ROWS, cols=TA_COLS)
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)
def index(self, page=1, sort=None, order=None): """ Affiche la liste des règles de mise en silence enregistrées dans la BDD, que l'utilisateur pourra ensuite éditer ou supprimer. @param sort: (optionnel) Critère de tri de la liste des règles de mise en silence enregistrées. @type sort: C{str} @param order: (optionnel) Ordre de tri. @type order: C{str} """ # # On récupère la langue de l'utilisateur # lang = get_lang() # if not lang: # lang = ['fr'] # lang = lang[0] # On récupère tous les enregistrements de la table # silence, qu'ils concernent des hôtes, des services # de bas niveau, ou bien des services de haut niveau. silences = self.query_silences() # On trie ces enregistrements selon le critère choisi # par l'utilisateur (par défaut, la date d'ajout). sort_keys = { 'hostname': 'hostname', 'servicename': 'servicename', 'lastmodification': Silence.lastmodification, 'author': Silence.author, 'comment': Silence.comment, # 'start': Silence.start, # 'end': Silence.end, 'states': 'states', } if sort in sort_keys.keys(): # Tri dans l'ordre croissant if order != 'desc': silences = silences.order_by(asc(sort_keys[sort])) # Tri dans l'ordre décroissant else: silences = silences.order_by(desc(sort_keys[sort])) # On calcule la pagination page = paginate.Page(silences, page=page, items_per_page=int(config['vigiboard_items_per_page'])) # # On initialise les widgets des calendriers # # utilisés dans le formulaire de mise en silence. # start_calendar = CalendarDateTimePicker('start', # button_text = l_("Choose a date"), # date_format = '%Y-%m-%d %H:%M', # calendar_lang = lang) # end_calendar = CalendarDateTimePicker('end', # button_text = l_("Choose a date"), # date_format = '%Y-%m-%d %H:%M', # calendar_lang = lang) # Traduction du nom des colonnes columns = [ ('hostname', l_('Host')), ('servicename', l_('Service')), ('states', l_('States')), ('lastmodification', l_('Last modification')), ('author', l_('Author')), ('comment', l_('Comment')) ] return dict( page=page, sort=sort, order=order, # start_calendar=start_calendar, # end_calendar=end_calendar, columns=columns )
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)
class RootController(BaseController): # secc = SecureController() # admin = AdminController(model, DBSession, config_type=TGAdminConfig) data = DataController() error = ErrorController() # The index page is the simply login page @expose('abchat.templates.login') def index(self): if request.identity is not None: redirect('/post_login') return dict() # Login page # Just exposes the login.html page in templates @expose('abchat.templates.login') def login(self): return dict() # Post_login handler # This will verify the user for us using repoze.what # and then redirect us to the login again if the credentials were # invalid, with a flash message, or to a temporary page if the # login attempt was valid @expose('abchat.templates.login') def post_login(self): if not request.identity: login_counter = request.environ['repoze.who.logins'] + 1 flash(_('Wrong credentials'), 'warning') return dict() userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) redirect('root') # Register page # Exposes the register.html page in templates @expose('abchat.templates.register') def register(self): return dict() # Registration Handling Code # Just checks that the passwords match and that the username does not # already exist. If all is good, we add the user to the DB, otherwise # a flash error message shows. # The parameters x, y, Submit.x, Submit.y are the coordinates of the mouse, # I believe and the function won't work without them (though we don't care # about their value...) @expose('abchat.templates.register') def register_handler(self, username=None, password=None, confirm_password=None, y=None, x=None, Submit=None): DBSession = DBSessionmaker() if password == confirm_password and username is not None and password is not None and confirm_password is not None: if DBSession.query(User).filter( User.user_name == username).count() == 0: newuser = User(username, password, 0) normal = DBSession.query(Group).filter( Group.group_name == 'normal').first() newuser.groups = newuser.groups + [normal] DBSession.add(newuser) DBSession.commit() flash(_('Successfully Registered, %s!') % username) redirect('/') else: flash(_('Username %s already registered') % username) redirect('/register') elif password != confirm_password: flash(_('Passwords do not match')) redirect('/register') else: flash(_('Insufficient information')) redirect('/register') return # Logout function # A simple redirect to the actual logout function # Clean up if guest account... @expose() def logout(self, came_from='/'): if request.identity is not None: username = request.identity['repoze.who.userid'] if 'GUEST-' in username: DBSession = DBSessionmaker() try: u = DBSession.query(User).filter( User.user_name == username).all() except: DBSession.close() redirect('/logout_handler') if len(u) == 0: DBSession.close() redirect('/logout_handler') buds = DBSession.query(Buddies).filter( or_(Buddies.user_initiated == u[0], Buddies.user_target == u[0])).all() msgs = DBSession.query(Message).filter( or_(Message.uto == u[0], Message.ufrom == u[0])).all() try: buds = DBSession.query(Buddies).filter( or_(Buddies.user_initiated == u[0], Buddies.user_target == u[0])).all() msgs = DBSession.query(Message).filter( or_(Message.uto == u[0], Message.ufrom == u[0])).all() except: DBSession.close() redirect('/logout_handler') DBSession.delete(u[0]) for b in buds: DBSession.delete(b) for m in msgs: DBSession.delete(m) DBSession.commit() DBSession.close() redirect('/logout_handler') # Logout function # Repoze will take care of the user's DBSession, we just # have to redirect them and show a pretty flash message @expose() def post_logout(self, came_from='/'): flash(_('We hope to see you soon!')) redirect('/') # Main Page # This function displays the main page for logged in users @expose('abchat.templates.root2') @require( predicates.has_permission('normal', msg=l_('You must login to view this page'))) def root(self): # redirect('/data/get_buddies') if request.identity is None: redirect('/') user = request.identity['repoze.who.userid'] if user is None: return dict() return dict(username=[user]) # Guest account # First it gets the number of the next guest account, and then it creates a new guest # account GUEST-#+1, with password abc. Then it forwards this to auto_login to # log the new guest into the system. @expose() def guest(self): DBSession = DBSessionmaker() guests = DBSession.query(User).order_by(User.user_name).all() try: guests = DBSession.query(User).order_by(User.user_name).all() except: DBSession.close() redirect('/') last = -1 for guest in guests: if 'GUEST-' in guest.user_name: tmp = int(guest.user_name.split('GUEST-')[1]) if tmp > last: last = tmp username = '******' + str(last + 1) password = '******' confirm_password = '******' if password == confirm_password and username is not None and password is not None and confirm_password is not None: if DBSession.query(User).filter( User.user_name == username).count() == 0: newuser = User(username, password, 0) normal = DBSession.query(Group).filter( Group.group_name == 'normal').first() newuser.groups = newuser.groups + [normal] DBSession.add(newuser) DBSession.commit() DBSession.close() redirect('/auto_login?username='******'&password='******'Username %s already registered') % username) DBSession.close() redirect('/') elif password != confirm_password: flash(_('Passwords do not match')) DBSession.close() redirect('/') else: flash(_('Insufficient information')) DBSession.close() redirect('/') # Auto_login employs a silly automatic login hack # basically, with the passed username and passowrd, it returns a # pre-filled in form which a Javascript onLoad event automatically # submits, logging the user in with these credentials. @expose('abchat.templates.auto') def auto_login(self, username, password): return dict(username=username, password=password)
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)
def create_data_exploration(): managers = SapnsRole.by_name(ROLE_MANAGERS) #managers = SapnsRole() logger = logging.getLogger('lib.sapns.util.create_data_exploration') tables = extract_model(all=True) #['tables'] for us in dbs.query(SapnsUser).\ join((SapnsUserRole, and_(SapnsUserRole.user_id == SapnsUser.user_id, SapnsUserRole.role_id == managers.group_id, ))): create_dashboards(us) data_ex = us.get_dataexploration() sc_sapns = data_ex.by_order(0) sc_project = data_ex.by_order(1) # data exploration/project for i, tbl in enumerate(tables): cls = dbs.query(SapnsClass).\ filter(SapnsClass.name == tbl['name']).\ first() # look for this table "list" action act_table = dbs.query(SapnsPermission).\ filter(and_(SapnsPermission.type == SapnsPermission.TYPE_LIST, SapnsPermission.class_id == cls.class_id)).\ first() if not act_table: act_table = SapnsPermission() act_table.permission_name = '%s#%s' % ( cls.name, SapnsPermission.TYPE_LIST) act_table.display_name = unicode(l_('List')) act_table.type = SapnsPermission.TYPE_LIST act_table.class_id = cls.class_id dbs.add(act_table) dbs.flush() # add to "managers" role managers.permissions_.append(act_table) dbs.flush() # project sc_parent = sc_project.shortcut_id if cls.name.startswith('sp_'): # sapns sc_parent = sc_sapns.shortcut_id sc_table = dbs.query(SapnsShortcut).\ filter(and_(SapnsShortcut.parent_id == sc_parent, SapnsShortcut.permission_id == act_table.permission_id, SapnsShortcut.user_id == us.user_id, )).\ first() # does this user have this class shortcut? if not sc_table: sc_table = SapnsShortcut() sc_table.title = tbl['name'] sc_table.parent_id = sc_parent sc_table.user_id = us.user_id sc_table.permission_id = act_table.permission_id sc_table.order = i dbs.add(sc_table) dbs.flush() else: logger.info('Shortcut for "%s" already exists' % cls.title) # TODO: sort (alphabetically) shortcuts inside "data exploration" logger.info('Sorting shortcuts inside "data exploration"') i = 0 for sc in dbs.query(SapnsShortcut).\ filter(SapnsShortcut.parent_id == sc_project.shortcut_id).\ order_by(SapnsShortcut.title): sc.order = i dbs.add(sc) dbs.flush() i += 1