Beispiel #1
0
 def export(self, **kw):
     try:
         current = dt.now()
         dateStr = current.strftime("%Y%m%d")
         fileDir = os.path.join(config.get("public_dir"), "report", 'inventory', dateStr)
         if not os.path.exists(fileDir):
             os.makedirs(fileDir)
         templatePath = os.path.join(config.get("public_dir"), 'TEMPLATE', "INVENTORY_TEMPLATE_AE.xlsx")
         if in_group('Buyer'):
             templatePath = os.path.join(config.get("public_dir"), 'TEMPLATE', "INVENTORY_TEMPLATE.xlsx")
         tempFileName = os.path.join(fileDir, "tmp_%s.xlsx" % current.strftime("%Y%m%d%H%M%S"))
         realFileName = os.path.join(fileDir, "report_%s.xlsx" % current.strftime("%Y%m%d%H%M%S"))
         shutil.copy(templatePath, tempFileName)
         report_xls = InventoryExcel(templatePath=tempFileName, destinationPath=realFileName)
         data = []
         if kw:
             if in_group('Buyer'):
                 data = self._query_buyer_result(kw)
             else:
                 data = self._query_ae_result(kw)
         report_xls.inputData(data=data)
         report_xls.outputData()
         try:
             os.remove(tempFileName)
         except:
             pass
         return serveFile(unicode(realFileName))
     except:
         traceback.print_exc()
         flash("Export Fail.")
         redirect("/inventory/report")
Beispiel #2
0
def is_admin(bquser=None):
    'return whether current user has admin priveledges'
    if bquser:
        groups = bquser.get_groups()
        return any((g.group_name == 'admin' or g.group_name == 'admins')
                   for g in groups)

    return in_group('admins').is_met(
        request.environ) or in_group('admin').is_met(request.environ)
Beispiel #3
0
    def _query_result(self, kw):
        try:
            conditions = []

            if kw.get("orderNO", False):
                conditions.append(OrderInfoHeader.orderNO == kw.get("orderNO", ""))
                
            if kw.get("orderDate", False):
                b_date = dt.strptime(kw.get("orderDate", '2009-12-1200:00:00') + "00:00:00", "%Y-%m-%d%H:%M:%S")
                
                conditions.append(OrderInfoHeader.orderDate >= b_date)
            
            if kw.get("vendorPO", False):
                conditions.append(OrderInfoHeader.vendorPO.op("ILIKE")("%%%s%%" % kw.get("vendorPO", "").strip()))
            
            if kw.get("item_no", False):
                item = DBSession.query(Item)\
                                .filter(Item.item_number == kw.get("item_no", "").strip())\
                                .first()
                dtlHeaderIDs = DBSession.query(OrderInfoDetail.headerID).filter(OrderInfoDetail.itemID == item.id).all()
                conditions.append(OrderInfoHeader.id.in_([id[0] for id in dtlHeaderIDs]))

            if len(conditions):
                order = DBSession.query(OrderInfoHeader).filter(OrderInfoHeader.status != 0)

                for condition in conditions:
                    order = order.filter(condition)

                if in_group("AE") or in_group("Admin"):
                    result = order.order_by(desc(OrderInfoHeader.orderDate)).all()
                else:
                    result = order.filter(OrderInfoHeader.issuedBy == request.identity['user'])\
                                    .order_by(desc(OrderInfoHeader.orderDate)).all()
            else:
                if in_group("AE") or in_group("Admin"):
                    result=DBSession.query(OrderInfoHeader)\
                                    .filter(OrderInfoHeader.status != 0)\
                                    .order_by(desc(OrderInfoHeader.orderDate))\
                                    .all()
                else:
                    result=DBSession.query(OrderInfoHeader)\
                                    .filter(OrderInfoHeader.status != 0)\
                                    .filter(OrderInfoHeader.issuedBy == request.identity['user'])\
                                    .order_by(desc(OrderInfoHeader.orderDate))\
                                    .all()

            return result
        except:
            traceback.print_exc()
Beispiel #4
0
def protect_obj_modify(protected_obj=None):
    p = protected_obj
    if p:
        if not Any(is_user(p.user.user_name), 
                   has_permission('dmirr_admin'), 
                   in_group(p.group.group_name)):
            raise NotAuthorizedError
Beispiel #5
0
def protect_product_release_obj(protected_obj=None):
    p = protected_obj
    if p:
        if not Any(is_user(p.product.project.user.user_name), 
                   has_permission('dmirr_admin'), 
                   in_group(p.product.project.group.group_name)):
            raise NotAuthorizedError
Beispiel #6
0
    def search(self,id=None,page=1):
        identity = request.environ.get('repoze.who.identity')
        c.menu_items = h.top_menu(self.menu_items,_('Shop online'))
        action = request.params.getone('action')
        values = dict(request.params)
        del values['action']            

        if is_met(in_group('customer')):
            schema = InvoiceSearchCustomer()
            try:
                result = schema.to_python(dict(request.params), c)
            except Invalid, e:
                html = render('/derived/invoice/customer/index.html')
                return htmlfill.render(html, defaults=values, errors=variabledecode.variable_encode(
                    e.unpack_errors() or {},
                    add_repetitions=False
                ))
            querystr = "Session.query(Invoice).filter_by(deleted=False).join(Invoice.customer).filter(User.user_name == '%s')"%identity['user'].user_name            
            products = result['contains_product']
            if products :
                querystr += ".join(Invoice.invoice_items).join(Invoice_item.product)"
                if len(products)>1:
                    querystr += ".filter(and_("
                    for item in products:
                        querystr += ","
                        querystr += "Product.name.like('%%%s%%')"%item
                    querystr += "))"
                else:
                    querystr += ".filter(Product.name.like('%%%s%%'))"%products[0]
Beispiel #7
0
def application(environ, start_response):
    req = Request(environ)
    resp = Response()
    resp.content_type = 'text/plain'
    resp.body = 'anonymous'
    if req.path_info == '/auth' and not environ.get('repoze.what.credentials'):
        return exc.HTTPUnauthorized()(environ, start_response)
    if req.path_info == '/secure':

        ident = environ.get('repoze.who.identity', {})
        body = 'repoze.who.identity = {\n'
        for k, v in ident.items():
            if k.lower() != 'password':
                body += '    %r: %r,\n' % (k, v)
        body += '}\n\n'

        cred = environ.get('repoze.what.credentials', {})
        body += 'repoze.what.credentials = {\n'
        for k, v in cred.items():
            body += '    %r: %r,\n' % (k, v)
        body += '}\n\n'

        for group in ('svn', 'bureau', 'other'):
            body += 'in_group(%r) == %s\n' % (group,
                                              in_group(group).is_met(environ))

        for perm in ('read', 'write'):
            body += 'has_permision(%r) == %s\n' % (
                perm, has_permission(perm).is_met(environ))

        resp.body = body
    return resp(environ, start_response)
Beispiel #8
0
 def evaluate(self, environ, credentials):
     if hasattr(tmpl_context, 'user') and hasattr(tmpl_context, 'project'):
         userid = credentials.get('repoze.what.userid')
         if tmpl_context.user in tmpl_context.project.admins:
             return
         elif in_group('administrators'):
             return
     self.unmet()
Beispiel #9
0
class SecurePanel(WSGIController):
    """Mock Pylons secure controller"""
    def index(self):
        return 'you are in the panel'

    @ActionProtector(in_group('developers'))
    def commit(self):
        return 'you can commit'
Beispiel #10
0
   def index(self, mb=None, id=None, folder='INBOX', to=None, 
         busy=None, unavail=None, greet=None):
      ''' List messages
      '''

      log.debug('mb=%s, id=%s, folder=%s, to=%s, busy=%s, unavail=%s, greet=%s' % (
            mb, id, folder, to, busy, unavail, greet))

      grid = MyJqGrid( id='grid', url='fetch', 
            caption=u"%s" % folders[folder],
            sortname='id', sortorder='asc',
            colNames = [u'Action', u'Extension',
               u'Message', u'De', u'Date', u'Ecoute' ],
            colModel = [ { 'width': 60, 'align': 'center', 'sortable': False },
               { 'name': 'mb', 'width': 60 },
               { 'name': 'id', 'width': 60 },
               { 'name': 'callerid', 'width': 100 },
               { 'name': 'origdate', 'width': 100 },
               { 'width': 60, 'align': 'center', 'sortable': False },
               ],
            navbuttons_options = {'view': False, 'edit': False, 'add': False,
               'del': False, 'search': False, 'refresh': True},
            postData = {'folder': folder},
         )

      tmpl_context.grid = grid

      tmpl_context.form2 = None if in_group('admin') else \
         TableForm(
            'messages_form', name = 'messages_form',
            fields = [
               Label(text = u'Nouveaux messages personnalisés :'),
               FileField('greet', 
                  validator=FieldStorageUploadConverter(not_empty=False),
                  label_text=u'Nom', 
#                  help_text=u'Fichier au format WAV'
                  ),
               FileField('unavail', 
                  validator=FieldStorageUploadConverter(not_empty=False),
                  label_text=u'Indisponible',
#                  help_text=u'Fichier au format WAV'
                  ),
               FileField('busy', 
                  validator=FieldStorageUploadConverter(not_empty=False),
                  label_text=u'Occupé', 
#                  help_text=u'Fichier au format WAV'
                  ),
            ],
            submit_text = u'Valider...',
            action = 'custom_messages',
#            hover_help = True
         )

      tmpl_context.form = folder_form
      return dict( title=u"Messages vocaux", debug='', 
            values={'folder': folder}, values2={'greet': 'Mon nom', 
               'unavail': 'Indisponible', 'busy': 'Occupé'})
Beispiel #11
0
    def query_silences(self):
        """
        Retourne une requête SQLAlchemy interrogeant
        la table des mises en silence
        """

        # Si l'utilisateur fait partie du groupe 'managers', on récupère la
        # liste de tous les supitems de la base de données
        if in_group('managers').is_met(request.environ):
            lls_query = DBSession.query(
                    LowLevelService.idservice.label('idsupitem'),
                    LowLevelService.servicename.label("servicename"),
                    Host.name.label('hostname')
                ).join((Host, Host.idhost == LowLevelService.idhost))

            host_query = DBSession.query(
                    Host.idhost.label('idsupitem'),
                    "NULL",
                    Host.name.label('hostname')
                )

            supitems = lls_query.union(host_query).subquery()

        # Sinon on ne récupère que les supitems auxquels l'utilisateurs a accès
        else:
            user_name = request.identity['repoze.who.userid']
            supitems = DBSession.query(
                UserSupItem.idsupitem.label('idsupitem'),
                UserSupItem.servicename.label("servicename"),
                UserSupItem.hostname.label('hostname')
            ).filter(
                UserSupItem.username == user_name
            ).distinct().subquery()

        # On interroge la base pour avoir la liste des règles de mise en silence
        # correspondant à ces supitems.
        states = DBSession.query(
                StateName.statename,
                SILENCE_STATE_TABLE.c.idsilence,
            ).join((SILENCE_STATE_TABLE,
                StateName.idstatename == SILENCE_STATE_TABLE.c.idstate)
            ).order_by(StateName.statename
            ).subquery()
        states = DBSession.query(
                states.c.idsilence,
                group_concat(states.c.statename, ', ').label('states'),
            ).group_by(states.c.idsilence
            ).subquery()
        silences = DBSession.query(
                Silence,
                supitems.c.hostname,
                supitems.c.servicename,
                states.c.states
            ).join((supitems, supitems.c.idsupitem == Silence.idsupitem)
            ).join((states, states.c.idsilence == Silence.idsilence))

        return silences
Beispiel #12
0
class SecurePanel(TGController):
    """Mock TG2 secure controller"""
    @expose()
    def index(self):
        return 'you are in the panel'

    @expose()
    @ActionProtector(in_group('developers'))
    def commit(self):
        return 'you can commit'
Beispiel #13
0
 def update(self):
     ftype = request.params.get('type',False)      
     if ftype == 'selected':
         pass
     else:
         if is_met(has_permission(u'edit_invoice')):
             return self._admin_update(request)
         elif is_met(in_group('customer')):
             h.flash(_('You can only delete an unconfirmed invoices. If you want to change anything in a shipping order contact us by phone'))
             return redirect(controller='invoice',action='index')
Beispiel #14
0
class BasicPylonsController(WSGIController):
    """Mock Pylons controller"""

    sub1 = SubController1()

    panel = SecurePanel()

    def index(self, **kwargs):
        return 'hello world'

    @ActionProtector(in_group('admins'))
    def admin(self, *args, **kwargs):
        return 'got to admin'

    def troll_detected(reason):
        # Let's ignore the reason
        return 'Trolls are banned'

    @ActionProtector(All(not_anonymous(), Not(is_user('sballmer'))),
                     denial_handler=troll_detected)
    def leave_comment(self):
        return 'Comment accepted'

    @special_require(not_anonymous())
    def logout(self):
        return 'You have been logged out'

    @special_require(All(not_anonymous(), Not(is_user('sballmer'))),
                     denial_handler=troll_detected)
    def start_thread(self):
        return 'You have started a thread'

    @ActionProtector(Not(not_anonymous()))
    def get_parameter(self, something):
        # Checking that parameters are received
        return 'Parameter received: %s' % something

    def boolean_predicate(self):
        p = not_anonymous()
        return 'The predicate is %s' % bool(p)

    def is_met_util(self):
        if is_met(not_anonymous()):
            return 'You are not anonymous'
        return 'You are anonymous'

    def not_met_util(self):
        if not_met(not_anonymous()):
            return 'You are anonymous'
        return 'You are not anonymous'
def application(environ, start_response):
    req = Request(environ)
    resp = Response()
    resp.content_type = 'text/plain'
    resp.body = 'anonymous'
    if req.path_info == '/secure':
        body = ''
        cred = environ.get('repoze.what.credentials', {})
        for k, v in cred.items():
            body += '%s: %s\n' % (k, v)
        for group in ('admin', 'others'):
            body += 'in_group(%r): %s\n' % (group, in_group(group).is_met(environ))
        for perm in ('read', 'write'):
            body += 'has_permision(%r): %s\n' % (perm, has_permission(perm).is_met(environ))
        resp.body = body
    return resp(environ, start_response)
def application(environ, start_response):
    req = Request(environ)
    resp = Response()
    resp.content_type = 'text/plain'
    resp.body = 'anonymous'
    if req.path_info == '/secure':
        body = ''
        cred = environ.get('repoze.what.credentials', {})
        for k, v in cred.items():
            body += '%s: %s\n' % (k, v)
        for group in ('admin', 'others'):
            body += 'in_group(%r): %s\n' % (group,
                                            in_group(group).is_met(environ))
        for perm in ('read', 'write'):
            body += 'has_permision(%r): %s\n' % (
                perm, has_permission(perm).is_met(environ))
        resp.body = body
    return resp(environ, start_response)
Beispiel #17
0
class RootController(BaseController):
    def index(self):
        return render('index.mako')

    @ActionProtector(is_user('test'))
    def user(self):
        return render('loggedin.mako')

    @ActionProtector(is_user('nottest'))
    def notuser(self):
        return render('loggedin.mako')

    @ActionProtector(in_group('admin'))
    def admin(self):
        return render('loggedin.mako')

    @ActionProtector(has_permission('edit'))
    def edit(self):
        return render('loggedin.mako')
Beispiel #18
0
 def index(self,id=None,page=1):       
     identity = request.environ.get('repoze.who.identity')
     c.menu_items = h.top_menu(self.menu_items,_('Shop online'))
     if is_met(in_group('customer')):
         if session.has_key('invoice_querystr'):
             invoices2 = eval(session['invoice_querystr']+".order_by(desc(Invoice.date_time))")
             #invoices = Session.query(Invoice).filter_by(customer=identity['user']).filter_by(deleted=False).order_by(Invoice.date_time)                
             c.paginator = paginate.Page(invoices2,
                                         page=int(request.params.get('page',page)),
                                         items_per_page=10)
             html = render('/derived/invoice/customer/index.html')
             return htmlfill.render(html, defaults=session['invoice_search_values'], errors={})
         else:
             invoices = Session.query(Invoice).filter_by(customer=identity['user']).filter_by(deleted=False).order_by(desc(Invoice.date_time))
             c.paginator = paginate.Page(invoices,
                                         page=int(request.params.get('page',page)),
                                         items_per_page=10)                                                 
             return render('/derived/invoice/customer/index.html')
  
     else:
         h.flash(_('Please take a few moments to %s\n')%(h.link_to(_("register"),url(controller="user", action="new"))))
         return redirect(url(controller='home',action='index'))
Beispiel #19
0
 def tocancel(self, **kw):
     headerID = kw.get('headerID')
     reHeader = getOr404(ReceiveItemHeader, headerID)
     twenty_minutes = timedelta(minutes=20)
     if dt.now() > reHeader.createTime + twenty_minutes and not in_group('Admin'):
         flash("More than twenty minutes, So can not cancel!", "warn")
         redirect('/receive/view?recid=%s' % headerID)
     try:
         reHeader.active = 1
         reHeader.remark += '    Cancel'
         reHeader.lastModifyTime = dt.now()
         reHeader.lastModifyBy = request.identity["user"]
         DBSession.query(ReceiveItem).filter(and_(ReceiveItem.headerID == reHeader.id,
             ReceiveItem.active == 0)).update({ReceiveItem.active: 1,
                                                 ReceiveItem.lastModifyTime: dt.now(),
                                                 ReceiveItem.lastModifyById: request.identity["user"].user_id})
     except:
         transaction.doom()
         traceback.print_exc()
         flash("The service is not avaiable now!", "warn")
         redirect('/receive/view?recid=%s' % headerID)
     else:
         flash("Cancel successfully!")
         redirect('/receive/index')
Beispiel #20
0
class RolesController(BaseController):

    allow_only = authorize.not_anonymous()

    @expose('sapns/roles/users.html')
    @require(p.in_group(u'managers'))
    @add_language
    def users(self, id_role, **kw):

        logger = logging.getLogger('RolesController.roles')
        try:
            role = dbs.query(SapnsRole).get(int(id_role))

            users = []
            for u in dbs.query(SapnsUser):

                has_role = dbs.query(SapnsUserRole).\
                    filter(and_(SapnsUserRole.role_id == role.group_id,
                                SapnsUserRole.user_id == u.user_id,
                                )).\
                    first()

                users.append(
                    dict(
                        id=u.user_id,
                        name=u.user_name,
                        selected=has_role != None,
                    ))

            return dict(page='Role users',
                        came_from=kw.get('came_from'),
                        role=dict(id=role.group_id, name=role.group_name),
                        users=users)

        except Exception, e:
            logger.error(e)
Beispiel #21
0
                        row_id=i,
                        who=user.user_id,
                        what=_('delete'),
                    )

            dbs.flush()

            # success!
            return dict(status=True)

        except Exception, e:
            logger.error(e)
            return dict(status=False, message=str(e), rel_tables=rel_tables)

    @expose('sapns/order/insert.html')
    @require(p.in_group(u'managers'))
    @add_language
    def ins_order(self, cls, came_from='/'):

        user = dbs.query(SapnsUser).get(request.identity['user'].user_id)

        # check privilege on this class
        if not user.has_privilege(cls):
            redirect(
                url('/message',
                    params=dict(message=_(
                        'Sorry, you do not have privilege on this class'),
                                came_from=came_from)))

        class_ = SapnsClass.by_name(cls)
Beispiel #22
0
 def is_admin(self):
     return in_group('admins').is_met(self.environ)
Beispiel #23
0
class AdminController(ServiceController):
    """
        The admin controller is a central point for
        adminstrative tasks such as monitoring, data, user management, etc.
    """
    service_type = "admin"

    allow_only = Any(in_group("admin"), in_group('admins'))
    #allow_only = is_user('admin')

    #admin = BisqueAdminController([User, Group], DBSession)
    @expose("bq.admin_service.templates.manager")
    def manager(self):
        return dict()

    @expose(content_type='text/xml')
    def _default(self, *arg, **kw):
        """
            Returns some command information
        """
        log.info('admin/index')
        index_xml = etree.Element('resource', uri=str(request.url))
        users_xml = etree.SubElement(index_xml,
                                     'command',
                                     name='user',
                                     value='Lists all the users')
        users_xml = etree.SubElement(index_xml,
                                     'command',
                                     name='user/RESOURCE_UNIQ',
                                     value='Lists the particular user')
        users_xml = etree.SubElement(index_xml,
                                     'command',
                                     name='user/RESOURCE_UNIQ/login',
                                     value='Log in as user')

        etree.SubElement(index_xml,
                         'command',
                         name='notify_users',
                         value='sends message to all users')
        etree.SubElement(index_xml,
                         'command',
                         name='message_variables',
                         value='returns available message variables')
        return etree.tostring(index_xml)

    @expose(content_type='text/xml')
    def notify_users(self, *arg, **kw):
        """
          Sends message to all system users
        """
        log.info("notify_users")
        if request.method.upper() == 'POST' and request.body is not None:
            try:
                resource = etree.fromstring(request.body)
                message = resource.find('tag[@name="message"]').get('value')
                userlist = resource.find('tag[@name="users"]').get('value')
                self.do_notify_users(userlist, message)
                return '<resource type="message" value="sent" />'
            except Exception:
                log.exception("processing message")
                return abort(400, 'Malformed request document')

        abort(400, 'The request must contain message body')

    @expose(content_type='text/xml')
    def message_variables(self, **kw):
        """
          Sends message to all system users
        """
        log.info("message_variables")
        variables = self.get_variables()
        resp = etree.Element('resource', name='message_variables')
        for n, v in variables.iteritems():
            etree.SubElement(resp, 'tag', name=n, value=v)
        return etree.tostring(resp)

    def add_admin_info2node(self, user_node, view=None):
        """
            adds email and password tags and remove the email value
        """
        if view and 'short' not in view:
            tg_user = User.by_user_name(user_node.get('name'))
            email = user_node.attrib.get('value', '')
            etree.SubElement(user_node, 'tag', name='email', value=email)
            if tg_user is None:
                log.error("No tg_user was found for %s", user_node.get('name'))
            else:
                if 'password' in view:
                    password = tg_user.password
                else:
                    password = '******'
                etree.SubElement(user_node,
                                 'tag',
                                 name='password',
                                 value=password)
                etree.SubElement(user_node,
                                 'tag',
                                 name="groups",
                                 value=",".join(g.group_name
                                                for g in tg_user.groups
                                                if tg_user))
                etree.SubElement(user_node,
                                 'tag',
                                 name='user_name',
                                 value=tg_user.user_name)

        #try to remove value from user node
        user_node.attrib.pop('value', None)

        return user_node

    #@expose(content_type='text/json')
    @expose()
    def loggers(self, *arg, **kw):
        """
        Set logging level dynamically
        post /admin/loggers
        """
        view = kw.pop('view', 'short')
        fmt = kw.pop('format', 'xml')
        #filter = kw.pop ('filter', 'bq.')
        if fmt == 'json':
            response.headers['Content-Type'] = 'text/json'
        elif fmt == 'xml':
            response.headers['Content-Type'] = 'text/xml'

        if request.method == 'GET':
            loggers = [
                {
                    'name': ln,
                    'level': logging.getLevelName(lv.level)
                } for ln, lv in logging.Logger.manager.loggerDict.items()
                if hasattr(lv, 'level')  #and lv.level != logging.NOTSET
            ]

            # filter and sort loggers
            loggers.sort(key=lambda x: x['name'])

            if fmt == 'json':
                return json.dumps(loggers)
            elif fmt == 'xml':
                xml = etree.Element('resource',
                                    name='loggers',
                                    uri='/admin/loggers')
                for l in loggers:
                    etree.SubElement(xml,
                                     'logger',
                                     name=l.get('name'),
                                     value=l.get('level'))
                return etree.tostring(xml)

        elif request.method in ('POST', 'PUT'):

            if request.headers['Content-Type'] == 'text/json':
                loggers = json.loads(request.body)
            else:
                xml = etree.fromstring(request.body)
                loggers = [{
                    'name': l.get('name'),
                    'level': l.get('value')
                } for l in xml.xpath('logger')]

            for l in loggers:
                ln = l.get('name')
                lv = l.get('level')
                log.debug("Changing log level of %s to %s", ln, lv)
                lg = logging.getLogger(ln)
                lg.setLevel(lv)
            return ""

    @expose()
    def logs(self, *arg, **kw):
        """
        get /admin/logs/config or /admin/logs - log config, this will return a local or a remote url
        get /admin/logs/read - read local log lines, by default 1000 last lines
        get /admin/logs/read/172444095 - read local log lines starting from a given time stamp
        """

        # TODO dima: add timestamp based read

        #log.info ("STARTING table (%s): %s", datetime.now().isoformat(), request.url)
        path = request.path_qs.split('/')
        path = [unquote(p) for p in path if len(p) > 0]
        operation = path[2] if len(path) > 2 else ''

        log_url = config.get('bisque.logger')

        if operation == 'config' or operation == '':
            # dima: here we have to identify what kind of logs we are using
            if log_url is not None:
                log_url = urlutil.urljoin(request.url, log_url)
                xml = etree.Element('log',
                                    name='log',
                                    uri=log_url,
                                    type='remote')
            else:
                xml = etree.Element('log',
                                    name='log',
                                    uri='/admin/logs/read',
                                    type='local')
            response.headers['Content-Type'] = 'text/xml'
            return etree.tostring(xml)
        elif operation == 'read':
            # dima, this will only work for local logger
            if log_url is not None:
                redirect(log_url)
            try:
                fn = logging.getLoggerClass().root.handlers[0].stream.filename
                logs = tail(fn, 1000)
                response.headers['Content-Type'] = 'text/plain'
                return ''.join(logs)
            except Exception:
                abort(500, 'Error while reading the log')
        abort(400, 'not a supported operation')

    @expose(content_type='text/xml')
    def cache(self, *arg, **kw):
        """
            Deletes system cache

            DELETE cache
        """
        if request.method == 'DELETE':
            return self.clearcache()
        return '<resource/>'

    @expose(content_type='text/xml')
    def user(self, *arg, **kw):
        """
            Main user expose

            Merges the shadow user with the normal user for admins easy access to the password
            columns

            GET user: returns list of all users in xml info see get_all_users for format

            GET user/uniq: returns user in xml info see get_user for format

            GET user/uniq/login: logins in the admin as the user resource provided

            POST user: creates new user, see post_user for format

            PUT user/uniq: update info on user see put_user for format

            DELETE user/uniq: deletes user, see delete user for format

            DELETE user/uniq/image
                Deletes only the users image data and not the user itself
        """
        http_method = request.method.upper()

        if len(arg) == 1:
            if http_method == 'GET':
                return self.get_user(arg[0], **kw)
            elif http_method == 'PUT':
                if request.body:
                    return self.put_user(arg[0], request.body, **kw)
            elif request.method == 'DELETE':
                return self.delete_user(arg[0])
            else:
                abort(400)
        elif len(arg) == 2:
            if arg[1] == 'login':
                if http_method == 'GET':
                    return self.loginasuser(arg[0])
            elif arg[1] == 'image':
                if http_method == 'DELETE':
                    uniq = arg[0]
                    bquser = data_service.resource_load(uniq=uniq)
                    #bquser = DBSession.query(BQUser).filter(BQUser.resource_uniq == uniq).first()
                    if bquser:
                        self.deleteimages(bquser.get('name'),
                                          will_redirect=False)
                        return '<resource name="delete_images" value="Successful">'
                    else:
                        abort(404)
        else:
            if http_method == 'GET':
                return self.get_all_users(*arg, **kw)
            elif http_method == 'POST':
                if request.body:
                    return self.post_user(request.body, **kw)
        abort(400)

    def get_all_users(self, *arg, **kw):
        """
            Returns a list of all users in xml with password and diplay name.
            (Note: may be removed in version 0.6 due to redundant functionality
            of data_service)

            Limited command support, does not have view=deep,clean..

            document format:
                <resource>
                    <user name="user" owner="/data_service/00-aYnhJQA5BJVm4GDpuexc2G" permission="published"
                    resource_uniq="00-aYnhJQA5BJVm4GDpuexc2G" ts="2015-01-30T02:23:18.414000" uri="admin/user/00-aYnhJQA5BJVm4GDpuexc2G">
                        <tag name="email" value="*****@*****.**"/>
                        <tag name="display_name" value="user"/>
                    </user>
                    <user>...
                </resource>
        """

        kw['wpublic'] = 1
        users = data_service.query(resource_type='user', **kw)
        view = kw.pop('view', None)
        resource = etree.Element('resource', uri=str(request.url))
        for u in users:
            user = self.add_admin_info2node(u, view)
            resource.append(user)
        return etree.tostring(resource)

    def get_user(self, uniq, **kw):
        """
            Returns requested user in xml with password and diplay name.
            (Note: may be removed in version 0.6 due to redundant functionality
            of data_service)

            document format:
                <user name="user" owner="/data_service/00-aYnhJQA5BJVm4GDpuexc2G" permission="published"
                resource_uniq="00-aYnhJQA5BJVm4GDpuexc2G" ts="2015-01-30T02:23:18.414000" uri="/data_service/00-aYnhJQA5BJVm4GDpuexc2G">
                    <tag name="email" value="*****@*****.**"/>
                    <tag name="display_name" value="user"/>
                    <tag name="password" value="******"/> //everything will be served in plan text no password will be returned
                    ...
                </user>
        """
        view = kw.pop('view', 'short')
        user = data_service.resource_load(uniq, view=view)
        if user is not None and user.tag == 'user':
            user = self.add_admin_info2node(user, view)
            return etree.tostring(user)
        else:
            abort(403)

    def _update_groups(self, tg_user, groups):
        """
        @param tg_user : a tg User
        @param a list of group names
        """
        tg_user.groups = []
        for grp_name in groups:
            if not grp_name:
                continue
            grp = DBSession.query(Group).filter_by(group_name=grp_name).first()
            if grp is None:
                log.error("Unknown group %s used ", grp_name)
                continue
            tg_user.groups.append(grp)
        log.debug("updated groups %s", tg_user.groups)

    def post_user(self, doc, **kw):
        """
            Creates new user with tags, the owner of the tags is assigned to the user

            document format:
                <user name="user">
                    <tag name="password" value="12345"/>
                    <tag name="email" value="*****@*****.**"/>
                    <tag name="display_name" value="user"/>
                </user>
        """
        userxml = etree.fromstring(doc)
        required_tags = ['user_name', 'password', 'email', 'display_name']
        tags = {}
        if userxml.tag == 'user':
            user_name = userxml.attrib['name']
            if user_name:
                tags['user_name'] = user_name
                for t in userxml.xpath('tag'):
                    tags[t.get('name')] = t.get('value')
                    #if (t.attrib['name']=='password') or (t.attrib['name']=='email'):
                    if t.get('name') in REMOVE_TAGS:
                        t.getparent().remove(t)  #removes email and password
                        if t.attrib['name'] == 'email':
                            userxml.attrib['value'] = t.attrib[
                                'value']  #set it as value of the user
                if all(k in tags for k in required_tags):
                    log.debug("ADMIN: Adding user: %s", str(user_name))
                    u = User(user_name=tags['user_name'],
                             password=tags['password'],
                             email_address=tags['email'],
                             display_name=tags['display_name'])
                    DBSession.add(u)
                    self._update_groups(u, tags.get('groups', '').split(','))
                    try:
                        transaction.commit()
                    except IntegrityError:
                        abort(
                            405,
                            'Another user already has this user name or email address'
                        )
                    #r = BQUser.query.filter(BQUser.resource_name == tags['user_name']).first()
                    r = data_service.query(resource_type='user',
                                           name=tags['user_name'],
                                           wpublic=1)
                    if len(r) > 0:
                        admin = get_username()  #get admin user
                        set_current_user(
                            tags['user_name']
                        )  #change document as user so that all changes are owned by the new user
                        r = data_service.update_resource(
                            '/data_service/%s' %
                            r[0].attrib.get('resource_uniq'),
                            new_resource=userxml)
                        set_current_user(admin)  #set back to admin user
                        return self.get_user(
                            '%s' % r.attrib.get('resource_uniq'), **kw)
                    else:
                        abort(400)
        abort(400)

    def put_user(self, uniq, doc, **kw):
        """
            update user

            @param: uniq - resource uniq for the user
            @param: doc - document in the format shown below

            document format:
                <user name="user" resource_uniq="00-1235218954">
                    <tag name="password" value="12345"/> or <tag name="password" value="******"/>
                    <tag name="email" value="*****@*****.**"/>
                    <tag name="display_name" value="user"/>
                </user>
        """
        userxml = etree.fromstring(doc)
        required_tags = ['user_name', 'password', 'email', 'display_name']
        tags = {}
        if userxml.tag == 'user':
            user_name = userxml.attrib.get('name')
            if user_name:
                #tags['user_name'] = user_name
                for t in userxml.xpath('tag'):
                    tags[t.get('name')] = t.get('value')
                    #if t.attrib['name'] == 'password' or t.attrib['name']=='email':
                    if t.get('name') in REMOVE_TAGS:
                        t.getparent().remove(t)  #removes email and password
                        if t.attrib['name'] == 'email':
                            userxml.attrib['value'] = t.attrib.get(
                                'value')  #set it as value of the user

                if all(k in tags for k in required_tags
                       ):  #checks to see if all required tags are present
                    #update tg_user
                    #tg_user = DBSession.query(User).filter(User.user_name == tags.get('user_name')).first()
                    #tg_user = User.by_user_name(tags.get('user_name'))
                    tg_user = User.by_user_name(user_name)
                    if not tg_user:
                        log.debug(
                            'No user was found with name of %s. Please check core tables?',
                            user_name)
                        abort(404)
                    #reset values on tg user
                    tg_user.email_address = tags.get("email",
                                                     tg_user.email_address)

                    if tags['password'] and tags['password'].count('*') != len(
                            tags['password']
                    ):  #no password and ***.. not allowed passwords
                        tg_user.password = tags.get(
                            "password", tg_user.password
                        )  #just set it as itself if nothing is provided
                    #else:
                    #    tags.pop("password", None) #remove the invalid password

                    tg_user.display_name = tags.get("display_name",
                                                    tg_user.display_name)
                    self._update_groups(tg_user,
                                        tags.get('groups', '').split(','))
                    if tags.get('user_name') != user_name:
                        tg_user.user_name = tags.get('user_name')
                        userxml.set('name', tags['user_name'])
                    #del tags['user_name']

                    log.debug("ADMIN: Updated user: %s", str(user_name))
                    transaction.commit()
                    ### ALL loaded variables are detached

                    #userxml.attrib['resource_uniq'] = r.attrib['resource_uniq']
                    #reset BQUser
                    admin = get_username()  #get admin user
                    set_current_user(
                        tags['user_name']
                    )  #change document as user so that all changes are owned by the new user
                    r = data_service.update_resource(resource=userxml,
                                                     new_resource=userxml,
                                                     replace=True)
                    log.debug("Sent XML %s", etree.tostring(userxml))
                    set_current_user(admin)  #set back to admin user
                    #DBSession.flush()
                    return self.get_user(r.attrib['resource_uniq'], **kw)
        abort(400)

    def delete_user(self, uniq):
        """
            Deletes user

            @param uniq - resource uniq for the user

        """
        # Remove the user from the system for most purposes, but
        # leave the id for statistics purposes.
        bquser = DBSession.query(BQUser).filter(
            BQUser.resource_uniq == uniq).first()
        if bquser:
            log.debug("ADMIN: Deleting user: %s", str(bquser))
            user = DBSession.query(User).filter(
                User.user_name == bquser.resource_name).first()
            log.debug("Renaming internal user %s", str(user))

            if user:
                DBSession.delete(user)
                # delete the access permission
                for p in DBSession.query(TaggableAcl).filter_by(
                        user_id=bquser.id):
                    log.debug("KILL ACL %s", str(p))
                    DBSession.delete(p)
                self.deleteimages(bquser.resource_name, will_redirect=False)
                #DBSession.delete(bquser)

                #transaction.commit()
            data_service.del_resource(bquser)
            return '<resource>Delete User</resource>'

        abort(400)

    def deleteimage(self, imageid=None, **kw):
        log.debug("image: %s ", str(imageid))
        image = DBSession.query(Image).filter(Image.id == imageid).first()
        DBSession.delete(image)
        transaction.commit()
        redirect(request.headers.get("Referer", "/"))

    def deleteuser(self, username=None, **kw):
        #DBSession.autoflush = False

        # Remove the user from the system for most purposes, but
        # leave the id for statistics purposes.
        user = DBSession.query(User).filter(User.user_name == username).first()
        log.debug("Renaming internal user %s", str(user))
        if user:
            DBSession.delete(user)
            #user.display_name = ("(R)" + user.display_name)[:255]
            #user.user_name = ("(R)" + user.user_name)[:255]
            #user.email_address = ("(R)" + user.email_address)[:16]

        user = DBSession.query(BQUser).filter(
            BQUser.resource_name == username).first()
        log.debug("ADMIN: Deleting user: %s", str(user))
        # delete the access permission
        for p in DBSession.query(TaggableAcl).filter_by(user_id=user.id):
            log.debug("KILL ACL %s", str(p))
            DBSession.delete(p)
        #DBSession.flush()

        self.deleteimages(username, will_redirect=False)
        DBSession.delete(user)
        transaction.commit()
        redirect('/admin/users')

    def deleteimages(self, username=None, will_redirect=True, **kw):
        user = DBSession.query(BQUser).filter(
            BQUser.resource_name == username).first()
        log.debug("ADMIN: Deleting all images of: %s", str(user))
        images = DBSession.query(Image).filter(Image.owner_id == user.id).all()
        for i in images:
            log.debug("ADMIN: Deleting image: %s", str(i))
            DBSession.delete(i)
        if will_redirect:
            transaction.commit()
            redirect('/admin/users')
        return dict()

    def loginasuser(self, uniq):
        log.debug('forcing login as user')
        user = DBSession.query(BQUser).filter(
            BQUser.resource_uniq == uniq).first()
        if user:
            response.headers = request.environ['repoze.who.plugins'][
                'friendlyform'].remember(request.environ,
                                         {'repoze.who.userid': user.name})
            redirect("/client_service")
        else:
            abort(404)

    def clearcache(self):
        log.info("CLEARING CACHE")

        def clearfiles(folder):
            for the_file in os.listdir(folder):
                file_path = os.path.join(folder, the_file)
                try:
                    if os.path.isfile(file_path):
                        os.unlink(file_path)
                except OSError as e:
                    log.debug("unlinking failed: %s", file_path)
                except Exception as e:
                    log.exception('while removing %s' % file_path)

        server_cache = data_path('server_cache')
        clearfiles(server_cache)
        log.info("CLEARED CACHE")
        return '<resource name="cache_clear" value="finished">'

    def get_variables(self):
        #bisque_root = config.get ('bisque.root')
        bisque_root = request.application_url
        bisque_organization = config.get('bisque.organization', 'BisQue')
        bisque_email = config.get('bisque.admin_email', 'info@bisque')

        variables = {
            'service_name':
            bisque_organization,
            'service_url':
            '<a href="%s">%s</a>' % (bisque_root, bisque_organization),
            'user_name':
            'username',
            'email':
            'user@email',
            'display_name':
            'First Last',
            'bisque_email':
            bisque_email,
        }
        return variables

    def do_notify_users(self, userlist, message):
        log.debug(message)
        variables = self.get_variables()

        #for users
        users = data_service.query(resource_type='user',
                                   wpublic='true',
                                   view='full')
        for u in users:
            variables['user_name'] = u.get('name')
            variables['email'] = u.get('value')
            variables['display_name'] = u.find(
                'tag[@name="display_name"]').get('value')
            if variables['email'] not in userlist:
                continue

            msg = copy.deepcopy(message)
            msg = string.Template(msg).safe_substitute(variables)
            #for v,t in variables.iteritems():
            #    msg = msg.replace('$%s'%v, t)

            # send
            log.info('Sending message to: %s', variables['email'])
            log.info('Message:\n%s', msg)

            try:
                notify_service.send_mail(
                    variables['bisque_email'],
                    variables['email'],
                    'Notification from %s service' % variables['service_name'],
                    msg,
                )
            except Exception:
                log.exception("Mail not sent")

    @expose(content_type='text/xml')
    def group(self, *args, **kw):
        """
            GET /admin/group: returns list of all groups <resource> <group name="a" /> <group ... /> </resource>

            POST /admin/group: creates new group,
                  <group name="new_group" /> or <resource> <group ..> <group ../> </resource>
                  shortcut:  POST /group/new_group with no body
            PUT /admin/group  : same as POST

            DELETE /admin/group/group_name : delete the group

        """

        log.debug("GROUP %s %s", args, kw)
        reqformat = kw.pop('format', None)
        http_method = request.method.upper()
        if http_method == 'GET':
            resource = self.get_groups(*args, **kw)
        elif http_method == 'DELETE':
            resource = self.delete_group(*args, **kw)
        elif http_method in ('PUT', 'POST'):
            resource = self.new_group(*args, **kw)
        else:
            abort(400, "bad request")
        accept_header = request.headers.get('accept')
        formatter, content_type = find_formatter(reqformat, accept_header)
        response.headers['Content-Type'] = content_type
        return formatter(resource)

    def get_groups(self, *args, **kw):
        resource = etree.Element('resource')
        for group in DBSession.query(Group):
            etree.SubElement(resource, 'group', name=group.group_name)
        return resource

    def delete_group(self, *args, **kw):
        if len(args):
            group_name = args[0]
        else:
            content_type = request.headers.get('Content-Type')
            inputer = find_inputer(content_type)
            body = request.body_file.read()
            log.debug("DELETE content %s", body)
            els = inputer(body)
            group_name = els.xpath('//group/@name')[0]

        resource = etree.Element('resource')
        group = DBSession.query(Group).filter_by(group_name=group_name).first()
        if group:
            etree.SubElement(resource, 'group', name=group.group_name)
            DBSession.delete(group)

        return resource

    def new_group(self, *args, **kw):
        if len(args):
            group_names = args
        else:
            content_type = request.headers.get('Content-Type')
            inputer = find_inputer(content_type)
            els = inputer(request.body_file)
            group_names = els.xpath('//group/@name')
        resource = etree.Element('resource')
        for nm in group_names:
            g = Group(group_name=nm)
            DBSession.add(g)
            etree.SubElement(resource, 'group', name=nm)

        try:
            transaction.commit()
        except (IntegrityError, InvalidRequestError) as e:
            transaction.abort()
            abort(400, "Bad request %s" % e)

        return resource
Beispiel #24
0
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")
 def test_user_doesnt_belong_to_group(self):
     environ = make_environ('gustavo', ['developers', 'admins'])
     p = predicates.in_group('designers')
     self.eval_unmet_predicate(
         p, environ,
         'The current user must belong to the group "designers"')
Beispiel #26
0
        return 'hello sub1'
    
    def in_group(self):
        return 'in group'


class SecurePanel(WSGIController):
    """Mock Pylons secure controller"""
    
    def index(self):
        return 'you are in the panel'
    
    @ActionProtector(in_group('developers'))
    def commit(self):
        return 'you can commit'
SecurePanel = ControllerProtector(in_group('admins'))(SecurePanel)


class SecurePanelWithHandler(WSGIController):
    """Mock Pylons secure controller"""
    
    def index(self):
        return 'you are in the panel with handler'
    
    @staticmethod
    def sorry(reason):
        response.status = 200
        return 'what are you doing here? %s' % reason
SecurePanelWithHandler = ControllerProtector(
    in_group('admins'), 'sorry')(SecurePanelWithHandler)
class ProyectoController(BaseController):
    allow_only = not_anonymous(
        msg='Solo usuarios registrados pueden acceder a los proyectos')

    @expose()
    def index(self, **named):
        """Handle the front-page."""
        redirect('/proyecto/lista')

    @expose(template='gestionitem.templates.proyectoTmpl.lista')
    def lista(self, **named):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        expresion = named.get('expresion')
        orden = named.get('submit')
        proyectos = []

        id = identity['user']
        for grupo in id.groups:
            if (grupo.group_name == 'Administrador'):
                if (orden == None or orden == 'Listar Todos'):
                    proyectos = DBSession.query(Proyecto).filter(
                        Proyecto.estado != 4).all()
                    muestraBoton = "false"
                elif (orden == 'Buscar' and expresion != None):
                    proyectoxlider = DBSession.query(Proyecto).join(
                        (User, Proyecto.lider)).filter(
                            User.user_name.like('%' + expresion + '%')).filter(
                                Proyecto.estado != 4).all()
                    proyectoxdescripcion = DBSession.query(Proyecto).filter(
                        Proyecto.descripcion.like(
                            '%' + expresion +
                            '%')).filter(Proyecto.estado != 4).all()
                    proyectoxestado = DBSession.query(Proyecto).join(
                        (EstadoProyecto, Proyecto.estadoObj)).filter(
                            EstadoProyecto.descripcion.like(
                                '%' + expresion +
                                '%')).filter(Proyecto.estado != 4).all()
                    proyectos = proyectoxdescripcion + proyectoxlider + proyectoxestado
                    muestraBoton = "true"

            if (grupo.group_name == 'LiderProyecto'):
                if (orden == None or orden == 'Listar Todos'):
                    proyectosLider = DBSession.query(Proyecto).filter(
                        Proyecto.id_lider == id.user_id).filter(
                            Proyecto.estado != 4).all()
                    muestraBoton = "false"
                elif (orden == 'Buscar' and expresion != None):
                    proyectoxlider = DBSession.query(Proyecto).join(
                        (User, Proyecto.lider)).filter(
                            User.user_name.like('%' + expresion + '%')).filter(
                                Proyecto.id_lider == id.user_id).filter(
                                    Proyecto.estado != 4).all()
                    proyectoxdescripcion = DBSession.query(Proyecto).filter(
                        Proyecto.descripcion.like('%' + expresion + '%')
                    ).filter(Proyecto.id_lider == id.user_id).filter(
                        Proyecto.estado != 4).all()
                    proyectoxestado = DBSession.query(Proyecto).join(
                        (EstadoProyecto, Proyecto.estadoObj)).filter(
                            EstadoProyecto.descripcion.like(
                                '%' + expresion + '%')).filter(
                                    Proyecto.id_lider == id.user_id).filter(
                                        Proyecto.estado != 4).all()
                    proyectosLider = proyectoxdescripcion + proyectoxlider + proyectoxestado
                    muestraBoton = "true"
                elif (orden):
                    proyectosLider = DBSession.query(Proyecto).filter(
                        Proyecto.id_lider == id.user_id).filter(
                            Proyecto.estado != 4).all()
                    muestraBoton = "false"

                for proyect in proyectosLider:
                    if (proyect in proyectos):
                        proyect.setDefinir()
                        proyect.setmostrarFases()
                        indice = proyectos.index(proyect)
                        proyectos[indice] = proyect

                    else:
                        proyect.setDefinir()
                        proyect.setmostrarFases()
                        proyectos.append(proyect)

            if (grupo.group_name == 'Desarrollador'
                    or grupo.group_name == 'Aprobador'):
                proyectosDesarrollador = []
                ufrs = DBSession.query(UsuarioFaseRol).filter(
                    UsuarioFaseRol.user_id == id.user_id).all()

                if (orden == None or orden == 'Listar Todos'):
                    for ufr in ufrs:
                        try:
                            fase = DBSession.query(Fase).join(
                                (Proyecto, Fase.proyectoObj)).filter(
                                    Fase.id == ufr.fase_id).filter(
                                        Proyecto.estado != 4).one()
                            proyectosDesarrollador.append(fase.proyectoObj)
                        except:
                            pass
                    proyectosDesarrolladorset = set(proyectosDesarrollador)
                    proyectosDesarrollador = list(proyectosDesarrolladorset)
                    muestraBoton = "false"

                elif (orden == 'Buscar' and expresion != None):
                    proyectoxlider = DBSession.query(Proyecto).join(
                        (User, Proyecto.lider)).filter(
                            User.user_name.like('%' + expresion + '%')).filter(
                                Proyecto.estado != 4).all()
                    proyectoxdescripcion = DBSession.query(Proyecto).filter(
                        Proyecto.descripcion.like(
                            '%' + expresion +
                            '%')).filter(Proyecto.estado != 4).all()
                    proyectoxestado = DBSession.query(Proyecto).join(
                        (EstadoProyecto, Proyecto.estadoObj)).filter(
                            EstadoProyecto.descripcion.like(
                                '%' + expresion +
                                '%')).filter(Proyecto.estado != 4).all()
                    proyectosaux = proyectoxlider + proyectoxdescripcion + proyectoxestado
                    proyectosauxset = set(proyectosaux)
                    proyectosaux = list(proyectosauxset)

                    for ufr in ufrs:
                        if ufr.fase.proyectoObj in proyectosaux:
                            proyectosDesarrollador.append(ufr.fase.proyectoObj)
                    proyectosDesarrolladorset = set(proyectosDesarrollador)
                    proyectosDesarrollador = list(proyectosDesarrolladorset)
                    muestraBoton = "true"

                if proyectos.__len__() > 0:
                    for proyecto1 in proyectosDesarrollador:
                        if proyecto1 in proyectos:
                            proyecto1.setmostrarFases()
                        else:
                            proyecto1.setmostrarFases()
                            proyectos.append(proyecto1)

                else:
                    proyectos = proyectosDesarrollador
                    for proyecto12 in proyectos:
                        proyecto12.setmostrarFases()

        proset = set(proyectos)
        proyectos = list(proset)

        from webhelpers import paginate

        count = proyectos.__len__()
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            proyectos,
            page,
            item_count=count,
            items_per_page=5,
        )
        proyectos = currentPage.items
        return dict(page='Lista de proyectos',
                    proyectos=proyectos,
                    subtitulo='Proyectos',
                    user=user,
                    muestraBoton=muestraBoton,
                    currentPage=currentPage)

    @expose('gestionitem.templates.proyectoTmpl.nuevo')
    @require(
        All(in_group('Administrador'),
            has_permission('crear proyecto'),
            msg='Debe poseer Rol "Administrador" para crear nuevos proyectos'))
    def nuevo(self):
        """Handle the front-page."""
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        lideres = DBSession.query(User).join(
            (Rol,
             User.groups)).filter(Rol.group_name == 'LiderProyecto').all()
        nombreProyectos = []
        proyectos = DBSession.query(Proyecto).all()
        for proyecto in proyectos:
            nombreProyectos.append(proyecto.descripcion)
            nombreProyectos.append(",")
        return dict(page='Nuevo Proyecto',
                    lideres=lideres,
                    nombreProyectos=nombreProyectos,
                    user=user)

    @expose()
    @require(
        All(in_group('Administrador'),
            has_permission('crear proyecto'),
            msg='Debe poseer Rol "Administrador" para crear nuevos proyectos'))
    def add_proyecto(self, descripcion, lider, **named):
        """Registra un proyecto nuevo """
        new = Proyecto(
            descripcion=descripcion,
            id_lider=lider,
            estado=1,
        )
        DBSession.add(new)
        flash('''Proyecto Registrado: %s''' % (descripcion, ))
        redirect('./index')

    @expose(template="gestionitem.templates.proyectoTmpl.editar")
    @require(
        All(in_group('Administrador'),
            has_permission('editar proyecto'),
            msg='Debe poseer Rol "Administrador" editar proyectos'))
    def editar(self, id):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']

        proyecto = DBSession.query(Proyecto).filter_by(id=id).one()

        if proyecto.lider != None:
            usuarios = DBSession.query(User).join((Rol, User.groups)).filter(
                Rol.group_name == 'LiderProyecto').filter(
                    User.user_id != proyecto.lider.user_id).all()
        else:
            usuarios = DBSession.query(User).join(
                (Rol, User.groups)).filter(Rol.group_name == 'LiderProyecto')

        return dict(page='Editar Proyecto',
                    id=id,
                    proyecto=proyecto,
                    subtitulo='ABM-Proyecto',
                    user=user,
                    usuarios=usuarios)

    @expose()
    @require(
        All(in_group('Administrador'),
            has_permission('editar proyecto'),
            msg='Debe poseer Rol "Administrador" editar proyectos'))
    def actualizar(self, id, descripcion, id_user, submit):
        """Create a new movie record"""
        proyecto = DBSession.query(Proyecto).filter_by(id=id).one()
        proyecto.descripcion = descripcion
        proyecto.id_lider = id_user

        DBSession.flush()

        redirect('/proyecto')

    @expose()
    @require(
        in_group('Administrador',
                 msg='Debe poseer Rol "Administrador" eliminar proyectos'))
    @require(
        All(in_group('Administrador'),
            has_permission('eliminar proyecto'),
            msg='Debe poseer Rol "Administrador" eliminar proyectos'))
    def eliminar(self, id):
        proyecto = DBSession.query(Proyecto).filter_by(id=id).one()
        proyecto.estado = 4

        redirect('/proyecto')

    @expose(template='gestionitem.templates.proyectoTmpl.avisoEliminarProyecto'
            )
    def avisoEliminarProyecto(self, id, **named):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        proyecto = DBSession.query(Proyecto).filter_by(id=id).one()

        return dict(page='Aviso Editar Item',
                    user=user,
                    fases=proyecto.fases,
                    proyecto=proyecto,
                    subtitulo='Aviso')

    @expose()
    def cambiarEstado(self, id, estado, **named):
        proyecto = DBSession.query(Proyecto).filter_by(id=id).one()
        proyecto.estado = estado
        DBSession.flush()
        redirect('/proyecto')

    @expose(template="gestionitem.templates.proyectoTmpl.proyectoDef")
    @require(
        All(in_group('LiderProyecto'),
            has_permission('definir proyecto'),
            msg='Debe poseer Rol "LiderProyecto" para definir proyectos'))
    def proyectoDef(self, id, **named):
        fases = DBSession.query(Fase).filter(Fase.proyecto_id == id)

        proyecto_id = id

        return dict(page='Definir Proyecto',
                    proyecto_id=proyecto_id,
                    subtitulo='Definir Proyecto')

    @expose(template="gestionitem.templates.proyectoTmpl.faseList")
    @require(
        All(in_group('LiderProyecto'),
            has_permission('definir proyecto'),
            msg='Debe poseer Rol "LiderProyecto" para definir fases'))
    def definir_fase(self, id, **named):
        identity = request.environ.get('repoze.who.identity')
        fases = []

        expresion = named.get('expresion')
        orden = named.get('submit')

        iduser = identity['user']

        proyecto = DBSession.query(Proyecto).filter(Proyecto.id == id).one()
        proyectoEstado = proyecto.estado
        for grupo in iduser.groups:
            if (grupo.group_name == 'LiderProyecto'):
                if (orden == None or orden == 'Listar Todos'
                        or orden == 'Cancelar'):
                    fases = DBSession.query(Fase).filter(
                        Fase.proyecto_id == id).order_by(
                            Fase.numero_fase).all()
                    muestraBoton = "false"
                elif (orden == 'Buscar' and expresion != None):
                    fasesxdescripcion = DBSession.query(Fase).filter(
                        Fase.proyecto_id == id).filter(
                            Fase.descripcion.like('%' + expresion +
                                                  '%')).all()
                    fasesxestado = DBSession.query(Fase).join(
                        (EstadoFase, Fase.estadoObj)).filter(
                            Fase.proyecto_id == id).filter(
                                EstadoFase.descripcion.like('%' + expresion +
                                                            '%')).all()
                    fases = fasesxdescripcion + fasesxestado
                    muestraBoton = "true"

            elif (grupo.group_name == 'Desarrollador'
                  or grupo.group_name == 'Aprobador'):
                ufrs = DBSession.query(UsuarioFaseRol).filter(
                    UsuarioFaseRol.user_id == iduser.user_id).all()
                for ufr in ufrs:
                    if (str(ufr.fase.proyecto_id) == id):
                        fasetot = []
                        if (orden == None or orden == 'Listar Todos'
                                or orden == 'Cancelar'):
                            fase1 = DBSession.query(Fase).filter(
                                Fase.id == ufr.fase_id).one()
                            muestraBoton = "false"
                        elif (orden == 'Buscar' and expresion != None):
                            fase1xdescripcion = DBSession.query(Fase).filter(
                                Fase.id == ufr.fase_id).filter(
                                    Fase.descripcion.like('%' + expresion +
                                                          '%')).all()
                            fase1xestado = DBSession.query(Fase).join(
                                (EstadoFase, Fase.estadoObj
                                 )).filter(Fase.id == ufr.fase_id).filter(
                                     EstadoFase.descripcion.like('%' +
                                                                 expresion +
                                                                 '%')).all()
                            fasetot = fase1xdescripcion + fase1xestado
                            muestraBoton = "true"
                        for fase1 in fasetot:
                            if (fase1 in fases):
                                pass
                            else:
                                fases.append(fase1)

        faseset = set(fases)
        fases = list(faseset)
        fases = sorted(fases, key=lambda Fase: Fase.numero_fase)
        proyecto_id = id

        from webhelpers import paginate
        count = fases.__len__()
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            fases,
            page,
            item_count=count,
            items_per_page=5,
        )
        fases = currentPage.items
        return dict(page='Lista de fases',
                    fases=fases,
                    proyecto_id=proyecto_id,
                    subtitulo='fases',
                    user=iduser,
                    proyectoEstado=proyectoEstado,
                    muestraBoton=muestraBoton,
                    proyecto=proyecto,
                    currentPage=currentPage)

    @expose(template="gestionitem.templates.proyectoTmpl.agregar_fase")
    @require(
        All(in_group('LiderProyecto'),
            has_permission('crear fase'),
            msg='Debe poseer Rol "LiderProyecto" para agregar fases'))
    def agregar_fase(self, id):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        proyecto = DBSession.query(Proyecto).filter(Proyecto.id == id).one()
        fase = DBSession.query(Fase).filter(
            Fase.proyecto_id == proyecto.id).all()
        codigos = []
        for i, cod in enumerate(fase):
            codigos.append(cod.codigo_fase)
            codigos.append(",")
        return dict(page='Nueva Fase',
                    proyecto=proyecto,
                    user=user,
                    codigos=codigos)

    @expose()
    @require(
        All(in_group('LiderProyecto'),
            has_permission('crear fase'),
            msg='Debe poseer Rol "LiderProyecto" para agregar fases'))
    def save_fase(self, id, descripcion_proyecto, nombre_fase, codFase,
                  submit):
        fases = DBSession.query(Fase).filter(Fase.proyecto_id == id)
        num = fases.count() + 1

        new = Fase(descripcion=nombre_fase,
                   proyecto_id=id,
                   numero_fase=num,
                   estado_id=3,
                   codigo_fase=codFase)
        DBSession.add(new)
        flash('''Fase Registrada: %s''' % (nombre_fase, ))
        redirect('/proyecto/definir_fase/' + id)

    @expose("gestionitem.templates.proyectoTmpl.editar_fase")
    @require(
        All(in_group('LiderProyecto'),
            has_permission('editar fase'),
            msg='Debe poseer Rol "LiderProyecto" para editar fases'))
    def editar_fase(self, id):

        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        fase = DBSession.query(Fase).filter(Fase.id == id).one()
        fases = DBSession.query(Fase).filter(
            Fase.proyecto_id == fase.proyecto_id).all()
        codigos = []
        for i, cod in enumerate(fases):
            codigos.append(cod.codigo_fase)
            codigos.append(",")

        return dict(page='Editar fase',
                    id=id,
                    fase=fase,
                    user=user,
                    codigos=codigos,
                    subtitulo='ABM-Fase')

    @expose()
    @require(
        All(in_group('LiderProyecto'),
            has_permission('editar fase'),
            msg='Debe poseer Rol "LiderProyecto" para editar fases'))
    def actualizar_fase(self, id, descripcion_proyecto, nombre_fase,
                        numero_fase, submit):
        fase = DBSession.query(Fase).filter(Fase.id == id).one()
        fase.descripcion = nombre_fase
        fase.numero_fase = numero_fase
        #        fase.codigo_fase = codFase
        DBSession.flush()
        redirect('/proyecto/definir_fase/' + str(fase.proyecto_id))

    @expose()
    @require(
        All(in_group('LiderProyecto'),
            has_permission('eliminar fase'),
            msg='Debe poseer Rol "LiderProyecto" para eliminar fases'))
    def eliminar_fase(self, id):
        fase = DBSession.query(Fase).filter(Fase.id == id).one()
        id_proyecto = fase.proyecto_id
        ufrs = DBSession.query(UsuarioFaseRol).filter(
            UsuarioFaseRol.fase_id == id).all()
        for ufr in ufrs:
            DBSession.delete(ufr)
        DBSession.flush()
        #        itemusuarios = DBSession.query(TipoItemUsuario).filter(TipoItemUsuario.fase_id == id).all()

        DBSession.delete(fase)
        fases = DBSession.query(Fase).filter(
            Fase.proyecto_id == id_proyecto).order_by(Fase.id).all()
        for i, fase in enumerate(fases):
            fase.numero_fase = i + 1
            DBSession.flush()

        redirect('/proyecto/definir_fase/' + str(id_proyecto))

    @expose("gestionitem.templates.proyectoTmpl.usuario_faseList")
    @require(
        in_group('LiderProyecto',
                 msg='Debe poseer Rol "LiderProyecto" para listar usuarios'))
    def usuario_faseList(self, id, **named):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        expresion = named.get('expresion')
        orden = named.get('submit')

        usuarioFaseRols = DBSession.query(UsuarioFaseRol).filter(
            UsuarioFaseRol.fase_id == id).all()

        for ufr in usuarioFaseRols:
            if ufr.usuario == None:
                DBSession.delete(ufr)
                DBSession.flush()
        if (orden == None or orden == 'Listar Todos' or orden == 'Cancelar'):
            usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
                UsuarioFaseRol.fase_id == id).all()
            muestraBoton = "false"
        elif (orden == 'Buscar' and expresion != None):
            usuarioxnombre = DBSession.query(UsuarioFaseRol).join(
                (User, UsuarioFaseRol.usuario)).filter(
                    UsuarioFaseRol.fase_id == id).filter(
                        User.user_name.like('%' + expresion + '%')).order_by(
                            User.user_name).all()
            usuarioxrol = DBSession.query(UsuarioFaseRol).join(
                (Rol, UsuarioFaseRol.rol)).filter(
                    UsuarioFaseRol.fase_id == id).filter(
                        Rol.group_name.like('%' + expresion + '%')).all()
            usuarioFaseRol1 = usuarioxnombre + usuarioxrol
            usuarioFaseRol = set(usuarioFaseRol1)
            usuarioFaseRol = list(usuarioFaseRol)
            muestraBoton = "true"
        fase = DBSession.query(Fase).filter(Fase.id == id).one()
        from webhelpers import paginate
        count = usuarioFaseRol.__len__()
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            usuarioFaseRol,
            page,
            item_count=count,
            items_per_page=5,
        )
        usuarioFaseRol = currentPage.items
        descripcion = fase.descripcion
        proyecto = DBSession.query(Proyecto).filter(
            Proyecto.id == fase.proyecto_id).one()

        return dict(page='Usuarios de fase ' + descripcion,
                    usuariofaserol=usuarioFaseRol,
                    descripcion=descripcion,
                    fase_id=id,
                    subtitulo='Usuarios de fase',
                    proyecto_id=fase.proyecto_id,
                    user=user,
                    muestraBoton=muestraBoton,
                    proyecto=proyecto,
                    currentPage=currentPage)

    @expose("gestionitem.templates.proyectoTmpl.agregarUsuarioFase")
    @require(
        All(in_group('LiderProyecto'),
            has_permission('asignar desarrollador'),
            msg='LiderProyecto" para agregar usuarios'))
    def agregar_usuario_fase(self, id, **named):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        usuarios = DBSession.query(User).join((Rol, User.groups)).filter(
            or_(Rol.group_name == 'Aprobador',
                Rol.group_name == 'Desarrollador')).all()
        roles = DBSession.query(Rol).filter(
            or_(Rol.group_name == 'Aprobador',
                Rol.group_name == 'Desarrollador')).all()
        fase = DBSession.query(Fase).filter(Fase.id == id).one()
        #        usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(UsuarioFaseRol.fase_id == id).all()

        return dict(page='Asignar Usuario a fase ' + fase.descripcion,
                    usuarios=usuarios,
                    roles=roles,
                    proyecto_id=id,
                    user=user,
                    fase=fase)

    @expose()
    @require(
        All(in_group('LiderProyecto'),
            has_permission('asignar desarrollador'),
            msg='Debe poseer Rol "LiderProyecto" para agregar usuarios'))
    def save_usuario_fase(self, fase, user, rol, **named):
        try:
            rol = int(rol)
            try:
                usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
                    UsuarioFaseRol.fase_id == fase).filter(
                        UsuarioFaseRol.user_id == user).filter(
                            UsuarioFaseRol.rol_id == rol).one()
                DBSession.delete(usuarioFaseRol)
            except:
                pass
            new = UsuarioFaseRol(user_id=user, fase_id=fase, rol_id=rol)

            DBSession.add(new)

        except:

            for rol1 in rol:
                try:
                    usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
                        UsuarioFaseRol.fase_id == fase).filter(
                            UsuarioFaseRol.user_id == user).filter(
                                UsuarioFaseRol.rol_id == rol1).one()
                    DBSession.delete(usuarioFaseRol)
                except:
                    pass
                new = UsuarioFaseRol(user_id=user, fase_id=fase, rol_id=rol1)

                DBSession.add(new)

        CambiarEstadoFase = DBSession.query(Fase).filter(Fase.id == fase).one()
        CambiarEstadoFase.estado_id = 1
        redirect('/proyecto/usuario_faseList/' + fase)

    @expose()
    @require(
        All(in_group('LiderProyecto'),
            has_permission('eliminar desarrollador'),
            msg='Debe poseer Rol "LiderProyecto" para eliminar usuarios'))
    def eliminar_usuario_fase(self, ufr):
        usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
            UsuarioFaseRol.id == ufr).one()
        fase = usuarioFaseRol.fase_id
        DBSession.delete(usuarioFaseRol)
        usuarioFaseRolcantidad = DBSession.query(UsuarioFaseRol).filter(
            UsuarioFaseRol.fase_id == fase).all()
        if usuarioFaseRolcantidad.__len__() == 0:
            faseCambiarEstado = DBSession.query(Fase).filter(
                Fase.id == fase).one()
            faseCambiarEstado.estado_id = 3
            DBSession.flush()

        redirect('/proyecto/usuario_faseList/' + str(fase))

    @expose("gestionitem.templates.proyectoTmpl.editarUsuarioFase")
    @require(
        All(in_group('LiderProyecto'),
            has_permission('editar desarrollador'),
            msg='Debe poseer Rol "LiderProyecto" para editar usuarios'))
    def editar_usuario_fase(self, ufr, **named):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']
        usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
            UsuarioFaseRol.id == ufr).one()
        fase = DBSession.query(Fase).filter(
            Fase.id == usuarioFaseRol.fase_id).one()
        usuario = DBSession.query(User).filter(
            User.user_id == usuarioFaseRol.user_id).one()
        rol = DBSession.query(Rol).filter(
            Rol.group_id == usuarioFaseRol.rol_id).one()
        roles = DBSession.query(Rol).filter(
            or_(Rol.group_name == 'Aprobador',
                Rol.group_name == 'Desarrollador')).all()
        return dict(page='Editar Usuario de fase' + fase.descripcion,
                    fase=fase,
                    usuario=usuario,
                    roles=roles,
                    rol=rol,
                    user=user,
                    ufr=usuarioFaseRol)

    @expose()
    @require(
        All(in_group('LiderProyecto'),
            has_permission('editar desarrollador'),
            msg='Debe poseer Rol "LiderProyecto" para editar usuarios'))
    def actualizar_usuario_fase(self, fase, ufr, submit, **named):
        rol = named.get('rol')
        usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
            UsuarioFaseRol.id == ufr).one()
        user = usuarioFaseRol.user_id

        if rol == None:
            usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
                UsuarioFaseRol.id == ufr).one()
            DBSession.delete(usuarioFaseRol)

        else:

            try:
                rol = int(rol)
                try:
                    usuarioFaseRol = DBSession.query(UsuarioFaseRol).filter(
                        UsuarioFaseRol.fase_id == fase).filter(
                            UsuarioFaseRol.user_id == user).filter(
                                UsuarioFaseRol.rol_id == rol).one()
                    DBSession.delete(usuarioFaseRol)
                except:
                    pass
                new = UsuarioFaseRol(user_id=user, fase_id=fase, rol_id=rol)

                DBSession.add(new)

            except:

                for rol1 in rol:
                    try:
                        usuarioFaseRol = DBSession.query(
                            UsuarioFaseRol).filter(
                                UsuarioFaseRol.fase_id == fase).filter(
                                    UsuarioFaseRol.user_id == user).filter(
                                        UsuarioFaseRol.rol_id == rol1).one()
                        DBSession.delete(usuarioFaseRol)
                    except:
                        pass
                    new = UsuarioFaseRol(user_id=user,
                                         fase_id=fase,
                                         rol_id=rol1)

                    DBSession.add(new)
        redirect('/proyecto/usuario_faseList/' + fase)
Beispiel #28
0
class AdminController(TGController):
    """
    A basic controller that handles User Groups and Permissions for a TG application.
    """
    allow_only = in_group('managers')

    def __init__(self, models, session, config_type=None, translations=None):
        super(AdminController, 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.admin.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)
Beispiel #29
0
class PaymentsController(BaseController):
    def index(self):
        payments = self.user.payments
        c.forms = []
        for payment in payments:
            fs = PaymentForm.bind(payment)
            fs.readonly = True
            c.forms.append(fs)
        c.user = self.user
        return render('/payments.mako')

    @ActionProtector(predicates.in_group('bureau'))
    def edit(self, id, paymentDate=None, message=None):
        id = str(id)
        c.user = ldap.getUser(id)

        # forms
        payments = c.user.payments
        c.forms = []
        for payment in payments:
            if request.POST and paymentDate:
                if paymentDate in payment._dn:
                    fs = PaymentForm.bind(payment, data=request.POST or None)
                    if fs.validate():
                        fs.sync()
                        payment.save()
                        ldap.updateExpirationDate(user)
            fs = PaymentForm.bind(payment)
            c.forms.append(fs)

        # add form
        now = datetime.now()
        new_date = now
        payments = [p for p in payments if p.paymentAmount]
        if payments:
            last_payment = payments[-1]
            d = h.to_python(h.to_string(last_payment.paymentDate), datetime)
            if d + timedelta(365) < now - timedelta(90):
                new_date = d + timedelta(365)
        payment = ldap.Payment()
        payment.paymentDate = new_date
        payment.paymentObject = ldap.PERSONNAL_MEMBERSHIP
        c.new = NewPaymentForm.bind(payment, request.POST or None)
        c.message = message
        return render('/edit_payments.mako')

    @ActionProtector(predicates.in_group('bureau'))
    def delete(self, id, paymentDate):
        user = ldap.getUser(id)
        for p in user.payments:
            if paymentDate in p._dn:
                user._conn.delete(p)
                ldap.updateExpirationDate(user)
                break
        ldap.updateExpirationDate(user)
        message = 'Supprimer a %s' % datetime.now().strftime('%H:%M:%S')
        return self.edit(id, message=message)

    @ActionProtector(predicates.in_group('bureau'))
    def add(self, id):
        id = str(id)
        payment = ldap.Payment()
        fs = NewPaymentForm.bind(payment, data=request.POST)
        if fs.validate():
            fs.sync()
            user = ldap.getUser(id)
            user.append(payment)
            payment.save()
            message = 'Ajouter a %s' % datetime.now().strftime('%H:%M:%S')
        else:
            message = 'Erreur a %s' % datetime.now().strftime('%H:%M:%S')
        return self.edit(id, message=message)
Beispiel #30
0
                # result in readonly
                fs = NewUserForm.bind(user)
                fs2 = NewPaymentForm.bind(payment)
                fs.readonly = True
                fs2.readonly = True

                message = 'Utilisateur ajout&eacute; et son mot de passe envoy&eacute; par courriel'

        c.title = 'Inscription de membre'
        html = h.form(h.url.current(id=None), id="new_user")
        html += h.literal(fs.render(message=message))
        if fs2.readonly:
            html += h.literal(
                '<table width="100%" class="payments_listing listing">')
            html += h.literal(fs2.header())
            html += h.literal(fs2.render())
            html += h.literal('</table>')
        else:
            html += h.literal(
                '<table width="100%" class="payments_listing listing">')
            html += h.literal(fs2.header())
            html += h.literal('</table>')
            html += h.literal(fs2.render())
        html += h.end_form()
        c.body = h.literal(html)
        return render('/generic.mako')


AdminController = ControllerProtector(
    predicates.in_group('bureau'))(AdminController)
Beispiel #31
0
    def _query_result(self, kw):
        try:
            conditions=[]
            if kw.get("customerPO", False):
                conditions.append(DBAOrderInfo.po==kw["customerPO"].strip())

            if kw.get("sob", False):
                conditions.append(DBAOrderInfo.sob==kw["sob"].strip())

            if kw.get("orderStartDate", False) and kw.get("orderEndDate", False):
                b_date=dt.strptime(kw.get("orderStartDate", '2009-12-1200:00:00')+"00:00:00", "%Y-%m-%d%H:%M:%S")
                e_date=dt.strptime(kw.get("orderEndDate", '2009-12-1200:00:00')+"23:59:59", "%Y-%m-%d%H:%M:%S")
                conditions.append(DBAOrderInfo.create_time>=b_date)
                conditions.append(DBAOrderInfo.create_time<=e_date)
            elif kw.get("orderStartDate", False):
                b_date=dt.strptime(kw.get("orderStartDate", '2009-12-1200:00:00')+"00:00:00", "%Y-%m-%d%H:%M:%S")
                conditions.append(DBAOrderInfo.create_time>=b_date)
            elif kw.get("orderEndDate", False):
                e_date=dt.strptime(kw.get("orderEndDate", '2009-12-1200:00:00')+"23:59:59", "%Y-%m-%d%H:%M:%S")
                conditions.append(DBAOrderInfo.create_time<=e_date)

            if kw.get("shipStartDate", False) and kw.get("shipEndDate", False):
                b_date=date(*time.strptime(kw.get("shipStartDate", '2009-12-12'), '%Y-%m-%d')[:3])
                e_date=date(*time.strptime(kw.get("shipEndDate", '2009-12-12'), '%Y-%m-%d')[:3])
                conditions.append(DBAOrderInfo.ship_date>=b_date)
                conditions.append(DBAOrderInfo.ship_date<=e_date)
            elif kw.get("shipStartDate", False):
                b_date=date(*time.strptime(kw.get("shipStartDate", '2009-12-12'), '%Y-%m-%d')[:3])
                conditions.append(DBAOrderInfo.ship_date>=b_date)
            elif kw.get("shipEndDate", False):
                e_date=date(*time.strptime(kw.get("shipEndDate", '2009-12-12'), '%Y-%m-%d')[:3])
                conditions.append(DBAOrderInfo.ship_date<=e_date)
                
            
            #add@2011-07-20
            if kw.get("deliveryStartDate", False) and kw.get("deliveryEndDate", False):
                b_date=date(*time.strptime(kw.get("deliveryStartDate", '2009-12-12'), '%Y-%m-%d')[:3])
                e_date=date(*time.strptime(kw.get("deliveryEndDate", '2009-12-12'), '%Y-%m-%d')[:3])
                conditions.append(DBAOrderInfo.delivery_date>=b_date)
                conditions.append(DBAOrderInfo.delivery_date<=e_date)
            elif kw.get("deliveryStartDate", False):
                b_date=date(*time.strptime(kw.get("deliveryStartDate", '2009-12-12'), '%Y-%m-%d')[:3])
                conditions.append(DBAOrderInfo.delivery_date>=b_date)
            elif kw.get("deliveryEndDate", False):
                e_date=date(*time.strptime(kw.get("deliveryEndDate", '2009-12-12'), '%Y-%m-%d')[:3])
                conditions.append(DBAOrderInfo.delivery_date<=e_date)
            ############
            

            if kw.get("item_code", False):
                conditions.append(DBAItem.__table__.c.item_code.op('ilike')("%%%s%%" %kw["item_code"]))

            if kw.get("category_id", False):
                conditions.append(DBAItem.category_id==kw["category_id"])

            if kw.get("customer_id", False):
                conditions.append(DBAOrderInfo.customer_id == kw["customer_id"])

            if len(conditions):
                if kw.get("item_code", False) or kw.get("category_id", False):
                    obj=DBSession.query(DBAOrderInfo).join(DBAOrderDetail, DBAItem)
                else:
                    obj=DBSession.query(DBAOrderInfo)

                for condition in conditions: obj=obj.filter(condition)

                if not in_group("Admin") and not in_group("DBA_AE") and not in_group("DBA_BUYER"):
                    obj=obj.filter(DBAOrderInfo.create_by_id==request.identity["user"].user_id)
                result=obj.filter(DBAOrderInfo.active==0) \
                            .order_by(desc(DBAOrderInfo.id)) \
                            .all()
            else:
                if not in_group("Admin") and not in_group("DBA_AE") and not in_group("DBA_BUYER"):
                    result=DBSession.query(DBAOrderInfo) \
                         .filter(DBAOrderInfo.create_by_id==request.identity["user"].user_id) \
                         .filter(DBAOrderInfo.active==0) \
                         .order_by(desc(DBAOrderInfo.id)) \
                         .all()
                else:
                    result=DBSession.query(DBAOrderInfo) \
                                      .filter(DBAOrderInfo.active==0) \
                                      .order_by(desc(DBAOrderInfo.id)) \
                                      .all()
                        
            return result
        except:
            traceback.print_exc()
Beispiel #32
0
                    result['sell_price'],
                    result['buy_date'],
                    result['brand'],
                    photos,
                    result['tag']
                )
                product.code = result['code']
                product.wholesale_price = result['wholesale_price']
                product.deleted = False
                Session.add(product)
                Session.commit()

                h.flash(_('Product added successfully.'))
                redirect(url(controller='product', action='index'))    

    @ActionProtector(in_group('admin'))                            
    def edit(self,id):
        product = Session.query(Product).filter_by(id=int(id)).one()
        jd = jcal.gregorian_to_jd(product.buy_date.year, product.buy_date.month, product.buy_date.day)
        jalali = jcal.jd_to_jalali(jd)
        jalali = str(jalali[0])+'/'+str(jalali[1])+'/'+str(jalali[2])
        values={
            'code':product.code,
            'name':product.name,
            'brand':product.brand,
            'quantity':product.quantity,
            'description':product.description,
            'buy_price':product.buy_price,
            'sell_price':product.sell_price,
            'wholesale_price':product.wholesale_price,
            'buy_date':jalali,            
Beispiel #33
0
class AccountsController(BaseController):
    """Controller for Accounts """
    def index(self):
        """ Default to the account edit for your account? """
        abort(404)

    def login(self):
        """This is where the login form should be rendered."""
        if auth.check(not_anonymous()):
            # if we're not anonymous then we're logged in and need to be
            # redirected
            log.debug('already logged in')
            redirect(url('/page/test'))

        # Without the login counter, we won't be able to tell if the user has
        # tried to log in with the wrong credentials
        if 'repoze.who.logins' in request.environ:
            login_counter = request.environ['repoze.who.logins']
        else:
            login_counter = 0

        if login_counter > 0:
            log.debug('Wrong Login credentials')
            #flash('Wrong credentials')
        tpl.login_counter = login_counter
        tpl.came_from = request.params.get('came_from') or url('/')

        if 'login_failed' in request.params:
            tpl.login_failed = True
        else:
            tpl.login_failed = False
        return render('/login.mako')

    def post_login(self):
        """ Handle logic post a user's login

        I want to create a login_handler that's redirected to after login. This
        would check

        - if user was logged in, if not then send back to login
        - if user is admin, go to job list
        - if user can add joblist then go to *
        - if user is read only go to job list that's trimmed down a bit

        On the post login page adjust the max age on the existing cookie to XX
        remember me timeframe
        """
        if auth.check(not_anonymous()):
            log.debug('checked auth')
        else:
            # login failed, redirect back to login
            log.debug('failed auth')
            redirect(
                url(controller="accounts", action="login", login_failed=True))

        # expire this cookie into the future
        ck = request.cookies['authtkt']
        response.set_cookie('authtkt', ck, max_age=60 * 60 * 24 * 7, path='/')

        redirect(url('/page/test'))

    @ActionProtector(in_group('admin'))
    def list(self):
        """ List the user accounts in the system"""
        user_list = UserMgr.get_list()
        log.debug(user_list)
        tpl.user_list = user_list

        return render('/account/list.mako')

    @ActionProtector(in_group('admin'))
    @mijson()
    def edit(self, user_name):
        """Load the edit ui for this user"""
        tpl.user = UserMgr.get(user_name=user_name)
        tpl.group_list = GroupMgr.get_list()

        tpl.form_errors = False
        for g in tpl.group_list:
            if g in tpl.user.groups:
                log.debug("IN GROUP")
            else:
                log.debug("NOT IN GROUP")

        self.json.success = True
        return render('/account/edit.mako')

    @ActionProtector(in_group('admin'))
    @mijson()
    def edit_error(self):
        """Authenticate the changes to the user account specified

        Currently the only changes to a user account are to assign permission
        groups to it.

        """
        user_groups = request.params.getall('groups')
        user_name = request.params['user_name']

        user = UserMgr.get(user_name=user_name)

        # we're admin so we're allowed to do this regardless of username
        user.groups = GroupMgr.get_list(user_groups)
        redirect(url(controller="accounts", action="list"))

    def new(self):
        """Add a new user to the auth system

        """
        tpl.group_list = GroupMgr.get_list()
        tpl.form_errors = False
        return render('/account/new.mako')

    @validate(schema=UserFormNew(),
              form='new',
              post_only=False,
              on_get=True,
              auto_error_formatter=error_formatter,
              prefix_error=False)
    def new_errors(self):
        """Validate a new user account details

        """
        user = User()
        user.fromdict(request.params)

        # now make sure we create the group info
        # this just overwrites the from dict stuff I think
        user_groups = request.params.getall('groups')
        user.groups = GroupMgr.get_list(user_groups)

        try:
            meta.Session.add(user)
            #SystemLogger.log_activity('system',
            #        None,
            #        'Added new user: %s to the system' % user.user_name)

        except:
            meta.Session.rollback()

        # @todo fill in the code to create the queued job to process this
        # new file we just uploaded with tons of emails to create
        redirect(url(controller="accounts", action="list"))

    @ActionProtector(in_group('admin'))
    @mijson()
    def delete(self, user_name):
        """Remove a user from the system if this is an admin

        :param user_name: the user to remove from the system

        """
        user = UserMgr.get(user_name=user_name)
        meta.Session.delete(user)
        redirect(url(controller="accounts", action="list"))

    @ActionProtector(in_group('admin'))
    @mijson()
    def fetch_ldap_user(self, user_name):
        """ Attempt to find this user in the ldap database and return the user
        object

        :param id: string username or email address

        """
        ldap_server = config['app_conf']['auth.ldap_server']
        search = LDAPSearch(ldap_server)

        if user_name is None or user_name == "":
            self.json.success = False
            self.json.message = "Please supply a user name or email address"

        try:
            # see if this is an email search
            record = search.find_by_email(user_name)
            self.json.success = True
            self.json.payload = {'user': record.attributes}
        except LDAPNotFound:
            # if we fail to find the user by their email, just try it on the
            # cn:username
            try:
                record = search.find_by_cn(user_name)
                self.json.success = True
                self.json.payload = {'user': record.attributes}
            except LDAPNotFound:
                self.json.success = False
                self.json.message = "User %s not found in ldap system" % \
                    user_name

        if self.json.success:
            self.json.message = "Found user in the system as: %s" % \
                record.attributes['fullName']

        log.debug(self.json.payload)
        return self.json.message
Beispiel #34
0
                                      row_id=i,
                                      who=user.user_id,
                                      what=_('delete'),
                                      )

            dbs.flush()

            # success!
            return dict(status=True)

        except Exception, e:
            logger.error(e)
            return dict(status=False, message=str(e), rel_tables=rel_tables)

    @expose('sapns/order/insert.html')
    @require(p.in_group(u'managers'))
    @add_language
    def ins_order(self, cls, came_from='/'):

        user = dbs.query(SapnsUser).get(request.identity['user'].user_id)

        # check privilege on this class
        if not user.has_privilege(cls):
            redirect(url('/message',
                         params=dict(message=_('Sorry, you do not have privilege on this class'),
                                     came_from=came_from)))

        class_ = SapnsClass.by_name(cls)

        return dict(page='insertion order', insertion=class_.insertion(),
                    title=class_.title, came_from=url(came_from))
Beispiel #35
0
        return 'in group'


class SecurePanel(TGController):
    """Mock TG2 secure controller"""
    @expose()
    def index(self):
        return 'you are in the panel'

    @expose()
    @ActionProtector(in_group('developers'))
    def commit(self):
        return 'you can commit'


SecurePanel = ControllerProtector(in_group('admins'))(SecurePanel)


class SecurePanelWithHandler(TGController):
    """Mock TG2 secure controller"""
    @expose()
    def index(self):
        return 'you are in the panel with handler'

    @staticmethod
    def sorry(reason):
        response.status = 200
        return 'what are you doing here? %s' % reason


SecurePanelWithHandler = ControllerProtector(in_group('admins'),
Beispiel #36
0
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')
Beispiel #37
0
class ConnoisseurController(ServiceController):
    #Uncomment this line if your controller requires an authenticated user
    #allow_only = predicates.not_anonymous()

    service_type = "connoisseur"

    allow_only = Any(in_group("admin"), in_group('admins'),
                     in_group(service_type))

    def __init__(self, server_url):
        super(ConnoisseurController, self).__init__(server_url)
        self.basepath = os.path.dirname(inspect.getfile(
            inspect.currentframe()))
        self.workdir = config.get('bisque.connoisseur.models',
                                  data_path('connoisseur'))
        #_mkdir (self.workdir)

        self.path_models = os.path.join(self.workdir, 'models')
        self.path_templates = os.path.join(self.workdir, 'templates')
        self.path_images = os.path.join(self.workdir, 'images')
        _mkdir(self.path_models)
        _mkdir(self.path_templates)
        _mkdir(self.path_images)

        self.adapters_gobs = PluginManager(
            'adapters_gobs', os.path.join(self.basepath, 'adapters_gobs'),
            AdapterGobjectsBase)
        self.adapters_pixels = PluginManager(
            'adapters_pixels', os.path.join(self.basepath, 'adapters_pixels'),
            AdapterPixelsBase)

        # frameworks available in the system
        self.frameworks = PluginManager(
            'frameworks', os.path.join(self.basepath, 'frameworks'),
            FrameworkBase)

        # classifiers available to the system, requested with method argument
        self.classifiers = PluginManager(
            'classifiers', os.path.join(self.basepath, 'classifiers'),
            ClassifierBase)

        # importers are matched by their input mime and output mime
        self.importers = PluginManager(
            'importers', os.path.join(self.basepath, 'importers'),
            ImporterBase)
        self.importers_by_mime = {
            '%s;%s' % (e.mime_input, e.mime_type): e
            for k, e in self.importers.plugins.iteritems()
        }
        #log.debug('Importers: %s', self.importers_by_mime)

        # exporters are matched by their input mime and output mime
        self.exporters = PluginManager(
            'exporters', os.path.join(self.basepath, 'exporters'),
            ExporterBase)
        self.exporters_by_mime = {
            '%s;%s' % (e.mime_input, e.mime_type): e
            for k, e in self.exporters.plugins.iteritems()
        }
        #log.debug('Exporters: %s', self.exporters_by_mime)

        # loaded models hashed by their ID
        self.models_loaded_max = 10
        self.models = {}

        log.info('Connoisseur service started, using temp space at: %s' %
                 self.workdir)

    #----------------------------------------------------------------------------------------------
    # RESTful API
    #----------------------------------------------------------------------------------------------

    #@expose('bq.connoisseur.templates.index')
    @expose(content_type='text/xml')
    def index(self, **kw):
        """Add your service description here """
        self.log_start()
        try:
            return self.info()
        finally:
            self.log_finish()

    @expose()
    @require(predicates.not_anonymous(msg='Requires authenticated users'))
    def _default(self, *args, **kw):
        """find export plugin and run export"""
        self.log_start()
        path = request.path_qs.replace(self.baseuri, '', 1).split('/')
        path = [urllib.parse.unquote(p) for p in path if len(p) > 0]
        log.debug("Path: %s", path)

        #GET /connoisseur/MODEL_ID/classify:IMAGE_ID
        #GET /connoisseur/MODEL_ID/classify:IMAGE_ID/points:100

        #GET /connoisseur/MODEL_ID/train
        #GET /connoisseur/MODEL_ID/class:3/sample:1

        if len(path) < 1:
            #abort(responses.BAD_REQUEST, 'resource ID is required as a first parameter, ex: /connoisseur/MODEL_ID/classify:IMAGE_ID' )
            return self.info()
        model_uniq = path.pop(0)

        # parse URL: read all operations and arguments
        args = {}
        while len(path) > 0:
            o = path.pop(0)
            try:
                n, v = o.split(':', 1)
                args[n.lower()] = v
            except ValueError:
                args[o.lower()] = None

        # operations not requiring model uniq id
        op = model_uniq.lower()
        if op in ['info', 'api', 'devices', 'templates', 'template', 'create']:
            try:
                if op in ['info', 'api']:
                    return self.info()
                elif op in ['devices']:
                    return self.devices()
                elif op in ['templates']:
                    return self.templates(args)
                elif op in ['template']:
                    return self.template(args)
                elif op in ['create']:
                    return self.create(args)
            except ConnoisseurException, e:
                abort(e.code, e.message)
            except Exception:
                log.exception('Error processing %s', op)
                abort(responses.INTERNAL_SERVER_ERROR, 'Server error')
            finally:
Beispiel #38
0
     try:
         id_repo = get_paramw(kw, 'id_repo', int)
         r = SapnsDoc.upload(f, id_repo)
         
         return sj.dumps(dict(status=True, 
                              uploaded_file=r['uploaded_file'],
                              file_name=r['file_name'],
                              file_size=r['file_size'],
                              ))
     
     except Exception, e:
         logger.error(e)
         return sj.dumps(dict(status=False, message=str(e).decode('utf-8')))
     
 @expose()
 @require(p.Any(p.in_group('managers'), p.has_any_permission('manage', 'docs')))
 def download(self, id_doc):
     
     content, mt, file_name = SapnsDoc.download(int(id_doc))
     response.content_type = mt.encode('latin1')
     response.headers['Content-Disposition'] = 'attachment;filename=%s' % file_name
     
     return content
     
 @expose('json')
 @require(authorize.has_any_permission('manage', 'docs'))
 def remove_file(self, **kw):
     
     logger = logging.getLogger('DocsController.remove_file')
     try:
         file_name = get_paramw(kw, 'file_name', unicode)
class LineaBaseController(BaseController):
    @expose(template="gestionitem.templates.lineaBase.generar_linea_base")
    @require(
        All(
            in_group(
                'LiderProyecto',
                msg='Debe poseer Rol "LiderProyecto" para generar lineas bases'
            ),
            has_permission(
                'Gestionar linea base',
                msg=
                'Debe poseer Permiso "Generar linea base" para agregar fases'))
    )
    def generar_linea_base(self, idfase, **named):
        """ Se utiliza para generar la linea base de un fase indicada en el parametro.
   
        @param idfase: identificador de la fase.
        @type idfase: Integer
       
        @return: diccionario de todos los elementos que se obtienen con las consultas para mostrar en la pagina.
        @rtype: Diccionario.
        """
        expresion = ""

        itemSeleccionado = DBSession.query(ItemUsuario).filter_by(id=-1)
        itemselect = named.get('itemselect', '0')

        fase = DBSession.query(Fase).filter(Fase.id == idfase).one()

        if (itemselect != 0):
            try:
                itemselect = int(itemselect)
                itemselect = [itemselect]
                itemSeleccionado = DBSession.query(ItemUsuario).filter(
                    ItemUsuario.id.in_(itemselect)).order_by(ItemUsuario.id)
            except:
                itemSeleccionado = DBSession.query(ItemUsuario).filter(
                    ItemUsuario.id.in_(itemselect)).order_by(ItemUsuario.id)

        submit = named.get('submit')

        if (submit == "Buscar"):
            expresion = named.get('filtros')
            expre_cad = expresion
            items = DBSession.query(ItemUsuario).filter(
                ItemUsuario.estado_id == 8).filter(
                    ItemUsuario.fase_id == idfase).filter(
                        or_(
                            ItemUsuario.descripcion.like('%' + str(expre_cad) +
                                                         '%'),
                            (ItemUsuario.cod_item.like('%' + str(expre_cad) +
                                                       '%')))).order_by(
                                                           ItemUsuario.id)
        else:
            items = DBSession.query(ItemUsuario).filter(
                ItemUsuario.fase_id == idfase).filter(
                    ItemUsuario.estado_id == 8).all()

        return dict(items=items,
                    fase=fase,
                    filtro=expresion,
                    itemSeleccionado=itemSeleccionado)

    print generar_linea_base.__doc__

    @expose()
    def guardar_linea_base(self, faseid, **named):

        itemselect = named.get('itemselect')

        try:
            itemselect = int(itemselect)
            itemselect = [itemselect]
            itemseleccionados = DBSession.query(ItemUsuario).filter(
                ItemUsuario.id.in_(itemselect)).all()

            listaIds = DBSession.query(LineaBase).order_by(LineaBase.id)
            if (listaIds.count() > 0):
                list = listaIds[-1]
                id = list.id + 1
            else:
                id = 1

            lb = LineaBase(id=int(id),
                           version=1,
                           estado_id=1,
                           fase_id=int(faseid))
            DBSession.add(lb)
            DBSession.flush()

            for item in itemseleccionados:
                lbAnterior = item.linea_base_ant
                itemsEnLbAnterior = DBSession.query(ItemUsuario).filter(
                    ItemUsuario.linea_base_ant == lbAnterior).all()
                for itemLbAnt in itemsEnLbAnterior:
                    if itemLbAnt.estado_id == 5:
                        itemLbAnt.estado_id = 3
                        itemLbAnt.linea_base_id = id
                        itemLbAnt.linea_base_ant = id
                item.estado_id = 3
                item.linea_base_id = id
                item.linea_base_ant = id
                DBSession.flush()
        except:
            itemseleccionados = DBSession.query(ItemUsuario).filter(
                ItemUsuario.id.in_(itemselect)).all()
            listaIds = DBSession.query(LineaBase).order_by(LineaBase.id)
            if (listaIds.count() > 0):
                list = listaIds[-1]
                id = list.id + 1
            else:
                id = 1

            lb = LineaBase(id=int(id),
                           version=1,
                           estado_id=1,
                           fase_id=int(faseid))
            DBSession.add(lb)
            DBSession.flush()

            for item in itemseleccionados:
                lbAnterior = item.linea_base_ant
                itemsEnLbAnterior = DBSession.query(ItemUsuario).filter(
                    ItemUsuario.linea_base_ant == lbAnterior).all()
                for itemLbAnt in itemsEnLbAnterior:
                    if itemLbAnt.estado_id == 5:
                        itemLbAnt.estado_id = 3
                        itemLbAnt.linea_base_id = id
                        itemLbAnt.linea_base_ant = id
                item.estado_id = 3
                item.linea_base_id = id
                item.linea_base_ant = id
                DBSession.flush()

        estados = [1, 2, 3, 4, 5, 8]
        itemsEnLB = DBSession.query(ItemUsuario).filter(
            ItemUsuario.fase_id == faseid).filter(
                ItemUsuario.estado_id.in_(estados)).order_by(
                    ItemUsuario.id).all()
        faseConLB = 0
        for itemP in itemsEnLB:
            if itemP.estado_id != 3:
                faseConLB = 1
        if faseConLB == 0:
            fase = DBSession.query(Fase).filter_by(id=faseid).one()
            fase.estado_id = 4
            DBSession.flush()

        redirect('/item/itemList/' + faseid)

    @expose(template="gestionitem.templates.lineaBase.lista_linea_base")
    def listar_linea_base(self, idproyecto, idfase, **named):

        expresion = ""

        submit = named.get('submit')

        if (submit == "Buscar"):
            expresion = named.get('filtro')

            if expresion.isdigit():
                lista = DBSession.query(LineaBase).filter(
                    LineaBase.estado_id == 1).filter(
                        LineaBase.fase_id == idfase).filter(
                            LineaBase.id == int(expresion)).all()
            else:
                lista = DBSession.query(LineaBase).filter(
                    LineaBase.estado_id == 1).filter(
                        LineaBase.fase_id == idfase).all()
        else:
            lista = DBSession.query(LineaBase).filter(
                LineaBase.estado_id == 1).filter(
                    LineaBase.fase_id == idfase).all()

        fase = DBSession.query(Fase).filter(Fase.id == idfase).one()
        proyecto = DBSession.query(Proyecto).filter(
            Proyecto.id == idproyecto).one()

        from webhelpers import paginate
        #count = items.count()
        count = lista.__len__()
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            lista,
            page,
            item_count=count,
            items_per_page=2,
        )

        lista = currentPage.items

        return dict(lista=lista,
                    fase=fase,
                    proyecto=proyecto,
                    filtro=expresion,
                    currentPage=currentPage,
                    page=page)

    @expose(template="gestionitem.templates.lineaBase.lista_items_x_linea_base"
            )
    def items_linea_base(self, lb_id, idfase, **named):

        expresion = ""

        submit = named.get('submit')

        if (submit == "Buscar"):
            expresion = named.get('filtro')
            expre_cad = expresion
            items = DBSession.query(ItemUsuario).filter(
                ItemUsuario.estado_id == 3).filter(
                    ItemUsuario.linea_base_id == lb_id).filter(
                        or_(
                            ItemUsuario.descripcion.like('%' + str(expre_cad) +
                                                         '%'),
                            (ItemUsuario.cod_item.like('%' + str(expre_cad) +
                                                       '%')))).all()
        else:
            items = DBSession.query(ItemUsuario).filter(
                ItemUsuario.linea_base_id == lb_id).all()

        fase = DBSession.query(Fase).filter(Fase.id == idfase).one()
        lineabase = DBSession.query(LineaBase).filter(
            LineaBase.id == lb_id).one()

        from webhelpers import paginate
        #count = items.count()
        count = items.__len__()
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            items,
            page,
            item_count=count,
            items_per_page=2,
        )
        items = currentPage.items

        return dict(items=items,
                    fase=fase,
                    filtro=expresion,
                    lineabase=lineabase,
                    page=page,
                    currentPage=currentPage)

    @expose(
        template="gestionitem.templates.lineaBase.cerrar_linea_base_abierta")
    def cerrar_linea_base_abierta(self, idFase, **named):

        identity = request.environ.get('repoze.who.identity')
        user = identity['user']

        #CONSULTA ALA BD
        lbSolicitadas = DBSession.query(LineaBase).filter(
            LineaBase.estado_id == 2).filter(
                LineaBase.fase_id == idFase).all()
        itemsLBSol = []
        for idLB in lbSolicitadas:
            items = DBSession.query(ItemUsuario).filter(
                ItemUsuario.linea_base_id == idLB.id).filter(
                    ItemUsuario.estado_id == 5).all()
            codigosItemsSol = ""
            for item in items:
                codigosItemsSol = codigosItemsSol + "|" + item.cod_item + " "
            itemsLBSol.append(codigosItemsSol)

        fase = DBSession.query(Fase).filter_by(id=idFase).one()
        # SI EXISTE FILTROS DE BUSQUEDAS
        itemSelec = named.get('itemselect', '0')
        filtro = named.get('filtros', '')
        if (filtro != ""):
            if filtro.isdigit():
                lbSolicitadas = DBSession.query(LineaBase).filter(
                    LineaBase.estado_id == 2).filter(
                        LineaBase.fase_id == idFase).filter_by(
                            id=filtro).order_by(LineaBase.id).all()
            else:
                lbSolicitadas = DBSession.query(LineaBase).filter(
                    LineaBase.estado_id == 2).filter(
                        LineaBase.fase_id == idFase).filter(
                            LineaBase.descripcion.like('%' + str(filtro) +
                                                       '%')).order_by(
                                                           LineaBase.id).all()
            lbIds = []
            itemsLB = []

            for idLB in lbSolicitadas:
                lbIds.append(idLB.id)
                items = DBSession.query(ItemUsuario).filter(
                    ItemUsuario.linea_base_id == idLB.id).all()
                codigosItems = ""
                for item in items:
                    codigosItems = codigosItems + "|" + item.cod_item + " "
                itemsLB.append(codigosItems)

        proyecto = DBSession.query(Proyecto).filter_by(
            id=fase.proyecto_id).one()
        from webhelpers import paginate
        count = items.__len__()
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            items,
            page,
            item_count=count,
            items_per_page=3,
        )

        muestraBoton = "false"
        return dict(page='Solicitudes de Apertura',
                    user=user,
                    itemsLBSol=itemsLBSol,
                    muestraBoton=muestraBoton,
                    lbSolicitadas=lbSolicitadas,
                    named=named,
                    filtro=filtro,
                    itemSelec=itemSelec,
                    items=items,
                    fase=fase,
                    proyecto=proyecto,
                    currentPage=currentPage,
                    subtitulo='Solicitudes de Apertura')

    @expose()
    def accionSolicitud(self, idFase, **named):
        identity = request.environ.get('repoze.who.identity')
        user = identity['user']

        lbs = DBSession.query(LineaBase).filter_by(fase_id=idFase).filter_by(
            estado_id=2).all()
        for lb in lbs:
            accion = named.get(str(lb.id), '')
            if (accion != "") and (accion == "Cerrar"):
                lb.estado_id = 1
                DBSession.flush()
                ###Cambia Estado del Item
                items = DBSession.query(ItemUsuario).filter_by(
                    linea_base_id=lb.id).all()
                for item in items:
                    if (item.estado_id == 5):
                        item.estado_id = 3
                        DBSession.flush
                estados = [1, 2, 3, 4, 5, 8]
                itemsEnLB = DBSession.query(ItemUsuario).filter(
                    ItemUsuario.fase_id == idFase).filter(
                        ItemUsuario.estado_id.in_(estados)).order_by(
                            ItemUsuario.id).all()
                faseConLB = 0
                for itemP in itemsEnLB:
                    if itemP.estado_id != 3:
                        faseConLB = 1
                if faseConLB == 0:
                    fase = DBSession.query(Fase).filter_by(id=idFase).one()
                    fase.estado_id = 4
                    DBSession.flush()
        fase = DBSession.query(Fase).filter_by(id=idFase).one()

        redirect('/item/itemList/' + str(fase.id))

    @expose(
        template="gestionitem.templates.proyectoTmpl.listar_proyectos_definidos"
    )
    def listar_proyectos_definidos(self, idfaseDestino, **named):

        submit = named.get('submit')

        if (submit == "Buscar"):
            expresion = named.get('filtros')
            expre_cad = expresion
            proyectos = DBSession.query(Proyecto).filter(
                or_(Proyecto.estado == 2, Proyecto.estado == 3)).filter(
                    Proyecto.descripcion.like('%' + str(expre_cad) +
                                              '%')).all()
        else:
            proyectos = DBSession.query(Proyecto).filter(
                or_(Proyecto.estado == 2, Proyecto.estado == 3)).all()

        return dict(proyecto=proyectos,
                    filtro='',
                    proy='1',
                    idfaseDestino=idfaseDestino)

    @expose(
        template="gestionitem.templates.proyectoTmpl.listar_fases_definidas")
    def listar_fases_definidas(self, idfaseDestino, idproyecto, **named):
        expre_cad = ""
        proyecto = DBSession.query(Proyecto).filter_by(id=idproyecto).one()

        submit = named.get('submit')

        if (submit == "Buscar"):
            expresion = named.get('filtros')
            expre_cad = expresion
            fases = DBSession.query(Fase).filter(
                Fase.proyecto_id == idproyecto).filter(
                    Fase.descripcion.like('%' + str(expre_cad) + '%')).all()
        else:
            fases = DBSession.query(Fase).filter(
                Fase.proyecto_id == idproyecto).all()
        return dict(proyecto=proyecto,
                    fases=fases,
                    filtro=expre_cad,
                    idfaseDestino=idfaseDestino)

    @expose(
        template="gestionitem.templates.proyectoTmpl.importar_tipoItems_proyecto"
    )
    def importar_tipoItems_proyecto(self, idfaseDestino, idfase, **named):

        #proyecto= DBSession.query(Proyecto).filter(Proyecto.id == idproyecto).one()
        itemSeleccionado = DBSession.query(TipoItemUsuario).filter_by(id=-1)

        itemselect = named.get('itemselect', '0')

        if (itemselect != 0):

            try:
                itemselect = int(itemselect)
                itemselect = [itemselect]
                itemSeleccionado = DBSession.query(TipoItemUsuario).filter(
                    TipoItemUsuario.id.in_(itemselect)).order_by(
                        TipoItemUsuario.id)

            except:
                itemSeleccionado = DBSession.query(TipoItemUsuario).filter(
                    TipoItemUsuario.id.in_(itemselect)).order_by(
                        TipoItemUsuario.id)

        fase = DBSession.query(Fase).filter(Fase.id == idfase).one()

        proyecto = DBSession.query(Proyecto).filter(
            Proyecto.id == fase.proyecto_id).one()

        submit = named.get('submit')

        if (submit == "Buscar"):
            expresion = named.get('filtros')
            expre_cad = expresion
            itemUsuarios = DBSession.query(TipoItemUsuario).filter(
                TipoItemUsuario.fase_id == idfase).filter(
                    or_(
                        TipoItemUsuario.descripcion.like('%' + str(expre_cad) +
                                                         '%'),
                        (TipoItemUsuario.codigo.like('%' + str(expre_cad) +
                                                     '%')))).all()
        else:
            itemUsuarios = DBSession.query(TipoItemUsuario).filter(
                TipoItemUsuario.fase_id == idfase).all()

        return dict(listaItemUser=itemUsuarios,
                    proyecto=proyecto,
                    itemSeleccionado=itemSeleccionado,
                    filtro="",
                    fase=fase,
                    idfaseDestino=idfaseDestino)

    @expose()
    def guardar_items_importados(self, idfaseDestino, **named):

        itemselect = named.get('itemselect')

        try:
            itemselect = int(itemselect)
            itemselect = [itemselect]
            tipoItemSeleccionado = DBSession.query(TipoItemUsuario).filter(
                TipoItemUsuario.id.in_(itemselect)).all()

            tipoItemExiste = DBSession.query(TipoItemUsuario).filter(
                TipoItemUsuario.codigo == tipoItemSeleccionado.codigo).filter(
                    TipoItemUsuario.fase_id == idfaseDestino).all()

            if tipoItemExiste.__len__() == 0:
                listaIds = DBSession.query(TipoItemUsuario).order_by(
                    TipoItemUsuario.id)
                if (listaIds.count() > 0):
                    list = listaIds[-1]
                    id = list.id + 1
                else:
                    id = 1

                ti = TipoItemUsuario(
                    id=int(id),
                    descripcion=tipoItemSeleccionado.descripcion,
                    codigo=tipoItemSeleccionado.codigo,
                    fase_id=idfaseDestino)  #el parametro pasado aca debe ir.
                DBSession.add(ti)
                DBSession.flush()

                for atributo in tipoItemSeleccionado.atributos:

                    at = TipoItemUsuarioAtributos(
                        nombre_atributo=atributo.nombre_atributo,
                        tipo_item_id=int(id),
                        tipo_id=atributo.tipo_id)

                    DBSession.add(at)
                    DBSession.flush()

        except:

            itemseleccionados = DBSession.query(TipoItemUsuario).filter(
                TipoItemUsuario.id.in_(itemselect)).all()

            for tipoItemSelect in itemseleccionados:

                tipoItemExiste = DBSession.query(TipoItemUsuario).filter(
                    TipoItemUsuario.codigo == tipoItemSelect.codigo).filter(
                        TipoItemUsuario.fase_id == idfaseDestino).all()

                if tipoItemExiste.__len__() == 0:

                    listaIds = DBSession.query(TipoItemUsuario).order_by(
                        TipoItemUsuario.id)
                    if (listaIds.count() > 0):
                        list = listaIds[-1]
                        id = list.id + 1
                    else:
                        id = 1

                    ti = TipoItemUsuario(
                        id=int(id),
                        descripcion=tipoItemSelect.descripcion,
                        codigo=tipoItemSelect.codigo,
                        fase_id=idfaseDestino
                    )  #el parametro pasado aca debe ir.
                    DBSession.add(ti)
                    DBSession.flush()

                    for atributo in tipoItemSelect.atributos:

                        at = TipoItemUsuarioAtributos(
                            nombre_atributo=atributo.nombre_atributo,
                            tipo_item_id=int(id),
                            tipo_id=atributo.tipo_id)

                        DBSession.add(at)
                        DBSession.flush()

        redirect("/tipoItems/tipoItemUsuario/" + idfaseDestino + "/lista")
 def test_user_belongs_to_group(self):
     environ = make_environ('gustavo', ['developers'])
     p = predicates.in_group('developers')
     self.eval_met_predicate(p, environ)
Beispiel #41
0
 def customer(self):
     c.menu_items = h.top_menu(self.menu_items, _("Customers"))
     if is_met(in_group("customer")) or is_met(in_group("admin")):
         user = request.environ.get("repoze.who.identity")["user"]
         values = create_dict(user)
         return render_customer_form(self.menu_items, user.id, values)
Beispiel #42
0
 def is_superuser(self):
     """Return True if user is a superuser and has admin mode enabled."""
     return predicates.in_group("superusers") and self.admin_mode