Beispiel #1
0
 def save(self, id):
     order = h.checkorder(id)
     # Теперь - проверка прав доступа (админ либо ответственный подразделения, создавшего заявку)
     if not (h.have_role('admin') or h.have_role('operator') or (session.has_key('division') and (h.have_role('creator') and order.cust_id==session['division']) or (h.have_role('responsible') and order.perf_id==session['division']))):
         abort(401)
     for key, value in self.form_result.items():
         if getattr(order, key) != value and key not in ['inventories', 'urgent']:
             setattr(order, key, value)
     # Не все могут помечать заявку важной
     if h.have_role('admin') or (session.has_key('division') and h.have_role('responsible') and order.perf_id==session['division']):
         setattr(order, 'urgent', bool(self.form_result.get('urgent')))
     # Проверяем права
     # Изменяем отношения заявка <-> инвентарники
     for item in order.inventories: # Удаляем уже неактуальные отношения (удалённые при редактировании инвентарники)
         if item.id not in self.form_result['inventories']:
             order.inventories.remove(item)
     for inv in self.form_result['inventories']: # Добавляем новые отношения
         item = meta.Session.query(model.Inventory).get(inv);
         if not item:
             # <TODO text="Убрать добавление инвентарников в базу после введения проверок!">
             item = model.Inventory()
             item.id = inv
             meta.Session.add(item)
             # </TODO>
         if item not in order.inventories:
             order.inventories.append(item)
     meta.Session.commit()
     h.flashmsg (u"Заявка была изменена")
     redirect_to(h.url_for(controller='order', action='view', id=order.id))
Beispiel #2
0
    def list(self,id=None,page=1): 
        if "repoze.who.identity" in request.environ:
            user = request.environ.get('repoze.who.identity')['user']
            wholesale_tag = Session.query(UserTag).filter_by(tag='wholesale').one()
            if wholesale_tag in user.tags:
                c.wholesale=True
        c.tags = Session.query(ProductTag).all()
        c.menu_items = h.top_menu(self.menu_items,_('Shop online'))

        if session.has_key('product_querystr'):
            if session.has_key('paliasedtags'):
                for item in session['paliasedtags']:
                    exec(item)
            products = eval(session['product_querystr']+".filter(Product.deleted==False)")
            c.paginator = paginate.Page(products,
                                        page=int(request.params.get('page', page)),
                                        items_per_page = 10)
            html = render('/derived/product/list.html')
            return htmlfill.render(html,defaults=session['product_search_values'])
        else:
            products = Session.query(Product).filter_by(deleted=False)
            c.paginator = paginate.Page(products,
                                        page=int(request.params.get('page', page)),
                                        items_per_page = 10)
            return render('/derived/product/list.html')
Beispiel #3
0
 def revoke(self, id=None):
     """Отзыв заявки её создателем (например, решили проблему сами или «ложная тревога»)."""
     order = h.checkorder(id)
     # Заявка должна быть свободна!
     if order.status.id != 1:
         abort(403)
     # Проверка прав доступа (админ либо ответственный подразделения, создавшего заявку)
     if not (
         h.have_role("admin")
         or (
             session.has_key("division")
             and session.has_key("creator")
             and session["creator"]
             and order.cust_id == session["division"]
         )
     ):
         abort(401)
     # Заявка готова, но никто её не сделал
     order.status = meta.Session.query(model.Status).get(15)
     order.performers = []
     order.performer = None
     # Добавление записи в журнал действий над заявкой
     act = model.Action()
     act.order_id = order.id
     act.status = meta.Session.query(model.Status).get(15)
     act.division = meta.Session.query(model.Division).get(session["division"])
     act.performers.append(meta.Session.query(model.Person).get(session["id"]))
     if session.has_key("operator_id") and session["id"] != session["operator_id"]:
         act.performers.append(meta.Session.query(model.Person).get(session["operator_id"]))
     meta.Session.add(act)
     # Готово
     meta.Session.commit()
     h.flashmsg(u"Заявка № " + h.strong(order.id) + u" отозвана.")
     redirect_to(h.url_for(controller="order", action="view", id=order.id))
Beispiel #4
0
    def index(self):
        qorder = meta.Session.query(model.Order).filter_by(deleted=False)
        # Filter old orders (more than 1 year old)
        max_age = request.params.get('max_age_in_days', '365')
        if len(max_age) and max_age != 'unlimited':
            qorder = qorder.filter("age(orders.created) < interval ':age days'").params(age=int(max_age))
        freeorders = qorder.filter_by(status_id=1)  # .limit(10) #
        if (session.get('preferences') or dict()).get('upcat') is not None:
            c.upcat = meta.Session.query(model.UpperCategory).filter_by(url_text=session['preferences']['upcat']).one()
            freeorders = freeorders.filter_by(upcat_id=c.upcat.id)
        c.numfree = freeorders.count()
        c.freeorders = freeorders.order_by(model.sql.desc(model.Order.created))[:10]
        if session.has_key('division') and h.have_role('performer'): #session.has_key('performer') and session['performer']:
            # Заявки, выполняемые моим подразделением
            c.mydivorders = qorder.filter("status_id<>:value and perf_id=:perf").params(value=4, perf=session['division']).order_by(model.sql.desc(model.Order.created))[:10]
            # Заявки, выполняемые мной
            myperf = qorder.filter(model.sql.not_(model.Order.status_id.in_([1, 3, 4, 5])))
            myperf = myperf.filter(model.Order.performers.any(id=session['id']))
            c.myperforming = myperf.order_by(model.Order.created)[:10]
            # Жалобы!
            c.complaints = qorder.filter("status_id=:value and perf_id=:perf").params(value=6, perf=session['division']).order_by(model.Order.created).all()
        if session.has_key('division') and session.has_key('creator') and session['creator']:
            c.myownorders = qorder.filter("cust_id=:div").params(div=session['division']).order_by(model.sql.desc(model.Order.created))[:10]
            orderstoapprove = qorder.filter("status_id=:value and cust_id=:perf").params(value=3, perf=session['division'])
            c.orderstoapprove = orderstoapprove.order_by(model.Order.created)[:10]
            c.numtoapprove = orderstoapprove.count()
        # Немножко статистики на главную
        c.ordercount = meta.Session.query(model.Order).filter_by(deleted=False).count()
        statuses = meta.Session.query(model.Status).filter(model.Status.redirects==model.Status.id)\
            .order_by(model.Status.id).all()
        c.ordercountbystatus = [(unicode(status.title), status.ordercount) for status in statuses]

        return render('/main.html')
Beispiel #5
0
 def makethank (self):
     order = meta.Session.query(model.Order).filter_by(id=self.form_result['id']).first()
     if order is None:
         abort(404)
     if order.deleted:
         abort(410)
     # Теперь - проверка прав доступа (ответственный подразделения, подавшего эту заявку)
     if not (session.has_key('division') and session['division']):
         abort(401)
     if not (h.have_role('creator') and order.cust_id == session['division']):
         abort(403)
     thank = model.Action()
     thank.order_id = order.id
     thank.status = meta.Session.query(model.Status).get(14)
     thank.div_id = session['division']
     perf = meta.Session.query(model.Person).get(session['id'])
     thank.performers.append(perf)
     # Если претензию подаёт оператор, то и его добавим
     if session.has_key("operator_id") and session["id"] != session["operator_id"]:
         thank.performers.append(meta.Session.query(model.Person).get(session["operator_id"]))
     thank.description = self.form_result['description']
     meta.Session.add (thank)
     meta.Session.commit()
     h.flashmsg (u"Спасибо за " + h.literal("&laquo;") + u"спасибо" + h.literal("&raquo;") + "!")
     redirect_to(h.url_for(controller='order', action='view', id=order.id)) 
Beispiel #6
0
 def index(self):
     c.clients_quan = meta.Session.query(sidb.Client).count()
     c.sorts = [('name', sidb.Client.name), ('prdate', sidb.Tmppricesstorage.price_date), ('tmpitems', sidb.Tmppricesstorage.tmpitems_quan)]
     c.sort_col = request.GET.get("sort_field", 'name')
     sort_field = dict(c.sorts).get(c.sort_col)
     c.sort_rule = request.GET.get("sort_rule", 'asc')
     sort_field = (c.sort_rule == 'desc' and  sort_field.desc() or sort_field.asc())
     for key, value in request.POST.iteritems():
         if key in ['s_name', 's_country', 's_city']: session[key] = value  
     session.save()
     c.s_name = session.has_key('s_name') and session.get('s_name') or u''
     c.s_country = session.has_key('s_country') and session.get('s_country') or u''
     c.s_city = session.has_key('s_city') and session.get('s_city') or u''
     clients_list = meta.Session.query(sidb.Client, sidb.City, sidb.Country, sidb.Clientlogo, sidb.User, sidb.Tmppricesstorage.rid.label('storage_rid'),
                                         sidb.Tmppricesstorage.tmpitems_quan, sidb.Tmppricesstorage.price_date).\
                                        join((sidb.City, sidb.Client._cities_rid == sidb.City.rid)).\
                                        join((sidb.Region, sidb.City._regions_rid == sidb.Region.rid)).\
                                        join((sidb.Country, sidb.Region._countries_rid == sidb.Country.rid)).\
                                        outerjoin((sidb.User, sidb.User._clients_rid == sidb.Client.rid)).\
                                        outerjoin((sidb.Clientlogo, sidb.Clientlogo._clients_rid == sidb.Client.rid)).\
                                        outerjoin((sidb.Tmppricesstorage, sidb.Tmppricesstorage._clients_rid == sidb.Client.rid)).\
                                        group_by(sidb.Client.rid).order_by(sort_field)
                     
     if c.s_name: clients_list = clients_list.filter(sidb.Client.name.like('%'+c.s_name+'%'))
     if c.s_country: clients_list = clients_list.filter(sidb.Country.name.like('%'+c.s_country+'%'))
     if c.s_city: clients_list = clients_list.filter(sidb.City.name.like('%'+c.s_city+'%'))
     page = paginate.Page(clients_list, items_per_page=15, page=request.GET.get("page", 1), sort_col=c.sort_col, sort_rule=c.sort_rule)
     c.pager = page.pager()
     c.clients_list = page.items
     c.subtempl = 'clients_list'
     return render('be/layouts/clients.html')
Beispiel #7
0
 def makecomplaint (self):
     order = meta.Session.query(model.Order).filter_by(id=self.form_result['id']).first()
     if order is None:
         abort(404)
     if order.deleted:
         abort(410)
     # Теперь - проверка прав доступа (ответственный подразделения, подавшего эту заявку)
     if not (session.has_key('division') and session['division']):
         abort(401)
     if not (h.have_role('creator') and order.cust_id == session['division']):
         abort(403)
     complaint = model.Action()
     complaint.order_id = order.id
     complaint.status = meta.Session.query(model.Status).get(6)
     complaint.div_id = session['division']
     perf = meta.Session.query(model.Person).get(session['id'])
     complaint.performers.append(perf)
     # Если претензию подаёт оператор, то и его добавим
     if session.has_key("operator_id") and session["id"] != session["operator_id"]:
         complaint.performers.append(meta.Session.query(model.Person).get(session["operator_id"]))
     complaint.description = self.form_result['description']
     meta.Session.add (complaint)
     order.status = meta.Session.query(model.Status).get(6)
     # Обновляем создателей заявки
     if perf not in order.customers:
         order.customers.append(perf)
     meta.Session.commit()
     h.flashmsg (u"Жалоба подана. Всех лишат зарплаты. Дело заявки № " + h.strong(order.id) + u" будет сделано.")
     redirect_to(h.url_for(controller='order', action='view', id=order.id)) 
Beispiel #8
0
def authenticated_user(reload=False):
    """
    Returns reference to AuthenticatedUser which is stored in session.
    If it's not in session method will add it and save session, then return object.
    """

    AUTHENTICATED_USER = "******"

    # Create authenticated user if it doesn't exist
    if request.environ.has_key('REMOTE_USER'):
        if reload or not session.has_key(AUTHENTICATED_USER) \
            or session[AUTHENTICATED_USER] == None \
            or session[AUTHENTICATED_USER].username != request.environ['REMOTE_USER']:
            model = request.environ['sqlalchemy.model']
            db = request.environ['sqlalchemy.session']

            try:
                authenticated_user = db.query(model.AuthenticatedUser).filter_by(username=request.environ['REMOTE_USER']).one()
            except:
                authenticated_user = model.AuthenticatedUser(
                    username = request.environ['REMOTE_USER'], email = request.environ['REMOTE_USER'])
                db.save(authenticated_user)
                db.commit()
                log.info(_("Created an %s" % (str(authenticated_user))))
            db.expunge(authenticated_user)
            session[AUTHENTICATED_USER] = authenticated_user
            session.save()
    
        return session[AUTHENTICATED_USER]

    if session.has_key(AUTHENTICATED_USER):
        session.pop(AUTHENTICATED_USER, None)
        session.save()

    return None
Beispiel #9
0
    def __before__(self, action, controller, *args, **kwargs):
        log.debug("Connection at %s.%s." % ( controller, action ) )

        # Global messages
        c.glob_messages = []

        # Detect global message passed in session (flash).
        if 'uimessage' in web_session:
            c.glob_messages.append(web_session['uimessage'])
            del web_session['uimessage']
            web_session.save()

        # Detect configuration changes.
        def config_has_changed():
            #model.new_engine() # not needed
            #model.init_local() # not needed
            kcd_model.new_engine()
            kcd_model.init_local()
            freemium_model.new_engine()
            freemium_model.init_local()
        detect_cached_config_change(config_has_changed)

        # Get cached master configuration.
        c.mc = get_cached_master_config()

        # Initialize models in local thread.
        #model.init_local() # not needed
        kcd_model.init_local()
        freemium_model.init_local()

        require_auth = None
        try:
            # Get the require_auth attribute.
            require_auth = getattr(self, 'require_auth')
        except AttributeError:
            # Class has no require_auth parameter.
            pass

        if require_auth and action in require_auth:
            # Object has a require_auth parameter.
            if not web_session.has_key('logged') or web_session['logged'] != True:
                # User is not logged.
                log.info("User not logged... redirecting to the login page.")
                return redirect(url_for('login'))

        c.logged = False
        if web_session.has_key('logged') and web_session['logged']:
            # Show logout button.
            c.logged = True

        # Get services objects.
        c.services = K2Services()

        # Load services status.
        for name, service in c.services.items():
            service.update_from_conf(c.mc)
Beispiel #10
0
    def createbasket(self):
        came_from = str(request.GET.get('came_from', ''))
        values = dict(request.params)
        for item in values:
            if item.startswith('product_id.'):
                id = int(item.split('.')[-1])
                try:
                    product = Session.query(Product).filter_by(id=id).one()
                except:
                    h.flash(_('No product exist with ID: %s')%id)
                    redirect(url(controller='product',action='list'))
        if values['quant']!='':
            quantity = int(values['quant'])
        else:
            quantity =1        

        if session.has_key('basket'):
            session['basket'][id]=quantity
        else:
            session['basket']={id:quantity}
        product = Session.query(Product).filter_by(id=id).one()
        h.flash(_('%s of product %s added to basket')%(quantity,product.name))
        if came_from !='':            
            return redirect(came_from)
        redirect(url(controller='product',action='list'))
Beispiel #11
0
 def edit(self, id):
     c.order = h.checkorder(id)
     # Теперь - проверка прав доступа (админ либо ответственный подразделения, создавшего заявку)
     h.requirelogin()
     if not (
         h.have_role("admin")
         or h.have_role("operator")
         or (
             session.has_key("division")
             and (h.have_role("creator") and c.order.cust_id == session["division"])
             or (h.have_role("responsible") and c.order.perf_id == session["division"])
         )
     ):
         abort(403)
     work = meta.Session.query(model.Work).order_by(model.Work.id).all()
     c.work = []
     for i in work:
         c.work.append([i.id, i.title])
     category = (
         meta.Session.query(model.Category)
         .filter(model.Category.upcat_id == c.order.upper_category.id)
         .order_by(model.Category.id)
         .all()
     )
     c.category = []
     for i in category:
         c.category.append([i.id, i.title])
     upcategory = (
         meta.Session.query(model.UpperCategory).filter_by(deleted=False).order_by(model.UpperCategory.id).all()
     )
     c.upcategory = [[None, u" -- выберите надкатегорию -- "]]
     for i in upcategory:
         c.upcategory.append([i.id, i.title])
     return render("/orders/edit.html")
Beispiel #12
0
    def _gccom_jobs(self, model_key, mode):
        c.jobstate          = 'build'
        c.jobmsg            = 'build: setting up the job. before submission.'
        c.model_key         = model_key
        c.mode              = mode
        c.error_flash       = None
        if session.has_key('error_flash'):
            c.error_flash = session['error_flash']
            try: del session['error_flash']
            except Exception as _: pass
        c.jobname           = '%s_%s' % (model_key, mode)
        c.cwuser            = session.get('user','user')
        c.acct              = Gccom.gccom_comm_acct
        c.model_param_hdrs  = Gccom.model_params['hdrs']
        c.model_params      = Gccom.model_params[c.model_key]
        c.model_desc        = str(Gccom.model_info[c.model_key]['desc'])
        c.title             = 'GCOM %s Simulation: Model:%s for JobName: %s' % (
                                   c.mode, str(c.model_desc), c.jobname)

        c.resources = h.get_user_resources(session.get('user_id'))
        c.hostname  = c.resources.keys()[0] if c.resources else ''     #used to init/set default host; reset later 

        c.grid_key          = Gccom.model_info[c.model_key]['grid_key']
        c.grid_imax         = Gccom.bath_grid[c.grid_key]['IMax']
        c.grid_jmax         = Gccom.bath_grid[c.grid_key]['JMax']
        c.grid_kmax         = Gccom.bath_grid[c.grid_key]['KMax']
        c.grid_name         = Gccom.bath_grid[c.grid_key]['name']
        c.grid_fname        = Gccom.bath_grid[c.grid_key]['fname']
        log.info( 'GCOM:: gccom_jobs:  building form data for model_key=%s, desc=%s, jobstate= %s, jobname= %s, gridname= %s, gridfnam=%s' % (c.model_key, c.model_desc,c.jobstate, c.jobname, c.grid_name, c.grid_fname))
        return render('/gcem/gccom/app_' + c.mode.lower() + '.mako')
 def contact_insert(self):
     '''functional controller'''
     if session.has_key("edit"):
         session['update'] = {}
         for item in request.params.items():
             session['update'][item[0]] = item[1]
         session.save()
         return redirect_to(controller='uniaddbook', action='contact_update', method="post")
     else:
         meta.Session.begin()
         meta.Session.add(Contact(first_name = str(request.params['fname']),
                     middle_name = str(request.params['mname']),
                     last_name = str(request.params['lname']),
                     nick_name = str(request.params['nname']),
                     birthday = datetime(year=int(request.params['year']), month=int(request.params['month']), day=int(request.params['day'])),
                     street_address = str(request.params['street']),
                     country = str(request.params['country']),
                     city = str(request.params['city']),
                     zipcode = int(request.params['zipcode']),
                     state_id = int(request.params['State']),
                     relationship_id = int(request.params['relationship'])))
         meta.Session.commit()
         session["id"] = meta.Session.query(Contact).order_by("id DESC").all()[0].id
         session.save()
         return redirect_to(controller='uniaddbook', action='contact_show', method="post")
Beispiel #14
0
def check_flash():
    # If the session data isn't of the particular format python has trouble.
    # So we check that it is a dict.
    if session.has_key("flash"):
        if type(session["flash"]) != dict:
            del session["flash"]
            session.save()
Beispiel #15
0
def check_flash():
    """If the session data isn't of the particular format python has trouble.
    So we check that it is a dict."""
    if session.has_key('flash'):
        if type(session['flash']) != dict:
            del session['flash']
            session.save()
Beispiel #16
0
    def add(text, type='cool'):
        """ Add a message to the message queue.
        
        Concerning the message type, it can be anything but to have any
        relevance to the end user it should have the name of a class in the CSS
        file.
        
        By default the available message types are:
        - cool (green)
        - warning (yellow)
        - critical (red)
        
        Keyword arguments:
        text -- the text to show in the message
        type -- the type of message. default value is 'cool'
        
        """
        if len(type) == 0:
            type = 'cool'
            
        if not session.has_key('swat_messages'):
            session['swat_messages'] = []

        session['swat_messages'].append({'text' : text, 'type' : type})
        session.save()
Beispiel #17
0
    def news(self):
        # Gather the messages to be displayed
        num_messages = 50
        c.messages = []

        # select user messages AND generic messages
        if session.has_key('user_id') and session.has_key('user_groups'):
            messages = meta.Session.query(Message).filter(sa.or_(Message.recipient_group_id.in_(session['user_groups']), Message.recipient_user_id == session['user_id'], sa.and_(Message.recipient_group_id == sa.null(), Message.recipient_user_id == sa.null()))).limit(num_messages)
        # select generic messages (user not logged in)
        else:
            messages = meta.Session.query(Message).filter(sa.and_(Message.recipient_group_id == sa.null(), Message.recipient_user_id == sa.null())).limit(num_messages)
        for i in messages:
            c.messages.append({'date':i.date.strftime("%b %d,%y %H:%M %p"), 'message':i.message})

        meta.Session.close()
        return render('/account/news.mako')    
Beispiel #18
0
    def add(text, type="cool"):
        """ Add a message to the message queue.
        
        Concerning the message type, it can be anything but to have any
        relevance to the end user it should have the name of a class in the CSS
        file.
        
        By default the available message types are:
        - cool (green)
        - warning (yellow)
        - critical (red)
        
        Keyword arguments:
        text -- the text to show in the message
        type -- the type of message. default value is 'cool'
        
        """
        if len(type) == 0:
            type = "cool"

        if not session.has_key("swat_messages"):
            session["swat_messages"] = []

        session["swat_messages"].append({"text": text, "type": type})
        session.save()
Beispiel #19
0
 def choose (self, id=None):
     c.order = h.checkorder(id)
     # Теперь - проверка прав доступа (ответственный подразделения, выполняющего заявки)
     if not (h.have_role('admin') or ((h.have_role("appointer")) and session.has_key('division') and c.order.perf_id == session['division'])):
         abort(403)
     actionquery = meta.Session.query(model.Action)
     #if actionquery.filter_by(div_id=c.order.perf_id).all() is None:
     #    lastaction = None
     #else:
     #    lastaction = actionquery.filter_by(div_id=c.order.perf_id).order_by(model.sql.desc(model.Action.created)).first()
     lastaction = actionquery.filter_by(order_id=id).filter_by(div_id=c.order.perf_id).filter(model.Action.status_id != 16).order_by(model.sql.desc(model.Action.created)).first()
     c.actions = actionquery.filter_by(order_id=id).order_by(model.Action.created).all()
     # Статусы
     statuses = meta.Session.query(model.Status).order_by(model.Status.gui_priority)
     if h.have_role('admin'): excluded_statuses = [1, 4, 6, 11, 12, 14]
     else: excluded_statuses = [1, 2, 4, 6, 11, 12, 14]
     c.statuses = [["", u" -- выберите -- "]] + [[status.id, status.title] for status in statuses if status.id not in excluded_statuses]
     # Люди-исполнители
     performers = meta.Session.query(model.Person).filter_by(deleted=False).filter_by(performer=True).order_by(model.Person.surname, model.Person.name, model.Person.name)
     if h.have_role('admin') and lastaction is not None:
         performers = performers.filter_by(div_id=lastaction.div_id)
     else:
         performers = performers.filter_by(div_id=session['division'])
     c.performers = [[user.id, h.name(user)] for user in performers]
     if lastaction is not None:
         c.curperfs = [x.id for x in c.order.performers]
         c.curdiv = lastaction.div_id
     if h.have_role("admin"):
         divlist = [x.div_id for x in meta.Session.query(model.Person.div_id).filter_by(performer=True).all()]
         c.divisions = [[x.id, x.title] for x in meta.Session.query(model.Division).filter_by(deleted=False).filter(model.Division.id.in_(divlist)).all()]
     return render("/actions/choose.html")
Beispiel #20
0
 def session_test(self):
     key = "session_test"
     if not session.has_key(key):
         session[key] = 0
     else:
         session[key] = session[key]+1
     return str(session[key])
Beispiel #21
0
def check_flash():
    # If the session data isn't of the particular format python has trouble.
    # So we check that it is a dict.
    if session.has_key('flash'):
        if type(session['flash']) != dict:
            del session['flash']
            session.save()
Beispiel #22
0
def flash(msg, category="information"):
    check_flash()
    if not session.has_key('flash'):
        session['flash'] = {}
    if not session['flash'].has_key(category):
        session['flash'][category] = []
    session['flash'][category].append(msg)
    session.save()
Beispiel #23
0
 def clean():
     """ Cleanup message queue. This should be called after messages are
     shown in the template
     
     """
     if session.has_key('swat_messages'):
         del session['swat_messages']
         session.save()
Beispiel #24
0
 def clean():
     """ Cleanup message queue. This should be called after messages are
     shown in the template
     
     """
     if session.has_key("swat_messages"):
         del session["swat_messages"]
         session.save()
Beispiel #25
0
def flash(msg, category="information"):
    check_flash()
    if not session.has_key('flash'):
        session['flash'] = {}
    if not session['flash'].has_key(category):
        session['flash'][category] = []
    session['flash'][category].append(msg)
    session.save()
Beispiel #26
0
 def destroy(self):
     """Destroy all persistent storage created by this object"""
     self.removefile()
     c = session.get('captcha', None)
     if session.has_key('captcha'):
         del session['captcha']
     session.save()
     return
 def index(self):
     if session.has_key('login'):
         if session['login']:
             return render('/parser_settings/parser.mako.html')
         else:
             return render('/login/login.mako.html')
     else:
         return render('/login/login.mako.html')
Beispiel #28
0
def get_flashes():
    check_flash()
    if not session.has_key('flash'):
        return None
    messages = session['flash']
    # it is save to delete now
    del (session['flash'])
    session.save()
    return messages
 def contact_add(self):
     '''mako controller'''
     
     self.contact_selection_boxes()
     
     if session.has_key("id"):
         session['id'] = meta.Session.query(Contact).order_by('id DESC').all()[0].id
         session.save()
     return render('/contact_add.mako')
Beispiel #30
0
    def set_nowplaying(self, song):
        self._nowplayingid = song.id
        stats = Session.query(SongStat).\
            filter(SongStat.song == song).\
            filter(SongStat.user == self)

        if session.has_key('src'):
            stats = stats.filter(SongStat.source == session['src'])

        stats = stats.first()
        if not stats:
            stats = SongStat(user = self, song = song)

        stats.playcount = stats.playcount + 1
        stats.lastplayed = datetime.now()
        if session.has_key('src'):
            stats.source = session['src']
        Session.add(stats)
Beispiel #31
0
 def logout(self):
     c.userid = None
     c.message = "We hope to see you soon!"
     #display_message("We hope to see you soon!", status="success")
     came_from = request.params.get('came_from', '') or "/"
     if session.has_key('user_name'):
         del session['user_name']
     if session.has_key('user_uri'):
         del session['user_uri']
     if session.has_key('user_id'):
         del session['user_id']
     if session.has_key('user_dept'):
         del session['user_dept']
     if session.has_key('user_email'):
         del session['user_email']
     session.save()
     #return redirect(came_from, code=303)
     return render('/logout.html')
Beispiel #32
0
 def logout(self):
     c.userid = None
     c.message = "We hope to see you soon!"
     #display_message("We hope to see you soon!", status="success")
     came_from = request.params.get('came_from', '') or "/"
     if session.has_key('user_name'):
         del session['user_name']
     if session.has_key('user_uri'):
         del session['user_uri']
     if session.has_key('user_id'):
         del session['user_id']
     if session.has_key('user_dept'):
         del session['user_dept']
     if session.has_key('user_email'):
         del session['user_email']
     session.save()
     #return redirect(came_from, code=303)
     return render('/logout.html')
Beispiel #33
0
def get_flashes():
    check_flash()
    if not session.has_key('flash'):
        return None
    messages = session['flash']
    # it is save to delete now
    del(session['flash'])
    session.save()
    return messages
Beispiel #34
0
 def submit_code(self):
     session['invitation_id'] = self.form_result['code'].id
     session.save()
     if (session.has_key('redir')):
         redir = session['redir']
         del(session['redir'])
         session.save()
         redirect(redir)
     else:
         redirect(url(controller = 'guests', action = 'confirmation_list'))
Beispiel #35
0
 def index(self):
     
     """
         Функция для отображения физуального интерфейса пользователя
     """
     
     if session.has_key('login'):
         return render('/login/login.mako.html')
     else:
         return render('/login/login.mako.html')
Beispiel #36
0
    def post_logout(self):
        flash = None
        basket = None
        
        if session.has_key('flash'):
            flash = session['flash']
        if session.has_key('basket'):
            basket = session['basket']

        session.clear()
        
        if flash:
            session['flash']=flash
        if basket:
            session['basket'] = basket
            
        session.save()
        redirect(url(controller='home', action='index'))
        
Beispiel #37
0
    def index(self):
        basedir = 'cyberweb/public'
        gallerydir = 'gcem-gallery'

        # Gather the messages to be displayed
        num_messages = 5
        c.messages = []


#        # select user/group specific  and generic messages
        if session.has_key('user_id') and session.has_key('user_groups'):
            messages = meta.Session.query(Message).filter(sa.or_(Message.recipient_group_id.in_(session['user_groups']), Message.recipient_user_id == session['user_id'], \
                                                                 sa.and_(Message.recipient_group_id == sa.null(), Message.recipient_user_id == sa.null()))).limit(num_messages)
#        # select generic messages (user not logged in)
        else:
            messages = meta.Session.query(Message).filter(sa.and_(Message.recipient_group_id == sa.null(), Message.recipient_user_id == sa.null())).limit(num_messages)

        c.messages =  [ ({'date':i.date.strftime("%b %d,%y %H:%M %p"), 'message':i.message}) for i in messages ]
        c.resources = meta.Session.query(Resource).filter(Resource.active == 1).distinct()
        c.service_names = meta.Session.query(ServiceName).distinct()

        # Gather images for the slideshow on the homepage
        # Pickup captions from a text file and match it to the filename
        c.images = []
        c.captions = dict()
        key = '/' + gallerydir + '/'
        try:
            fh = open(basedir + '/' + gallerydir + '.captions')
            for line in fh:
                arr = line.split('|')
                c.captions[key + arr[0]] = '|'.join(arr[1:]).strip()
            fh.close()
        except:
            log.error('Failed reading opening captions')
        for i in os.listdir(basedir + '/' + gallerydir):
            if i[0] != '.':
                c.images.append(key + i)
            if not c.captions.has_key(key + i):
                c.captions[key + i] = 'No caption'

        meta.Session.close()
        return render('/gallery.mako')
Beispiel #38
0
    def any():
        """ Checks if there are any messages in the queue.
        Returns a boolean value
        
        """
        has_any = False

	if session.has_key('swat_messages') and len(session['swat_messages']) > 0:
	    has_any = True
	    
	return has_any
Beispiel #39
0
def flash(msg, category="information"):
    check_flash()
    if not session.has_key('flash'):
        session['flash'] = {}
    if not session['flash'].has_key(category):
        session['flash'][category] = []
    # If we are redirected we may flash this more than once. Check
    # the message hasn't already been set by looking in the session
    if msg not in session['flash'][category]:
        session['flash'][category].append(msg)
    session.save()
Beispiel #40
0
    def login(self):
        # The user is already logged in; redirect to the status page.
        if web_session.has_key('logged') and web_session['logged']:
            return redirect(url_for('status'))

        # Initialize web session.
        self._init_session()

        # Load master config.
        master_config = load_master_config()

        # FIXME: isinstance(...) could be removed if property has a null=False parameter... check that with Laurent.
        pwd = None
        if isinstance(master_config.admin_pwd,
                      basestring) and len(master_config.admin_pwd) > 0:
            # Admin password is set.

            # Get the provided password, if any.
            pwd = request.POST.get('cfg_password', None)

            if pwd:
                if pwd == master_config.admin_pwd:
                    # User has provided the right password.
                    self._login()

                    # Redirect to the status page.
                    return redirect(url_for('status'))

                else:
                    # Show a bad password message.
                    ui_error(message=GT("login.bad_password"))

        else:
            # Admin password is not set yet; show a warning message.
            ui_error(message=GT("locals.admin_password_not_set"))

        # Push variables to template.
        c.pwd = pwd
        c.GT = GT

        return render('/login/login.mako')
Beispiel #41
0
 def show_kws_mgt_query_page(self):
    
     # Define the session variables, if required.
     if not web_session.has_key("kws_mgt_query_offset"):
         self.reset_kws_mgt_query()
     
     # Obtain the Teambox list.
     kws_list = self.get_kws_mgt_kws_list(web_session["kws_mgt_query_offset"], web_session["kws_mgt_query_limit"])
     
     # Obtain the information about the Teamboxes.
     kws_dict = odict()
     for kws_id in kws_list: kws_dict[kws_id] = self.get_kws_mgt_kws_info(kws_id)
     
     # Show the information.
     action_url = url_for('teamboxes')
     
     # Get the Teambox list content.
     s = ""
     for kws_info in kws_dict.values():
         kws_href = action_url + "?kws_mgt_specific_kws=%i" % (kws_info.kws_id)
         s += '    <tr>\n'
         s += '      <td><input type="checkbox" name="kws_mgt_kws_cb_%i"/></td>\n' % (kws_info.kws_id)
         s += '      <td class="kwstableid">%i</td>\n' % (kws_info.kws_id)
         s += '      <td class="kwstablename"><a href="%s">%s</a></td>\n' % \
              (kws_href, kweb_lib.html_text_escape(kws_info.name))
         s += '      <td class="kwstablestats">%i</td>\n' % (len(kws_info.user_list))
         s += '      <td class="kwstablestats">%s MiB</td>\n' % (self.format_as_mb(kws_info.file_size, 2))
         s += '      <td class="kwstablestats">%s</td>\n' % (self.format_kws_date(kws_info.creation_date))
         s += '      <td class="kwstablestats">%s</td>\n' % (kweb_lib.html_text_escape(kws_info.org_name))
         s += '    </tr>\n'
     kws_table_body = s
    
     # Push variables to template.  
     c.action_url = action_url
     c.kws_table_body = kws_table_body
     c.kws_mgt_query_offset = web_session["kws_mgt_query_offset"] + 1
     c.kws_mgt_query_limit = web_session["kws_mgt_query_limit"]
     
     return render('/teamboxes/query.mako')
Beispiel #42
0
def alive():
    if session.has_key('user_id') and session.has_key('name'):
        return True
    else:
        return False
Beispiel #43
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        try:
            id = ''
            if 'type' in request.params:
                id = request.GET.get('type')
                #if id == 'amps-nmr':
                #    c.num = 3
                #elif id == 'maxocc':
                #    c.num = 12
                #elif id == 'anisofit':
                #    c.num = 11
            elif 'id' in request.params:
                id = request.GET.get('id')
                #print '*'*40,id
            elif session.has_key('PORTAL'):
                id = session['PORTAL']
            else:
                id = 'amps-nmr'
                #c.num = 3
            #if session.has_key('PORTAL'):
            #    if session['PORTAL'] == 'amps-nmr':
            #        c.num = 3
            #        id = session['PORTAL']
            #    elif session['PORTAL'] == 'maxocc':
            #        c.num = 13
            #        id = session['PORTAL']
            #    elif session['PORTAL'] == 'anisofit':
            #        c.num = 11
            #        id = session['PORTAL']
            #f = open('/tmp/mah', 'w')
            #f.write(id)
            #f.close()

            if id == '1' or id == '5':

                return WSGIController.__call__(self, environ, start_response)
            if id in portalwithmenu:
                if id == 'amber':
                    print "someone use amber yet!"
                    id = 'amps-nmr'
                ca = Session.query(CalculationTipology).filter(
                    CalculationTipology.tipology == id)
                type_id = ca[0].id
                portal_menu = Session.query(Menu).filter(
                    and_(Menu.parent_id == None, Menu.sibling_id == None,
                         Menu.calctype_id == type_id)).order_by(
                             Menu.weight.asc()).all()
                all_menu = Session.query(Menu).filter(
                    and_(Menu.parent_id == None, Menu.sibling_id == None,
                         Menu.calctype_id == 4)).order_by(
                             Menu.weight.asc()).all()
                c.main_menu = sorted(portal_menu + all_menu,
                                     key=lambda menu: menu.weight)
            if u'REMOTE_USER' in session:
                c.current_user = Session.query(Users).get(
                    session[u'REMOTE_USER'])

            #log.debug(len(c.main_menu))
            #if u'REMOTE_USER' in session:
            #c.current_user = Session.query(Users).get(session[u'REMOTE_USER'])
            #if not environ[u'PATH_INFO'].endswith(u'/'):
            #environ[u'PATH_INFO'] += u'/'
            #url = construct_url(environ)
            #log.debug('PATH_INFO: %s URL: %s' % (environ[u'PATH_INFO'], url))
            #raise HTTPMovedPermanently(url)
            print "*******************", id
            return WSGIController.__call__(self, environ, start_response)
        finally:
            Session.remove()