Esempio n. 1
0
class RootController(BaseController):
   admin = AdminController(model, DBSession, config_type =  TGAdminConfig)

   @expose('libcreat.templates.index')
   def index(self):
      return dict(page = 'index')

   @expose('jsonp')
   def api(self, m='', sid='', **kw):
      if m == '':
          return {
              'info': 'missing api name.',
              'data': {},
              'status': 1
          }
      if sid == '' and m != 'config':
          return {
              'info': 'missing sid.',
              'data': {},
              'status': 10
          }
      # print request.remote_addr
      return api.process_request(m, sid, kw)

   @expose('libcreat.templates.login')
   def login(self, came_from = lurl('/'), failure = None,    login = ''):
    
      if failure is not None:
         if failure == 'user-not-found':
            flash(_('User not found'), 'error')
         elif failure == 'invalid-password':
            flash(_('Invalid Password'), 'error')
            
      login_counter = request.environ.get('repoze.who.logins', 0)
        
      if failure is None and login_counter > 0:
         flash(_('Wrong credentials'), 'warning')
         
      return dict(page = 'login', login_counter = str(login_counter), 
         came_from = came_from, login = login)
   @expose()
    
   def post_login(self, came_from = lurl('/')):
      if not request.identity:
         
         login_counter = request.environ.get('repoze.who.logins', 0) + 1
         redirect('/login', params = dict(came_from = came_from,__logins = login_counter))
        
         userid = request.identity['repoze.who.userid']
         flash(('Welcome back, %s!') % userid)
            
         return HTTPFound(location = came_from)
Esempio n. 2
0
class RootController(BaseController):
    admin = AdminController(algobowl.model, DBSession, config_type=AdminConfig)
    error = ErrorController()
    group = GroupsController()
    competition = CompetitionsController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "algobowl"

    @expose('algobowl.templates.index')
    def index(self):
        """Handle the front-page."""
        return dict(page='index')

    @expose()
    def algobowl(self):
        """Redirect for old route to homepage"""
        redirect(url('/'))

    @expose()
    def login(self):
        if not tg.request.identity:
            who_api = get_api(tg.request.environ)
            return who_api.challenge()
        redirect(url('/'))

    @expose()
    @require(predicates.not_anonymous())
    def logout(self):
        who_api = get_api(tg.request.environ)
        headers = who_api.logout()
        return HTTPFound(headers=headers)

    @expose()
    def post_login(self, came_from=lurl('/')):
        if tg.request.identity:
            user = tg.request.identity['user']
            flash("Welcome, {}!".format(user), 'success')
            u = tg.request.relative_url(str(came_from), to_application=True)
            if not u.startswith(tg.request.application_url):
                flash("Dangerous redirect prevented", "warning")
                redirect('/')
            redirect(u)
        else:
            flash("Login failure", 'error')
            redirect('/')
Esempio n. 3
0
class RootController(BaseController):
    """
    The root controller for the srvreq application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()
    trace = TraceController()

    _settings = SettingsController()
    ocip = OCIPController(_settings)
    xsi = XSIController(_settings)

    def _before(self, *args, **kw):
        tmpl_context.project_name = "srvreq"

    def _settings_form(self, **kw):
        settings = {s.__dict__["name"]: s.__dict__["value"] \
                    for s in DBSession.query(Setting).all()}
        _dict = dict(data=settings,
                     xsp_username=self._settings.get_user_prop("xsp_username"),
                     xsp_password=self._settings.get_user_prop("xsp_password"))
        utils.update_dict(_dict, kw)
        return _dict

    def get_property_value(self, name):
        return self._settings.get_active_user_prop(name)

    def set_property_value(self, name, value):
        return self._settings.set_active_user_prop(name, value)

    @expose('srvreq.templates.settings')
    def _default(self, pagename="Settings", **kw):
        return self._settings_form(**kw)

    @expose('srvreq.templates.settings')
    def settings(self, **kw):
        dict = self._settings_form(**kw)
        dict["page"] = 'settings'
        return dict

    @expose('srvreq.templates.settings')
    def index(self, pagename="Settings", **kw):
        """Handle the front-page."""
        return self._settings_form(**kw)

    @expose('srvreq.templates.about')
    def about(self):
        """Handle the 'about' page."""
        return dict(page='about')

    @expose('srvreq.templates.environ')
    def environ(self):
        """This method showcases TG's access to the wsgi environment."""
        return dict(page='environ', environment=request.environ)

    @expose('srvreq.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(page='data', params=kw)

    @expose('srvreq.templates.index')
    @require(predicates.has_permission('manage', msg=l_('Only for managers')))
    def manage_permission_only(self, **kw):
        """Illustrate how a page for managers only works."""
        return dict(page='managers stuff')

    @expose('srvreq.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('srvreq.templates.login')
    def login(self, came_from=lurl('/'), failure=None, login=''):
        """Start the user login."""
        if failure is not None:
            if failure == 'user-not-found':
                flash(_('User not found'), 'error')
            elif failure == 'invalid-password':
                flash(_('Invalid Password'), 'error')

        login_counter = request.environ.get('repoze.who.logins', 0)
        if failure is None and login_counter > 0:
            flash(_('Wrong credentials'), 'warning')

        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from,
                    login=login)

    @expose()
    def post_login(self, came_from=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        return HTTPFound(location=came_from)
Esempio n. 4
0
class RootController(BaseController):
    """
    The root controller for the myproject application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()

    libreria = LibreriaController()
    reload = ReloadController()
    courses = CoursesController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "myproject"

    @expose('myproject.templates.index')
    def index(self, **kw):
        """Handle the front-page."""

        return dict(page='index')

    @expose('myproject.templates.about')
    def about(self):
        """Handle the 'about' page."""
        return dict(page='about')

    @expose('myproject.templates.environ')
    def environ(self):
        """This method showcases TG's access to the wsgi environment."""
        return dict(page='environ', environment=request.environ)

    @expose('myproject.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(page='data', params=kw)

    @expose('myproject.templates.index')
    @require(predicates.has_permission('manage', msg=l_('Only for managers')))
    def manage_permission_only(self, **kw):
        """Illustrate how a page for managers only works."""
        return dict(page='managers stuff')

    @expose('myproject.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('myproject.templates.login')
    def login(self, came_from=lurl('/'), failure=None, login=''):
        """Start the user login."""
        if failure is not None:
            if failure == 'user-not-found':
                flash(_('User not found'), 'error')
            elif failure == 'invalid-password':
                flash(_('Invalid Password'), 'error')

        login_counter = request.environ.get('repoze.who.logins', 0)
        if failure is None and login_counter > 0:
            flash(_('Wrong credentials'), 'warning')

        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from,
                    login=login)

    @expose()
    def post_login(self, came_from=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        return HTTPFound(location=came_from)

    @expose('myproject.templates.weather')
    def weather(self):
        url = "http://api.openweathermap.org/data/2.5/weather?id=3523272&appid=d0aa2d3106f2aa9e95523348582e2d6c&units=metric&lang=es"
        r = requests.get(url)
        json = r.json()
        temperature = json['main']['temp']
        pressure = json['main']['pressure']
        humidity = json['main']['humidity']
        return dict(temperature=temperature,
                    pressure=pressure,
                    humidity=humidity)

    @expose('myproject.templates.datosweather')
    def datosweather(self):
        url = "http://api.openweathermap.org/data/2.5/weather?id=3523272&appid=d0aa2d3106f2aa9e95523348582e2d6c&units=metric&lang=es"
        r = requests.get(url)
        json = r.json()
        return dict(json=json)

    @expose('myproject.templates.makoconnection.connection')
    def connection(self, **kw):
        tracker = DBSession.query(Tracker).all(
        )  #tracker recibe todos los elementos de la base de datos
        kw['tracker'] = [
        ]  #Declaramos una nueva lista dentro del diccionario kw que tiene por llave 'tracker'
        for item in tracker:  #Iteramos cada elemento que este denro de trecker de la base de datos
            kw['tracker'].append({
                'id': item.id,
                'imei': item.imei,
                'ticket': item.ticket,
                'name': item.name
            })  #agregr diccionarios a la lista kw 'tracker'
        return dict(page='connection', kw=kw)

    @expose('myproject.templates.makoconnection.test')
    def test(self):
        return dict()

    @expose('myproject.templates.makoconnection.telefonica')
    def telefonica(self):
        return dict()

    @expose('json')
    def loadjqgridtelefonica(self, **kw):
        for x, y in kw.items():
            print("{} {}".format(x, y))
        page = kw["page"]
        records = []
        print(page)
        if page == "1":
            totalPages = 2
            selectedpage = 1

            id = "1"
            icc = "2345897458759"
            lifecyclestatus = "life1"
            records.append({'id': id, 'cell': [id, icc, lifecyclestatus]})
            id = "2"
            icc = "3452345235545"
            lifecyclestatus = "life2"
            records.append({'id': id, 'cell': [id, icc, lifecyclestatus]})
            totalRecords = len(records)
            id = "3"
            icc = "323232323233223"
            lifecyclestatus = "life3"
            records.append({'id': id, 'cell': [id, icc, lifecyclestatus]})
            totalRecords = len(records)
            id = "4"
            icc = "2345897458759"
            lifecyclestatus = "life1"
            records.append({'id': id, 'cell': [id, icc, lifecyclestatus]})
            id = "5"
            icc = "3452345235545"
            lifecyclestatus = "life2"
            records.append({'id': id, 'cell': [id, icc, lifecyclestatus]})
            totalRecords = len(records)
        if page == "2":
            totalPages = 2
            selectedpage = 2
            id = "6"
            icc = "323232323233223"
            lifecyclestatus = "life3"
            records.append({'id': id, 'cell': [id, icc, lifecyclestatus]})
        totalRecords = len(records)
        return dict(total=totalPages,
                    page=selectedpage,
                    records=totalRecords,
                    rows=records)

    @expose('myproject.templates.makoconnection.vistasj')
    def vistasj(self):
        return dict()

    @expose('json')
    def loadweather(self, **j):
        url = "http://api.openweathermap.org/data/2.5/weather?id=3523272&appid=d0aa2d3106f2aa9e95523348582e2d6c&units=metric&lang=es"
        r = requests.get(url)
        json = r.json()
        return dict(total=200, page=1, records=500, rows=json['weather'])

    @expose('myproject.templates.makoconnection.vistasj2')
    def vistasj2(self):
        return dict()

    @expose('myproject.templates.jqgrid')
    def jqgrid(self):
        return dict()

    @expose('json')
    def loadTest2(self, **kw):
        filter = []
        return jqgridDataGrabber(Tracker, 'id', filter, kw).loadGrid()

    @expose('json')
    def updateTest2(self, **kw):
        filter = []
        return jqgridDataGrabber(Tracker, 'id', filter, kw).updateGrid()

    @expose('myproject.templates.makoconnection.phonebook')
    def phonebook(self):
        return dict()

    @expose('json')
    def loadPhoneBook(self, **kw):
        filter = []
        return jqgridDataGrabber(PhoneBook, 'id', filter, kw).loadGrid()

    @expose('json')
    def updatePhoneBook(self, **kw):
        filter = []
        return jqgridDataGrabber(PhoneBook, 'id', filter, kw).updateGrid()

    @expose('json')
    def loanTemplate(self, **kw):
        list = []
        loantemplate = render_template(
            {"list": list}, "mako",
            'myproject.templates.makoconnection.loantemplate')
        return dict(loantemplate=loantemplate)

    @expose('json')
    def addLoan(self, **kw):
        phone_id = kw["phone_id"]
        amount = kw["amount"]
        due_date = kw["due_date"]
        query = DBSession.query(PhoneBook).filter_by(id=phone_id).first()
        if query is not None:
            newLoan = Loans()
            newLoan.phone_id = phone_id
            newLoan.amount = amount
            newLoan.due_date = due_date
            query.loans.append(newLoan)
            DBSession.add(newLoan)
            DBSession.flush()
        return dict(ok="ok")

    @expose('json')
    def displayLoanTemplate(self, **kw):
        displayloantemplate = render_template(
            {"loanid": kw['id']}, "mako",
            'myproject.templates.makoconnection.displayloantemplate')
        return dict(displayloantemplate=displayloantemplate)

    @expose('json')
    def loadjqgridloans(self, **kw):
        filter = [('phonebook_id', 'eq', kw['loanid'])]
        return jqgridDataGrabber(Loans, 'id', filter, kw).loadGrid()
Esempio n. 5
0
class RootController(BaseController):
    """
    The root controller for the portal application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()
    events = EventsController()
    bsb = BsbController()
    stations = StationsController()

    @expose('portal.templates.index')
    @expose('portal.templates.m_world')
    @expose('portal.templates.m_bsb')
    def index(self):

        e = model.events.Events()
        event_list = e.getAll()
        geojson = e.getAllGeoJson(8)

        b = model.bsb.BoletimSismico()
        bsb_list = b.getAll()
        geojson_l = b.getAllGeoJson(20)

        return dict(
            page='index',
            filterForm="",
            events=event_list[:8],
            bsb=bsb_list[:20],
            cycle=cycle,
            geojson=geojson,
            geojson_l=geojson_l,
            evt_png=url("/images/event.png"),
            last_evt_png=url("/images/event.png"),
        )

#        """Handle the front-page."""
#        return dict(page='index')

    @expose('portal.templates.waveform')
    def waveform(self):
        """Handle the waveform page."""
        event_list = model.events.Events().getAll()
        return dict(page='waveform', events=event_list)

    @expose('portal.templates.inform')
    def inform(self):
        """Handle the waveform page."""
        return dict(page='inform')

    @expose('portal.templates.download')
    def download(self, *args, **kw):

        import downloadForms as df
        from datetime import datetime

        filter = ""
        dat = {}
        if kw != {}:
            for k, v in kw.iteritems():
                dat[k] = v
                if v != '':
                    if k == "network":
                        filter += " network  %s " % v
                    elif k == "station":
                        filter += " station  %s " % v
                    elif k == "channel":
                        filter += " channel  %s " % v
                    elif k == "onehour":
                        filter += " onehour  %s " % v
                    elif k == "type":
                        filter += " type  %s " % v
                    elif k == "outfile":
                        filter += " outfile  %s " % v
                    elif k == "type":
                        filter += " network  %s " % v
                    elif k == "date_f":
                        filter += " start " + str(
                            datetime.strptime(v, "%d-%m-%Y %H:%M"))
                    elif k == "date_t":
                        filter += " end " + str(
                            datetime.strptime(v, "%d-%m-%Y %H:%M"))

        print dat

        f = df.DownloadForm().req()
        """Handle the waveform page."""
        #        event_list = model.events.Events().getAll()
        return dict(
            page='download',
            downloadForm=f,
            data=dat,
        )

    @expose('portal.templates.data_availability')
    def data_availability(self, **kw):
        d = None
        """return net_station_loc_chan"""
        try:
            con = psycopg2.connect(host="10.110.0.134",
                                   database='seishub',
                                   user='******',
                                   password="******")

            cursor = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
            query = """
                    select network_id, station_id, location_id, channel_id, start_datetime, end_datetime
                    from "/seismology/station"
                    group by network_id, station_id, location_id, channel_id, start_datetime, end_datetime
                    order by network_id, station_id, location_id, channel_id desc, start_datetime, end_datetime
                    """
            cursor.execute(query)

            rows = cursor.fetchall()
            l = []
            old_sta = None
            old_loc = None
            break_sta = False
            break_loc = False
            for r in rows:

                if old_sta != r['station_id']:
                    old_sta = r['station_id']
                    break_sta = True

                    old_loc = r['location_id']
                    break_loc = True
                else:
                    break_sta = False
                    if old_loc != r['location_id']:
                        old_loc = r['location_id']
                        break_loc = True
                    else:
                        break_loc = False

                if r["end_datetime"] == None:
                    r["end_datetime"] = datetime.now()

                if r["end_datetime"] > datetime.now():
                    r["end_datetime"] = datetime.now()

                if r["start_datetime"] >= datetime(2010, 01, 01):
                    show = True
                else:
                    show = False

                l.append(
                    dict(net=r['network_id'],
                         sta=r['station_id'],
                         loc=r['location_id'],
                         cha=r['channel_id'],
                         t0=r['start_datetime'],
                         tf=r['end_datetime'],
                         break_sta=break_sta,
                         break_loc=break_loc,
                         show=show))
            d = l

            con.close()

        except psycopg2.DatabaseError, e:
            print 'Error %s' % e
            pass
Esempio n. 6
0
class RootController(BaseController):

    admin = AdminController(model, DBSession, config_type=TGAdminConfig)
    course = CourseController()
    error = ErrorController()
    summary = SummaryController()
    paper = PaperController()
    student = StudentController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "revsub"
        tmpl_context.version = "1.1.0"

    @expose('revsub.templates.index')
    def login(self, came_from=lurl('/courses')):
        if request.environ.get('repoze.who.identity', None):
            redirect("/course")
        login_counter = request.environ.get('repoze.who.logins', 0)
        if login_counter > 0:
            flash(_('Error! Invalid username or password.'), 'warning')
        return dict(page='index', login_counter=str(login_counter),
                    came_from=came_from)

    #login = index
    @expose()
    def index(self):
        redirect("https://www.eecs.umich.edu/courses/eecs588/")
        #if request.environ.get('repoze.who.identity', None):
        #    redirect("/course")
        #else:
        #    redirect("/login")

    @require(not_anonymous())
    @expose('revsub.templates.myaccount')
    def account(self):
        login = request.environ.get('repoze.who.identity')\
            .get('repoze.who.userid')
        user = DBSession.query(User).filter(User.user_name == login).one() 
        return dict(user=user)

    @expose()
    def _reset_password(self, password1, password2, old_password):
        if password1 != password2:
            redirect("/error")
        if len(password1) > 256 or len(password1) < 6:
            redirect("/error")
        login = request.environ.get('repoze.who.identity')\
            .get('repoze.who.userid')
        user = DBSession.query(User).filter(User.user_name == login).one()
        if not user.validate_password(old_password):
            flash(_('Error! Incorrect original password.'), 'warning')
            redirect('/account')
        user.password = password1
        redirect('/account')

    @expose()
    def post_login(self, came_from=lurl('/course')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                params=dict(came_from=came_from, __logins=login_counter))
        redirect("/course")

    @expose()
    def post_logout(self, came_from=lurl('/login')):
        redirect("/login")
Esempio n. 7
0
class RootController(BaseController):
    """
    The root controller for the telefonica application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "telefonica"

    @expose('telefonica.templates.index')
    def index(self):
        """Handle the front-page."""
        return dict(page='index')
    @expose('telefonica.templates.about')
    def about(self):
        """Handle the 'about' page."""
        return dict(page='about')

    @expose('telefonica.templates.environ')
    def environ(self):
        """This method showcases TG's access to the wsgi environment."""
        return dict(page='environ', environment=request.environ)

    @expose('telefonica.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(page='data', params=kw)
    @expose('telefonica.templates.index')
    @require(predicates.has_permission('manage', msg=l_('Only for managers')))
    def manage_permission_only(self, **kw):
        """Illustrate how a page for managers only works."""
        return dict(page='managers stuff')

    @expose('telefonica.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('telefonica.templates.login')
    def login(self, came_from=lurl('/'), failure=None, login=''):
        """Start the user login."""
        if failure is not None:
            if failure == 'user-not-found':
                flash(_('User not found'), 'error')
            elif failure == 'invalid-password':
                flash(_('Invalid Password'), 'error')

        login_counter = request.environ.get('repoze.who.logins', 0)
        if failure is None and login_counter > 0:
            flash(_('Wrong credentials'), 'warning')

        return dict(page='login', login_counter=str(login_counter),
                    came_from=came_from, login=login)

    @expose()
    def post_login(self, came_from=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        return HTTPFound(location=came_from)


    # NEW

    @expose('telefonica.templates.empty')
    def empty(self):
        """Handle the 'about' page."""
        return dict(page='empty')

    @expose('telefonica.templates.widgets')
    def widgets(self):
        """Handle the 'about' page."""
        return dict(page='empty')

    @expose('telefonica.templates.charts')
    def charts(self):
        """Handle the 'about' page."""
        return dict(page='empty')

    @expose('telefonica.templates.elements')
    def elements(self):
        """Handle the 'about' page."""
        return dict(page='empty')

    @expose('telefonica.templates.panels')
    def panels(self):
        """Handle the 'about' page."""
        return dict(page='empty')

    @expose('telefonica.templates.jqgrid')
    def jqgrid(self):
        """Handle the 'about' page."""
        return dict(page='empty')

    @expose('telefonica.templates.test')
    def test(self):
        """Handle the 'about' page."""
        return dict(page='empty')
class RootController(BaseController):
    """
    The root controller for the WeGotPOP-BE-Example application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "wegotpopbeexample"

    @expose('wegotpopbeexample.templates.index')
    def index(self):
        """Handle the front-page."""
        return dict(page='index')

    @expose('json')
    def artists(self,
                age_min=None,
                age_max=None,
                age_wgt=None,
                loc_lat=None,
                loc_lon=None,
                loc_rad=None,
                loc_wgt=None,
                rate_max=None,
                rate_wgt=None,
                gender=None,
                gender_wgt=None,
                relevance='basic'):
        service = ArtistFileService.ArtistFileService(
            'wegotpopbeexample/controllers/artists.json')

        validated_age = AgeValidation.validate_age(age_min, age_max, age_wgt)
        validated_location = LocationValidation.validate_location(
            loc_lat, loc_lon, loc_rad, loc_wgt)
        validated_rate = RateValidation.validate_rate(rate_max, rate_wgt)
        validated_gender = GenderValidation.validate_gender(gender, gender_wgt)

        # Use service
        artists = service.get_artists()

        strategy = strategy_dict[relevance]
        filtered_artists = strategy().apply(artists, validated_age,
                                            validated_location, validated_rate,
                                            validated_gender)

        return filtered_artists
        # return '{}'

    @expose('wegotpopbeexample.templates.about')
    def about(self):
        """Handle the 'about' page."""
        return dict(page='about')
Esempio n. 9
0
class RootController(BaseController):
    """
    The root controller for the rubrica application.
    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.
    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()

    check = not_anonymous(msg='Solo gli utenti loggati possono accedere')

    def _before(self, *args, **kw):
        tmpl_context.project_name = "rubrica"

    @paginate("data", items_per_page=10)
    @expose('rubrica.templates.standard_index')
    def index(self, **kw):
        """handle index page"""
        if not request.identity:
            redirect('/login')
        data = DBSession.query(Contatto).filter_by(owner=request.identity['user'].user_id)
        ordering = kw.get('ordercol')
        if ordering and ordering[0] == '+':
            data = data.order_by(asc(ordering[1:]))
        elif ordering and ordering[0] == '-':
            data = data.order_by(desc(ordering[1:]))
        return dict(page='index', grid=tabella, data=data)

    @expose('json')
    @require(check)
    def esponi(self):
        """Espone la rubrica in formato JSON"""
        data = DBSession.query(Contatto).filter_by(owner=request.identity['user'].user_id).all()
        return dict(data=data)

    @expose('json')
    @require(check)
    def download(self):
        """Download della rubrica"""
        data = DBSession.query(Contatto).filter_by(owner=request.identity['user'].user_id).all()
        response.content_type = 'applications/json'
        response.headerlist.append(('Content-Disposition', 'attachment;filename=rubrica.json'))
        return dict(data=data)

    @expose('rubrica.templates.submitForm')
    @require(check)
    def add(self, **kw):
        """Aggiunge contatto"""
        return dict(page='add', form=SubmitForm)

    @expose()
    @require(check)
    @validate(SubmitForm, error_handler=add)
    def save(self, **kw):
        """Salva il contatto aggiunto con add"""
        contatto = Contatto(name=kw['nome'], phone=kw['telefono'])
        request.identity['user'].contacts.append(contatto)
        DBSession.add(contatto)
        redirect('/index')

    @expose()
    @require(check)
    @validate({"item_id": validators.Int(not_empty=True)})
    def delete(self, item_id):
        """Elimina contatto"""
        if not DBSession.query(exists().where(Contatto.id == item_id)).scalar():
            flash(_("Il contatto non esiste"))
            redirect('/index')
        if DBSession.query(Contatto).get(item_id) in request.identity['user'].contacts: 
            contatto = DBSession.query(Contatto).get(item_id)
            DBSession.delete(contatto)
            redirect('/index')
        else:
            flash(_("Non puoi eliminare questo contatto"))
            redirect('/index')

    @expose('rubrica.templates.about')
    def about(self):
        """Handle the 'about' page."""
        return dict(page='about')

    @expose('rubrica.templates.environ')
    def environ(self):
        """This method showcases TG's access to the wsgi environment."""
        return dict(page='environ', environment=request.environ)

    @expose('json')
    @expose('rubrica.templates.data')
    def data(self, **kw):
        """
        This method showcases how you can use the same controller
        for a data page and a display page.
        """
        return dict(page='data', params=kw)

    @expose('rubrica.templates.index')
    @require(predicates.has_permission('manage', msg=l_('Only for managers')))
    def manage_permission_only(self, **kw):
        """Illustrate how a page for managers only works."""
        return dict(page='managers stuff')

    @expose('rubrica.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('rubrica.templates.login')
    def login(self, came_from=lurl('/'), failure=None, login=''):
        """Start the user login."""
        if failure is not None:
            if failure == 'user-not-found':
                flash(_('User not found'), 'error')
            elif failure == 'invalid-password':
                flash(_('Invalid Password'), 'error')

        login_counter = request.environ.get('repoze.who.logins', 0)
        if failure is None and login_counter > 0:
            flash(_('Wrong credentials'), 'warning')

        return dict(page='login', login_counter=str(login_counter),
                    came_from=came_from, login=login)

    @expose()
    def post_login(self, came_from=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        return HTTPFound(location=came_from)
Esempio n. 10
0
class RootController(BaseController):
    """
    The root controller for the rocco application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "rocco"

    @expose('rocco.templates.index')
    def index(self):
        """Handle the front-page."""
        return dict(page='index')

    @expose('json')
    def add(self, **kw):
        statistic = model.Statistic()
        statistic.km = kw['km']
        statistic.lng = kw['lng']
        statistic.lat = kw['lat']
        statistic.device_id = kw['device_id']
        DBSession.add(statistic)

    @expose()
    def me(self, device_id):
        query = DBSession.query(func.sum(
            model.Statistic.km)).filter(model.Statistic.device_id == device_id)
        distance = query.scalar()
        return str(round(distance * 1000))

    @expose('rocco.templates.about')
    def about(self):
        """Handle the 'about' page."""
        return dict(page='about')

    @expose('rocco.templates.environ')
    def environ(self):
        """This method showcases TG's access to the wsgi environment."""
        return dict(page='environ', environment=request.environ)

    @expose('rocco.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(page='data', params=kw)

    @expose('rocco.templates.index')
    @require(predicates.has_permission('manage', msg=l_('Only for managers')))
    def manage_permission_only(self, **kw):
        """Illustrate how a page for managers only works."""
        return dict(page='managers stuff')

    @expose('rocco.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('rocco.templates.login')
    def login(self, came_from=lurl('/')):
        """Start the user login."""
        login_counter = request.environ.get('repoze.who.logins', 0)
        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=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)
        redirect(came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        redirect(came_from)
Esempio n. 11
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')
Esempio n. 12
0
class RootController(BaseController):
    """
    The root controller for the tg-sample-contacts application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "tgsamplecontacts"

    @expose('tgsamplecontacts.templates.form_error')
    def form_error(self, **kwargs):
        errors = [{
            e[0]: e[1].args[0]
        } for e in tg.tmpl_context.form_errors.items()]
        values = tg.tmpl_context.form_values

        return dict(errors=errors, values=values)

    @expose('tgsamplecontacts.templates.contacts')
    def index(self):
        """Handle the front-page."""
        user_id = get_user_id()
        contacts = DBSession.query(Contact).filter_by(user_id=user_id).all()
        return dict(page='contacts', contacts=contacts)

    @expose('tgsamplecontacts.templates.new_contact')
    def new_contact(self):
        """render the page with the form for adding a new user"""
        logged = False if get_user_id() is None else True
        return dict(page='New contact', logged=logged)

    @expose()
    @validate(validators=dict({
        'first_name':
        validators.String(max=80, not_empty=True),
        'last_name':
        validators.String(max=80),
        'number':
        validators.Regex(r'^\+?[-0-9 ]{10,20}$', not_empty=True)
    }),
              error_handler=form_error)
    def add_contact(self, first_name, last_name, number):
        contact = Contact()
        contact.first_name = first_name
        contact.last_name = last_name
        user = DBSession.query(User).filter_by(user_id=get_user_id()).one()
        contact.user = user
        n = Number()
        n.number = number
        n.contact = contact

        DBSession.add(n)
        DBSession.add(contact)
        redirect('/')

    @expose()
    def delete_contact(self, contact_id):
        """Deletes a single contact"""
        contact = DBSession.query(Contact).filter_by(id=contact_id).one()
        if contact.user_id == get_user_id():
            DBSession.query(model.Number).filter_by(contact_id=contact.id).\
                    delete()
            DBSession.delete(contact)
        redirect('/')

    @expose('json')
    def export(self):
        contacts = DBSession.query(Contact).\
                filter_by(user_id=get_user_id()).all()
        return {'contacts': contacts, 'user_id': get_user_id()}

    @expose('tgsamplecontacts.templates.login')
    def login(self, came_from=lurl('/'), failure=None, login=''):
        """Start the user login."""
        if failure is not None:
            if failure == 'user-not-found':
                flash(_('User not found'), 'error')
            elif failure == 'invalid-password':
                flash(_('Invalid Password'), 'error')

        login_counter = request.environ.get('repoze.who.logins', 0)
        if failure is None and login_counter > 0:
            flash(_('Wrong credentials'), 'warning')

        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from,
                    login=login)

    @expose()
    def post_login(self, came_from=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        flash(_('Welcome back, %s!') % request.identity['user'].user_name)

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        return HTTPFound(location=came_from)
Esempio n. 13
0
class RootController(BaseController):
    """
    The root controller for the reqaid application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    data = DataStorage()

    error = ErrorController()
    ocip = OCIPController(data)
    xsi = XSIController(data)

    def _before(self, *args, **kw):
        tmpl_context.project_name = ""

    @expose()
    def _default(self, pagename="Settings", **kw):
        redirect('/xsi')

    @expose('reqaid.templates.login')
    def login(self, came_from=lurl('/'), failure=None, login=''):
        """Start the user login."""
        if failure is not None:
            if failure == 'user-not-found':
                flash(_('User not found'), 'error')
            elif failure == 'invalid-password':
                flash(_('Invalid Password'), 'error')

        login_counter = request.environ.get('repoze.who.logins', 0)
        if failure is None and login_counter > 0:
            flash(_('Wrong credentials'), 'warning')

        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from,
                    login=login)

    @expose()
    def post_login(self, came_from=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        try:
            self.data.fetch_user_data()
        except AssertionError as ae:
            log.error("Failed to fetch server data: %s" % ae)
            redirect('/logout_handler')
        except Exception as e:
            log.error("Failed to fetch server data: %s" % e)
            redirect('/logout_handler',
                     params=dict(output="Failed to fetch server data: %s" % e))

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        return HTTPFound(location=came_from)
Esempio n. 14
0
class RootController(BaseController):
    """
    The root controller for the ksweb 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`.

    """
    admin = AdminController(model, None, config_type=TGAdminConfig)
    qa = QaController()
    precondition = PreconditionController()
    category = CategoryController()
    output = OutputController()
    document = DocumentController()
    questionary = QuestionaryController()
    resolve = ResolveController()
    output_plus = OutputPlusController()

    error = ErrorController()

    @expose('ksweb.templates.index')
    def index(self):
        if predicates.has_any_permission('manage', 'lawyer'):
            redirect('/start')
        return dict()

    @expose('ksweb.templates.questionary.index')
    @paginate('entities',
              items_per_page=int(config.get('pagination.items_per_page')))
    def dashboard(self, share_id):
        user = model.User.query.find({'_id': ObjectId(share_id)}).first()

        if not user:
            response.status_code = 403
            flash(_('You are not allowed to operate in this page'))
            return dict()

        entities = model.Questionary.query.find({
            '$or': [{
                '_user': ObjectId(user._id)
            }, {
                '_owner': ObjectId(user._id)
            }]
        }).sort('title')

        return dict(
            page='questionary-index',
            fields={
                'columns_name': [
                    _('Title'),
                    _('Owner'),
                    _('Shared with'),
                    _('Created on'),
                    _('Completion %')
                ],
                'fields_name':
                ['title', '_owner', '_user', 'creation_date', 'completion']
            },
            entities=entities,
            actions=False,
            actions_content=[_('Export')],
            workspace=None,
            show_sidebar=False,
            share_id=share_id)

    @decode_params('json')
    @expose('json')
    def become_editor_from_user(self, **kw):
        user = model.User.query.find({'_id': ObjectId(kw['share_id'])}).first()
        if user and not user.password:
            user.password = kw['password']
            user.user_name = kw['username']
            group = model.Group.query.find({'group_name': 'lawyer'}).first()
            user.groups = [group]
        return dict()

    @expose('ksweb.templates.start')
    @require(
        predicates.has_any_permission('manage',
                                      'lawyer',
                                      msg=l_('Only for admin or lawyer')))
    def start(self):
        user = request.identity['user']
        categories = model.Category.per_user(user._id)
        return dict(page='index',
                    user=user,
                    workspaces=categories,
                    show_sidebar=False)

    @expose('ksweb.templates.welcome')
    @require(
        predicates.has_any_permission('manage',
                                      'lawyer',
                                      msg=l_('Only for admin or lawyer')))
    def welcome(self, workspace):
        user = request.identity['user']
        ws = model.Category.query.find({'_id': ObjectId(workspace)}).first()
        return dict(page='welcome',
                    user=user,
                    workspace=workspace,
                    ws=ws,
                    show_sidebar=True)

    @expose('ksweb.templates.terms')
    def terms(self):
        return dict()

    @expose('ksweb.templates.privacy')
    def privacy(self):
        return dict()

    @expose('ksweb.templates.legal')
    def legal(self):
        return dict()

    @expose('ksweb.templates.source')
    def source(self):
        return dict()

    @expose('ksweb.templates.login')
    def login(self, came_from=lurl('/'), failure=None, login=''):
        """Start the user login."""
        if failure is not None:
            if failure == 'user-not-found':
                flash(_('User not found'), 'error')
            elif failure == 'invalid-password':
                flash(_('Invalid Password'), 'error')
            elif failure == 'user-created':
                flash(_('User successfully created'))

        login_counter = request.environ.get('repoze.who.logins', 0)
        if failure is None and login_counter > 0:
            flash(_('Wrong credentials'), 'warning')
        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from,
                    login=login)

    @expose()
    def post_login(self, came_from=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        return HTTPFound(location=came_from)
Esempio n. 15
0
class RootController(BaseController):
    """
    The root controller for the ska_calculator application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()

    #movie = MovieController()
    @expose()
    def index(self):
        return "<h1>Hello World</h1>"

    @expose()
    def _default(self, *args, **kw):
        return "This page is not ready"

    @expose("ska_calculator.templates.input")
    def input2(self):
        return {}

    @expose("ska_calculator.templates.sample")
    def output(self, **kw):
        current_time = time.strftime('%Y%m%d%H%M%S')
        # read the pre-defined ska parameters
        parameter_file = 'ska_calculator/data/ska_parameters.par'
        ska_par = read_parameters(parameter_file)
        # check whether input is valid
        check, message = cs.check_input(kw, ska_par)
        if check == 'Fail':
            return message
        else:
            # generate the uv file
            cs.make_uv(kw, current_time, ska_par)
            # generate the noise image and psf
            cs.make_image(kw, current_time, ska_par)
            # make a png plot of the psf
            # make a directory for the output:
            #public_dir = 'ska_calculator/public/data/' + current_time + '/'
            #os.system('mkdir ' +  public_dir)
            cs.plot_psf(kw, current_time)
            cs.plot_noise(kw, current_time)
            # plot the visibilities:
            # the fucntion below is disabled, it is working, however miriad has a memory limit which becomes problematic for LOW where the number of baselines exceeds teh limit to plot every point

            #cs.plot_uv(kw,current_time, ska_par)
            # generate some results
            #current_time4 = time.strftime('%Y%m%d%H%M%S')
            mydata = cs.ska_sens(kw, current_time)
            # clean the temporary data:
            os.system('rm -rf /tmp/ska_calculator/data/runs/' + current_time)
            return mydata
Esempio n. 16
0
class RootController(BaseController):
    """
    The root controller for the tg2express application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)
    error = ErrorController()

    writer = ExpressController(
        model=model.Writer, dbsession=DBSession,
        allow_only=None)  # predicates.has_permission('administration'))
    article = ExpressController(model=model.Article,
                                dbsession=DBSession,
                                allow_only=None)  # predicates.not_anonymous())
    comment = ExpressController(model=model.Comment,
                                dbsession=DBSession,
                                allow_only=None)

    def _before(self, *args, **kw):
        #logger.info("config: %s", config['tg.app_globals'].sa_engine)
        logger.info("args: %s", args)
        logger.info("kw: %s", kw)
        tmpl_context.project_name = "tg2express"

    @expose('tg2express.templates.index')
    def index(self):
        """Handle the front-page."""
        return dict(page='index')

    @expose('tg2express.templates.about')
    def about(self):
        """Handle the 'about' page."""
        return dict(page='about')

    @expose('tg2express.templates.environ')
    def environ(self):
        """This method showcases TG's access to the wsgi environment."""
        return dict(page='environ', environment=request.environ)

    @expose('tg2express.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(page='data', params=kw)

    @expose('tg2express.templates.index')
    @require(predicates.has_permission('manage', msg=l_('Only for managers')))
    def manage_permission_only(self, **kw):
        """Illustrate how a page for managers only works."""
        return dict(page='managers stuff')

    @expose('tg2express.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('tg2express.templates.login')
    def login(self, came_from=lurl('/')):
        """Start the user login."""
        login_counter = request.environ.get('repoze.who.logins', 0)
        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=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)
        redirect(came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        redirect(came_from)
Esempio n. 17
0
class RootController(BaseController):
    """
    The root controller for the contacts application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)
    # Added ContactController for the /contacts route
    contacts = AdminController.make_controller(
        CustomCrudConfig(ContactController.model), DBSession)
    # Added ResetPasswordController
    reset_password = ResetRequestController()

    error = ErrorController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "contacts"

    @expose('contacts.templates.index')
    def index(self):
        """Handle the front-page."""
        return dict(page='index')

    @expose('contacts.templates.environ')
    def environ(self):
        """This method showcases TG's access to the wsgi environment."""
        return dict(page='environ', environment=request.environ)

    @expose('contacts.templates.login')
    def login(self, came_from=lurl('/'), failure=None, login=''):
        """Start the user login."""
        if failure is not None:
            if failure == 'user-not-found':
                flash(_('User not found'), 'error')
            elif failure == 'invalid-password':
                flash(_('Invalid Password'), 'error')

        login_counter = request.environ.get('repoze.who.logins', 0)
        if failure is None and login_counter > 0:
            flash(_('Wrong credentials'), 'warning')

        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from,
                    login=login)

    @expose()
    def post_login(self, came_from=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        return HTTPFound(location=came_from)
Esempio n. 18
0
File: root.py Progetto: nomed/rnms
class RootController(BaseController):
    """
    The root controller for the RoseNMS application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=MyAdminConfig)
    admin.allow_only = predicates.has_permission('manage')

    error = ErrorController()

    """ RoseNMS Specific controllers below """
    attributes = AttributesController()
    events = EventsController()
    graphs = GraphController()
    hosts = HostsController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "rnms"

    @expose('rnms.templates.index')
    @require(predicates.not_anonymous())
    def index(self):
        """Handle the front-page."""
        statrows = get_overall_statistics()

        class EventChartPanel(PanelTile):
            title = "Events in last 24 hours"
            fullwidth = True

            class EventChart(LineChart):
                data_url = url('/events/hourly.json')
                show_legend = True

        class AttributeHBarPanel(PanelTile):
            title = "Attribute Status"

            class TestGraph(HBarAttributeStatus):
                pass

        class DoughnutPanel(PanelTile):
            title = 'Attribute State Graph'

            class TestDoughnut(AttributeStateDoughnut):
                pass

        class StatusPanel(PanelTile):
            title = 'Rose NMS Status'

            class MyDaemonStatus(DaemonStatus):
                pass

        return dict(page='index',
                    att_hbar=AttributeHBarPanel(),
                    eventchart_panel=EventChartPanel(),
                    doughnut=DoughnutPanel(),
                    status_panel=StatusPanel(),
                    statrows=statrows)

    @expose('rnms.templates.full_page')
    def about(self):
        """Handle the 'about' page."""
        from rnms.widgets.base import Text

        class AboutTile(PanelTile):
            fullheight = True
            fullwidth = True
            title = 'About Rose NMS'

            class AboutText(Text):
                template = 'rnms.templates.about_text'

        return dict(page_title='About Rose NMS', page_tile=AboutTile())

    @expose('rnms.templates.environ')
    def environ(self):
        """This method showcases TG's access to the wsgi environment."""
        return dict(page='environ', environment=request.environ)

    @expose('rnms.templates.login')
    def login(self, came_from=lurl('/')):
        """Start the user login."""
        login_counter = request.environ.get('repoze.who.logins', 0)
        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=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)
        if predicates.has_permission('manage'):
            redirect(came_from)
        else:
            redirect(lurl('/graphs/'))

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        redirect(came_from)

    @expose('rnms.templates.full_page')
    @require(predicates.not_anonymous())
    def profile(self):
        """
        Show the users own profile
        """
        class ProfileTile(PanelTile):
            title = 'Profile'
            fullwidth = True

            class MyProfile(ProfileForm):
                pass

        return dict(page='profile', page_title='profile',
                    page_tile=ProfileTile())

    @expose('rnms.templates.widgets.select')
    def attribute_client_option(self):
        """ Show option list of all users who own attributes """
        users = DBSession.query(
            model.User.user_id,
            model.User.display_name).join(model.Attribute).distinct()
        items = users.all()
        items.insert(0, ('', '-- Choose Client --'))
        return dict(items=items)
Esempio n. 19
0
class RootController(BaseController):
    """
    The root controller for the SAUCE 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`.

    """
    admin = AdminController(model, DBSession, SAUCEAdminConfig)

    error = ErrorController()

    # OUR CONTROLLERS
    #assignments = AssignmentsController()
    submissions = SubmissionsController()
    events = EventsController()
    #scores = ScoresController()
    user = UserController()
    languages = LanguagesController()

    debug = DebugController()

    @expose('sauce.templates.index')
    def index(self):
        """Handle the front-page."""
        return dict(page='index')

    @expose('sauce.templates.about')
    def about(self):
        c.side_menu = c.doc_menu
        return dict(page='about')

    @expose('sauce.templates.page')
    def docs(self, arg=''):
        page_title = u'SAUCE Documentation'
        page_header = u''

        if arg:
            try:
                f = open(os.path.join(g.loc, 'docs', arg + '.rst'))
            except IOError:
                abort(404)
            else:
                content = publish_string(f.read(), writer_name='html',
                    settings_overrides={'output_encoding': 'unicode'})
                page_title += ' - %s' % arg.capitalize()
        else:
            page_header = u'SAUCE Documentation'
            content = u'<p>In the menu on the left, you find all kinds of documentation about <b>SAUCE</b>.</p>'

        c.side_menu = c.doc_menu

        return dict(page='docs', page_title=page_title, page_header=page_header, content=content)

    @expose('sauce.templates.contact')
    def contact(self):
        return dict(page='contact')

    @expose('sauce.templates.news')
    @paginate('news', max_items_per_page=65535)
    def news(self):
        '''NewsItem listing page'''
        news_query = NewsItem.query.filter(NewsItem.event_id == None)

        if 'manage' not in request.permissions and \
                request.user not in (chain(e.teachers for e in Event.query)):
            news_query = news_query.filter_by(public=True)

        return dict(page='news', news=news_query)

    @expose('sauce.templates.login')
    def login(self, came_from=lurl('/')):
        """Start the user login."""
        if request.environ.get('repoze.who.identity', None):
            # Already authenticated through external means or by manual URL access
            # Clear flash message cookie
            flash.pop_payload()
            redirect(came_from)
        login_counter = request.environ.get('repoze.who.logins', 0)
        if login_counter > 0:
            flash(_('Wrong credentials'), 'warning')
        return dict(page='login', login_counter=unicode(login_counter),
                    came_from=came_from)

    @expose()
    def post_login(self, came_from=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                params=dict(came_from=came_from, __logins=login_counter))
        user = request.user
        flash(_('Welcome back, %s!') % user.display_name)
        redirect(came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        redirect(came_from)
Esempio n. 20
0
class RootController(BaseController):
    admin = AdminController(model, None, config_type=TGAdminConfig)
    qa = QaController()
    precondition = PreconditionController()
    workspace = WorkspaceController()
    output = OutputController()
    document = DocumentController()
    questionary = FormController()
    resolve = ResolveController()
    output_plus = OutputPlusController()

    error = ErrorController()

    @expose('ksweb.templates.index')
    def index(self):
        if predicates.has_any_permission('manage', 'lawyer'):
            redirect('/start')
        return dict()

    @expose('ksweb.templates.questionary.index')
    @paginate('entities',
              items_per_page=int(config.get('pagination.items_per_page')))
    def dashboard(self, share_id):
        user = model.User.query.find({'_id': ObjectId(share_id)}).first()

        if not user:
            response.status_code = 403
            flash(_('You are not allowed to operate in this page'))
            redirect('/start')

        entities = model.Questionary.query.find({
            '$or': [{
                '_user': ObjectId(user._id)
            }, {
                '_owner': ObjectId(user._id)
            }]
        }).sort('title')

        if not entities.count():
            flash(
                _('You don\'t have any form associated to %s' %
                  user.email_address))
            redirect('/start')

        auth_force_login(user.user_name)
        return dict(
            page='questionary-index',
            fields={
                'columns_name': [
                    _('Title'),
                    _('Owner'),
                    _('Shared with'),
                    _('Created on'),
                    _('Completion %')
                ],
                'fields_name':
                ['title', '_owner', '_user', 'creation_date', 'completion']
            },
            entities=entities,
            actions=False,
            actions_content=[_('Export')],
            workspace=None,
            show_sidebar=False,
            share_id=share_id)

    @decode_params('json')
    @expose('json')
    def become_editor_from_user(self, **kw):
        user = model.User.query.find({'_id': ObjectId(kw['share_id'])}).first()
        if user and not user.password:
            user.password = kw['password']
            user.user_name = kw['username']
            group = model.Group.query.find({'group_name': 'lawyer'}).first()
            user.groups = [group]
        return dict()

    @expose('ksweb.templates.start')
    @require(
        predicates.has_any_permission('manage',
                                      'lawyer',
                                      msg=l_('Only for admin or lawyer')))
    def start(self):
        user = request.identity['user']
        categories = model.Workspace.per_user(user._id)
        return dict(page='index',
                    user=user,
                    workspaces=categories,
                    show_sidebar=False)

    @expose('ksweb.templates.welcome')
    @require(
        predicates.has_any_permission('manage',
                                      'lawyer',
                                      msg=l_('Only for admin or lawyer')))
    @validate({'workspace': Convert(ObjectId, 'must be a valid ObjectId')},
              error_handler=ksweb_error_handler)
    def welcome(self, workspace):
        user = request.identity['user']
        ws = model.Workspace.query.find({'_id': ObjectId(workspace)}).first()
        return dict(page='welcome',
                    user=user,
                    workspace=workspace,
                    ws=ws,
                    show_sidebar=True)

    @expose('json')
    @require(
        predicates.has_any_permission('manage',
                                      'lawyer',
                                      msg=l_('Only for admin or lawyer')))
    def entity(self, _id):
        entity = entity_from_hash(_id)
        if not entity:
            entity = entity_from_id(_id)
        if entity:
            redirect(entity.url)

        abort(404)

    @expose('ksweb.templates.terms')
    def terms(self):
        return dict()

    @expose('ksweb.templates.privacy')
    def privacy(self):
        return dict()

    @expose('ksweb.templates.legal')
    def legal(self):
        return dict()

    @expose('ksweb.templates.source')
    def source(self):
        return dict()

    @expose('ksweb.templates.login')
    def login(self, came_from=lurl('/'), failure=None, login=''):
        if failure is not None:
            if failure == 'user-not-found':
                flash(_('User not found'), 'error')
            elif failure == 'invalid-password':
                flash(_('Invalid Password'), 'error')
            elif failure == 'user-created':
                flash(_('User successfully created'))

        login_counter = request.environ.get('repoze.who.logins', 0)
        if failure is None and login_counter > 0:
            flash(_('Wrong credentials'), 'warning')
        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from,
                    login=login)

    @expose()
    def post_login(self, came_from=lurl('/')):
        if not request.identity:
            login_counter = request.environ.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        flash(_('We hope to see you soon!'))
        return HTTPFound(location=came_from)
Esempio n. 21
0
class RootController(BaseController):
    """
    The root controller for the jistdocstore application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBS_ContractData, config_type=TGAdminConfig)

    mngntcont = ManagementController()
    topmngntcont = TopManagementController()
    labourcont = LabourController()
    logisticscont = LogisticsController()
    marketingcont = MarketingController()
    productioncont = ProductionController()
    contractscont = ContractsController()
    estimatingcont = EstimatingController()
    vettingcont = VettingController()
    manufacturecont = ManufacturingController()
    transportcont = TransportController()
    fleetcont = FleetController()
    accountscont = AccountsController()
    invoicingcont = InvoicingController()
    receptioncont = ReceptionController()
    cctvcont = CCTVController()
    est5yreskomfencingcont = Estimating_5yr_Eskom_Fencing_Controller()
    est3yresspalisadecont = Estimating_3yr_Ess_Palisade_Controller()
    est3yresshsfcont = Estimating_3yr_Ess_HSF_Controller()

    error = ErrorController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "Jistdocstore"

    @expose('jistdocstore.templates.index')
    def index(self):
        """Handle the front-page."""
        redirect('/myjistconsole')
        #return dict(page='index')

    @require(
        in_any_group("managers", "production", "marketing", "healthsafety",
                     "logistics", "stores", "estimates"))
    @expose('jistdocstore.templates.myjistconsole')
    def myjistconsole(self, **named):
        """Handle the 'myjistconsole'."""
        username = request.identity['repoze.who.userid']
        usernow = User.by_user_name(username)
        myid = usernow.user_id

        activeusers = DBS_ContractData.query(User).filter(
            User.active_status == 1).all()

        contracts = DBS_ContractData.query(JistContracts).filter(JistContracts.completed=="False"). \
               order_by(desc(JistContracts.jno)).all()
        pointlist = []
        productionlist = []
        accountslist = []
        for point in activeusers:
            if point:
                if point.user_id == 1:
                    pointlist.append({
                        'user_id': point.user_id,
                        'user_name': point.user_name,
                        'display_name': point.display_name
                    })
                user = User.by_user_id(point.user_id)
                userpermissions = user.permissions
                for permis in userpermissions:
                    #print permis.permission_name
                    if permis.permission_name == 'productionmanage':
                        pointlist.append({
                            'user_id': point.user_id,
                            'user_name': point.user_name,
                            'display_name': point.display_name
                        })

        return dict(page='My JIST Console',
                    contracts=contracts,
                    users=activeusers,
                    myjistid=myid,
                    points=pointlist)

    @require(
        in_any_group("managers", "production", "marketing", "healthsafety",
                     "logistics", "stores", "estimates"))
    @expose('jistdocstore.templates.mypoints')
    def mypoints(self, **named):
        """Handle the 'mypoints' page."""
        tmpl_context.widget = spx_contracts_table
        value = mycontracts_filler.get_value(values={},
                                             offset=0,
                                             order_by='jno',
                                             desc=True)
        count = len(value)
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            value,
            page,
            item_count=count,
            items_per_page=15,
        )
        items = currentPage.items
        #print currentPage
        #print currentPage.page
        #print currentPage.previous_page
        return dict(page='myjist',
                    wip=items,
                    thiscurrentPage=currentPage,
                    count=count)

    @require(
        in_any_group("managers", "production", "marketing", "healthsafety",
                     "logistics", "stores", "estimates"))
    @expose('jistdocstore.templates.mysiteagentspages')
    def my_site_agent_contracts(self, **named):
        """Handle the 'site_agent_contracts' page."""
        tmpl_context.widget = spx_contracts_table
        value = contracts_siteagent_filler.get_value(values={},
                                                     offset=0,
                                                     order_by='jno',
                                                     desc=True)
        count = len(value)
        page = int(named.get('page', '1'))
        currentPage = paginate.Page(
            value,
            page,
            item_count=count,
            items_per_page=15,
        )
        items = currentPage.items
        #print currentPage
        #print currentPage.page
        #print currentPage.previous_page
        return dict(page='myjist',
                    wip=items,
                    thiscurrentPage=currentPage,
                    count=count)

    @require(
        in_any_group("managers", "production", "marketing", "healthsafety",
                     "logistics", "stores", "estimates"))
    @expose('jistdocstore.templates.myjistpages')
    def myjist(self, **named):
        """Handle the 'myjistpages'."""
        return dict(page='My JIST Main Menu')

    #################################################################################
    #############Boiler Plate Code Starts############################################

    @expose('jistdocstore.templates.about')
    def about(self):
        """Handle the 'about' page."""
        return dict(page='about')

    @expose('jistdocstore.templates.environ')
    def environ(self):
        """This method showcases TG's access to the wsgi environment."""
        return dict(page='environ', environment=request.environ)

    @expose('jistdocstore.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(page='data', params=kw)

    @expose('jistdocstore.templates.index')
    #@require(predicates.has_permission('manage', msg=l_('Only for managers')))
    def manage_permission_only(self, **kw):
        """Illustrate how a page for managers only works."""
        return dict(page='managers stuff')

    @expose('jistdocstore.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('jistdocstore.templates.login')
    def login(self, came_from=lurl('/')):
        """Start the user login."""
        login_counter = request.environ.get('repoze.who.logins', 0)
        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=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)
        redirect(came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        redirect(came_from)
Esempio n. 22
0
class RootController(BaseController):
    """
    The root controller for the contatti application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()

    @expose("contatti.templates.registration")
    def registration(self, username=None, email=None, password=None):
        if username is None and email is None and password is None:
            return dict(page="registration")
        else:
            DBSession.add(
                User(user_name=username,
                     email_address=email,
                     password=password))
            redirect("/login")

    @expose("contatti.templates.contacts")
    def contacts(self):
        if request.identity:
            current_user = User.by_email_address(
                request.identity['repoze.who.userid'])
            contacts = DBSession.query(PhoneBook).filter(
                PhoneBook.id_user == current_user.user_id).order_by(
                    PhoneBook.name).all()
            return dict(page="contacts", contacts=contacts)
        else:
            redirect("/login")

    @expose("json")
    def contacts_json(self):
        if request.identity:
            current_user = User.by_email_address(
                request.identity['repoze.who.userid'])
            contacts = DBSession.query(PhoneBook).filter(
                PhoneBook.id_user == current_user.user_id).order_by(
                    PhoneBook.name).all()
            return dict(page="contacts", contacts=contacts)
        else:
            redirect("/login")

    @expose("contatti.templates.add_contact")
    def add_contact(self, id=None, name=None, number=None):
        if request.identity:
            if name is None and number is None:
                return dict(page="add_contact")
            else:
                if id is None:
                    current_user = User.by_email_address(
                        request.identity['repoze.who.userid'])
                    DBSession.add(
                        PhoneBook(id_user=current_user.user_id,
                                  name=name,
                                  number=number))
                else:
                    row = DBSession.query(PhoneBook).filter(
                        PhoneBook.id == id).first()
                    row.name = name
                    row.number = number

                redirect("contacts/")
        else:
            redirect("/login")

    @expose("contatti.templates.modify_contact")
    def modify_contact(self, id=None, name=None, number=None):
        if request.identity:
            if id is not None and name is not None and number is not None:
                return dict(page="modify_contact",
                            id=id,
                            name=name,
                            number=number)
        else:
            redirect("/login")

    @expose()
    def delete_contact(self, id=None):
        if request.identity:
            DBSession.query(PhoneBook).filter(PhoneBook.id == id).delete()
            redirect("/contacts")
        else:
            redirect("/login")

    def _before(self, *args, **kw):
        tmpl_context.project_name = "contatti"

    @expose('contatti.templates.index')
    def index(self):
        """Handle the front-page."""
        return dict(page='index')

    @expose('contatti.templates.about')
    def about(self):
        """Handle the 'about' page."""
        return dict(page='about')

    @expose('contatti.templates.environ')
    def environ(self):
        """This method showcases TG's access to the wsgi environment."""
        return dict(page='environ', environment=request.environ)

    @expose('contatti.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(page='data', params=kw)

    @expose('contatti.templates.index')
    @require(predicates.has_permission('manage', msg=l_('Only for managers')))
    def manage_permission_only(self, **kw):
        """Illustrate how a page for managers only works."""
        return dict(page='managers stuff')

    @expose('contatti.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('contatti.templates.login2')
    def login(self, came_from=lurl('/'), failure=None, login=''):
        """Start the user login."""
        if failure is not None:
            if failure == 'user-not-found':
                flash(_('User not found'), 'error')
            elif failure == 'invalid-password':
                flash(_('Invalid Password'), 'error')

        login_counter = request.environ.get('repoze.who.logins', 0)
        if failure is None and login_counter > 0:
            flash(_('Wrong credentials'), 'warning')

        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from,
                    login=login)

    @expose()
    def post_login(self, came_from=lurl('/contacts')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        return HTTPFound(location="/login")
Esempio n. 23
0
class RootController(BaseController):
    admin = AdminController(model, DBSession, config_type=AdminConfig)

    error = ErrorController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "Parqyng Lots"

    @expose('central.templates.index')
    def index(self):
        """Handle the front-page."""
        lots = DBSession.query(Lot).all()
        return dict(page='index', lots=lots)

    @expose('central.templates.login')
    def login(self, came_from=lurl('/'), failure=None, login=''):
        """Start the user login."""
        if failure is not None:
            if failure == 'user-not-found':
                flash(_('User not found'), 'error')
            elif failure == 'invalid-password':
                flash(_('Invalid Password'), 'error')

        login_counter = request.environ.get('repoze.who.logins', 0)
        if failure is None and login_counter > 0:
            flash(_('Wrong credentials'), 'warning')

        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from,
                    login=login)

    @expose()
    def post_login(self, came_from=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        return HTTPFound(location=came_from)

    @expose('json')
    def register(self, lot=None):
        node = Node(key=random.randint(0, 1 << 31))
        node.lot_id = lot
        DBSession.add(node)
        return {
            'key': node.key,
        }

    @expose('json')
    def report(self):
        if request.method == "POST":
            data = request.json
            key = data['key']
            node = DBSession.query(Node).filter(Node.key == key).first()
            if not node:
                abort(404, "no such node")

            delta = int(data.get('enter') or 0) - int(data.get('exit') or 0)
            if node.lot:
                node.lot.cars += delta
                DBSession.add(node.lot)

            return {}
        else:
            abort(405)

    @expose('json')
    def lots(self):
        return {
            'lots': DBSession.query(Lot).options(joinedload(Lot.nodes)).all()
        }
Esempio n. 24
0
class RootController(BaseController):
    """
    The root controller for the acm-website 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`.

    """
    admin = AdminController(model, DBSession, config_type=AdminConfig)
    mailinglist = MailingListController()
    u = UsersController()
    m = MeetingsController()
    s = SurveysController()
    schedule = ScheduleController()
    error = ErrorController()
    contact = ContactController()
    pages = WikiPagesController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "acmwebsite"

    @expose('acmwebsite.templates.index')
    def index(self):
        """Handle the front-page."""
        meetings = DBSession.query(Meeting).filter(
            Meeting.date > datetime.datetime.now() -
            datetime.timedelta(hours=3)).order_by(Meeting.date).limit(2)
        return dict(page='index', meetings=meetings)

    @expose('acmwebsite.templates.login')
    def login(self, came_from=lurl('/'), failure=None, login=''):
        """Start the user login."""
        if failure is not None:
            if failure == 'user-not-found':
                flash(_('User not found'), 'error')
            elif failure == 'invalid-password':
                flash(_('Invalid Password'), 'error')

        login_counter = request.environ.get('repoze.who.logins', 0)
        if failure is None and login_counter > 0:
            flash(_('Wrong credentials'), 'warning')

        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from,
                    login=login)

    @expose()
    def post_login(self, came_from=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        user = request.identity['user']
        flash(_('Welcome back, %s!') % user.display_name)

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        return HTTPFound(location=came_from)

    @expose()
    def toggle_theme(self):
        if session.get('theme', None) == 'dark':
            session['theme'] = 'light'
        else:
            session['theme'] = 'dark'
        session.save()
        return session.get('theme', None)

    @expose()
    def attend(self):
        meeting = DBSession.query(Meeting)\
                           .join(Meeting.survey)\
                           .filter(
                               Survey.opens < datetime.datetime.now()
                           ).order_by(Meeting.date.desc()).first()

        if meeting and meeting.survey.active:
            redirect('s/{}/respond'.format(meeting.survey.id))
        else:
            abort(404, 'No active meeting')
Esempio n. 25
0
class RootController(BaseController):
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)
    area51 = Area51Controller()

    error = ErrorController()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "onlinelux"

    @expose('onlinelux.templates.index')
    def index(self):
        latest = DBSession.query(Product).order_by(Product.id.desc()).limit(16).all()
        articles = DBSession.query(Article).order_by(Article.id.desc()).limit(2).all()
        top = []
        return dict(
            latest=latest,
            articles=articles,
            top=top,
            title='آنلاین لوکس - خرید بدلیجات',
            description=u'خرید ست، نیم ست، دستبند، گوشواره'
        )

    @expose('onlinelux.templates.product')
    def p(self, id, title):
        product = DBSession.\
            query(Product).\
            options(joinedload('comments.tg_user')).\
            filter(Product.id == id).\
            one_or_none()
        if not product:
            abort(404)

        return dict(
            product=product,
            title=u'آنلاین لوکس - {}'.format(dash_for_space(product.name)),
            description=product.description
        )

    @expose('onlinelux.templates.subcategory')
    def s(self, id, title, **kwargs):
        page = kwargs.get('page') or 1
        offset = (int(page) - 1) * 16
        result = DBSession.\
            query(Product).\
            filter(Product.subcat_id == id).\
            filter(Product.quantity > 0)

        products = result.order_by(Product.price.desc()).offset(offset).limit(16).all()
        return dict(
            total=len(result.all()),
            products=products,
            title=u'آنلاین لوکس محصولات دسته بندی - {}'.format(dash_for_space(title)),
            subcat_title=title,
            subcat_id=id,
            page=page
        )

    @expose('onlinelux.templates.magazine')
    def magazine(self, **kwargs):
        page = kwargs.get('page')
        offset = (page - 1) * 9 if page else 0
        articles = DBSession.\
            query(Article).\
            order_by(Article.id.desc()).\
            offset(offset).\
            all()
        top = DBSession.query(Article).order_by(Article.views.desc()).limit(3).all()
        return dict(articles=articles, top=top, title=u'آنلاین لوکس - مجله')

    @expose('onlinelux.templates.article')
    def a(self, a_id, a_title):
        article = DBSession.query(Article).filter(Article.id == a_id).one_or_none()
        if not article:
            abort(404)
        related = DBSession.\
            query(Article).\
            filter(Article.topic_id == article.topic_id).\
            order_by(Article.id.desc()).\
            limit(5).\
            all()
        article.views = Article.views + 1
        DBSession.flush()
        return dict(
            related=related,
            article=article,
            title=u'مجله آنلاین لوکس - {}'.format(dash_for_space(article.title))
        )

    @expose('onlinelux.templates.subcategory')
    def search(self, query, **kwargs):
        page = kwargs.get('page') or 1
        offset = (int(page) - 1) * 16
        result = DBSession. \
            query(Product). \
            filter(Product.name.contains(query)).\
            filter(Product.quantity > 0)

        products = result.order_by(Product.price.desc()).offset(offset).limit(16).all()
        return dict(
            products=products,
            title=u'آنلاین لوکس - نتایج جستجوی {}'.format(dash_for_space(query)),
            page=page,
            total=len(result.all()),
            query=query
        )

    @expose('onlinelux.templates.purchases')
    def purchases(self):
        purchases = DBSession.query(Purchase).filter(Purchase.user_id == User.current().user_id).all()
        return dict(purchases=purchases, title=u' آنلاین لوکس - سفارشات من')

    @expose('onlinelux.templates.basket')
    def basket(self):
        basket = DBSession.\
            query(Purchase).\
            filter(Purchase.user_id == User.current().user_id).\
            order_by(Purchase.id.desc()).\
            first()
        basket = basket if basket and basket.status == 'Selection' and len(basket.product) > 0 else None
        return dict(basket=basket, title=u'آنلاین لوکس - سبد خرید')

    @expose()
    def remove_from_basket(self, p_id):
        user = User.current()
        basket = DBSession. \
            query(Purchase). \
            filter(Purchase.user_id == user.user_id). \
            order_by(Purchase.id.desc()). \
            first()
        product = DBSession.query(Product).filter(Product.id == p_id).one_or_none()
        if basket and basket.status == 'Selection':
            if product in basket.product:
                basket.product.remove(product)
                tmp = basket.items
                del tmp[str(product.id)]
                basket.items = tmp
                DBSession.flush()
            redirect('/basket')

    @expose('json')
    def add_to_basket(self, p_id):
        user = User.current()
        basket = DBSession. \
            query(Purchase). \
            filter(Purchase.user_id == user.user_id). \
            order_by(Purchase.id.desc()). \
            first()
        product = DBSession.query(Product).filter(Product.id == p_id).one_or_none()
        if product.quantity < 1:
            return dict(ok=False)
        if basket and basket.status == 'Selection':
            if product in basket.product:
                return dict(ok=True)
            elif product not in basket.product:
                basket.product.append(product)
                tmp = basket.items
                tmp[product.id] = 1
                basket.items = tmp
                DBSession.flush()
            return dict(ok=True)
        if not basket or basket.status != 'Selection':
            basket = Purchase(
                user_id=user.user_id,
                items={}
            )
            basket.set_uid()
            basket.product.append(product)
            tmp = basket.items
            tmp[product.id] = 1
            basket.items = tmp
            DBSession.add(basket)
            DBSession.flush()
            return dict(ok=True)

    @expose()
    def change_count(self, product_id, value):
        user = User.current()
        basket = DBSession. \
            query(Purchase). \
            filter(Purchase.user_id == user.user_id). \
            order_by(Purchase.id.desc()). \
            first()
        product = DBSession.query(Product).filter(Product.id == product_id).one_or_none()
        tmp = basket.items
        if value == 'up':
            if int(basket.items.get(str(product.id))) >= int(product.quantity):
                return
            tmp[product_id] += 1
        elif value == 'down':
            if int(basket.items.get(str(product.id))) == 1:
                return
            tmp[product_id] += -1
        basket.items = tmp
        DBSession.flush()
        redirect('/basket')

    @expose('onlinelux.templates.finalize')
    def finalize(self, basket_id):
        user = User.current()
        basket = DBSession. \
            query(Purchase). \
            filter(Purchase.user_id == user.user_id). \
            filter(Purchase.id == basket_id). \
            order_by(Purchase.id.desc()). \
            first()
        if not basket or basket.status != 'Selection':
            redirect('/basket')
        return dict(user=user, basket_id=basket_id, title=u'آنلاین لوکس - تایید نهایی فاکتور {}'.format(basket.uid))

    @expose('json')
    def order_basket(self, **k):
        user = User.current()
        basket = DBSession. \
            query(Purchase). \
            filter(Purchase.user_id == user.user_id). \
            filter(Purchase.id == k.get('basket_id')).\
            order_by(Purchase.id.desc()). \
            first()
        if not basket or basket.status != 'Selection':
            return dict(ok=False, error='Invalid state')

        out_of_stock = False
        for p in basket.product:
            if p.quantity < 1:
                out_of_stock = True
                basket.product.remove(p)
            else:
                p.quantity = Product.quantity - basket.items.get(str(p.id))
        if out_of_stock:
            DBSession.flush()
            return dict(ok=False, error='Invalid state')

        dis_name, address, code, phone = k.get('name'), k.get('address'), k.get('code'), k.get('phone')
        user.display_name = dis_name
        user.postal_address = address
        user.postal_code = code
        user.phone_number = phone
        zp = ZarinpalClient(amount=basket.final_price, basket_uid=basket.uid)
        authority = zp.make()
        payment_url = config.get('payment')
        basket.authority = authority
        basket.status = 'Payment'
        try:
            DBSession.flush()
            return dict(ok=True, paymentUrl=payment_url, authority=authority)
        except IntegrityError:
            return dict(ok=False, error='Invalid state')

    @expose()
    def purchase_callback(self, **kwargs):
        authority = kwargs.get('Authority')
        status = kwargs.get('Status')
        user = User.current()
        if status == 'NOK':
            redirect('/basket')
        elif status == 'OK':
            basket = DBSession. \
                query(Purchase). \
                filter(Purchase.authority == authority). \
                filter(Purchase.user_id == user.user_id). \
                one_or_none()
            if basket and basket.status == 'Payment':
                zp = ZarinpalClient(basket.final_price, basket.uid)
                ref_id, status = zp.verify_payment(authority)
                if ref_id:
                    basket.ref_id = ref_id
                    basket.status = 'Preparing'
                    TelegramNotifier(basket, basket.final_price)
                    DBSession.flush()
                else:
                    redirect('/basket')
            else:
                redirect('/basket')

    @expose()
    def comment(self, **kwargs):
        text = kwargs.get('text')
        product_id = kwargs.get('product_id')
        product_title = kwargs.get('product_title')
        c = Comment(text=text, product_id=product_id, user_id=User.current().user_id)
        DBSession.add(c)
        DBSession.flush()
        redirect('/p/{}/{}'.format(product_id, product_title))

    @expose('onlinelux.templates.login')
    def login(self, came_from=None):
        if request.identity:
            redirect('/')
        return dict(came_from=came_from)

    @expose('onlinelux.templates.register')
    def register(self):
        if request.identity:
            redirect('/')
        return dict()

    @expose()
    def log_out(self):
        session.delete()
        redirect('/logout_handler')

    @expose()
    def post_login(self, came_from=lurl('/')):
        if not request.identity:
            return 'False'
        user = DBSession.query(User).filter(User.user_name == request.remote_user).one_or_none()
        session['user_id'] = user.user_id
        session['user_name'] = user.user_name
        session['display_name'] = user.display_name
        session.save()
        return 'True'

    @expose()
    def post_logout(self, came_from=lurl('/')):
        return HTTPFound(location=came_from)

    @expose('json')
    def register_handler(self, **kwargs):
        username = kwargs.get('username')
        password = kwargs.get('password')
        DBSession.add(User(
            user_name=username,
            password=password
        ))
        try:
            DBSession.flush()
            return dict(ok=True)
        except IntegrityError:
            return dict(ok=False)
Esempio n. 26
0
class RootController(BaseController):
    """
    The root controller for the TrackProblems application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    track = TrackProblemController()
    options = ValueOptionController()
    error = ErrorController()

    utility = Utility()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "trackproblems"

    @expose('trackproblems.templates.index')
    def index(self):

        return dict(page='index')

    @expose('json')
    def searchData(self, *args, **kw):
        print kw
        print args
        print request.body
        if request.body:
            self.df = json.loads(request.body, encoding=request.charset)
        else:
            self.df = []
        print self.df

        listData = []
        if ('project' in self.df and 'problem_type' in self.df):
            projectId = self.df.get('project')
            problemTypeId = self.df.get('problem_type')

            if ('pageSize' in self.df):
                pageSize = self.df.get('pageSize')
            else:
                pageSize = 50
            if ('page' in self.df):
                page = self.df.get('page')
            else:
                page = 0
            self.listData = model.TrackProblem.getListByProjectAndProblemType(
                projectId, problemTypeId, page, pageSize)

            for d in self.listData:
                listData.append(d.to_json())

        return dict(success=True, problem=listData)

    @expose('json')
    def getproblemtype(self, **kw):
        reload(sys)
        sys.setdefaultencoding("utf-8")
        response.content_type = 'application/json'
        response.headers["Access-Control-Allow-Origin"] = '*'
        response.headers["Access-Control-Allow-Headers"] = '*'

        project_id = 0
        security_key = 0
        domain_name = ''
        for data in kw:
            df = json.loads(data)
            domain_name = df.get('domain')
            project_id = df.get('project_id')
            security_key = df.get('security_key')
            print domain_name

        self.trackModule = model.TrackModule.getByIdAndSecureKey(
            project_id, security_key)
        datas = []
        if self.trackModule and self.trackModule.active == 1:

            if (self.trackModule.domain_name in domain_name
                    or self.trackModule.bypass == 1):
                self.problemType = self.trackModule.problemType
                if (self.problemType):
                    for type in self.problemType:
                        datas.append(type.to_json())
            else:
                return dict(status=False,
                            data=datas,
                            message='access denied this domain')
        else:
            return dict(status=False,
                        data=datas,
                        message='access denied this security key or client id')

        return dict(status=True, data=datas, message='')

    @expose(content_type='image/png')
    def getImage(self, **kw):
        reload(sys)
        sys.setdefaultencoding("utf-8")
        image_file = os.path.join(
            'C:/temp/upload/track_feedback/images/27/issue_27.png')
        imageId = kw.get('id')
        trackImage = model.TrackImage.getbyId(imageId)

        if trackImage:
            print trackImage.path_image
            image_file = os.path.join(trackImage.path_image)
            print image_file
            if not os.path.exists(image_file):
                print "Found no %s" % image_file
            else:

                return file(image_file, "rb").read()

        return file(r"c:\temp\upload\track_feedback\images\27\issue_27.png",
                    "rb").read()

    @expose('json')
    def feedback(self, data, **kw):

        reload(sys)
        sys.setdefaultencoding("utf-8")

        try:
            df = json.loads(data, encoding=request.charset)

            #print len(df);
            if (len(df) > 0):
                log.info(df[0])
                self.issue = df[0].get('issue')
                self.type_problem = df[0].get('type_problem')
                self.security_key = df[0].get('security_key')
                self.feedback_url = df[0].get('feedback_url')
                self.from_page = df[0].get('from_page')
                self.project_id = df[0].get('project_id')
                self.domain_name = df[0].get('domain')
                self.user = df[0].get('user')

                #query project
                self.module = model.TrackModule.checkSecureKey(
                    self.project_id, self.security_key)

                #check project_id and security_key is exits
                if (self.module):
                    #check bypass
                    if (self.module.domain_name in self.domain_name
                            or self.module.bypass == 1):
                        self.problem = model.TrackProblem()
                        self.problem.id_track_module = self.project_id
                        self.problem.id_problem_page = self.project_id
                        self.problem.id_problem_type = self.type_problem
                        self.problem.feedback_url = self.feedback_url
                        self.problem.description = self.issue
                        self.problem.user = self.user
                        self.problem.from_page = self.from_page
                        self.problem.save()

                        data = df[1]
                        UPLOAD_DIR = config['path_upload_file']
                        self.file_name = 'issue_' + str(
                            self.problem.id_track_problem) + '.png'
                        self.target_file_name = self.utility.joinPathFileAndCreatePath(
                            UPLOAD_DIR, str(self.problem.id_track_problem),
                            self.file_name)

                        type, b64data = data.split(',')

                        if (self.utility.createFileImageb64data(
                                b64data, self.target_file_name)):
                            self.trackImage = model.TrackImage()
                            self.trackImage.id_track_problem = self.problem.id_track_problem
                            self.trackImage.path_image = self.target_file_name
                            self.trackImage.save()
                        else:
                            log.info('can not create file image')

                    else:
                        #domain is not same
                        log.info('check domain data : ' +
                                 self.module.domain_name +
                                 " is not same with " + self.domain_name)
                        pass
                else:
                    log.info('project : ' + str(self.project_id) +
                             ' or security key : ' + str(self.security_key) +
                             '  is not exits')

        except Exception:
            log.info('project : ' + str(self.project_id) +
                     ' or security key : ' + str(self.security_key) +
                     '  is not exits')
        finally:
            pass

        response.content_type = 'application/json'
        response.headers["Access-Control-Allow-Origin"] = '*'
        response.headers["Access-Control-Allow-Headers"] = '*'

        return dict(success=True)

    @expose('trackproblems.templates.login')
    def login(self, came_from=lurl('/')):
        """Start the user login."""
        login_counter = request.environ.get('repoze.who.logins', 0)
        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=lurl('/')):
        """
        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.get('repoze.who.logins', 0) + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)

    @expose()
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        return HTTPFound(location=came_from)
Esempio n. 27
0
class RootController(BaseController):
    @expose('wiki20.templates.index')
    def index(self, username, password):
        return {
            "hello":
            str("Hello world via template replacement. Username is: " +
                username + " Password is: " + password),
            "page":
            'index'
        }

    """
    The root controller for the Wiki-20 application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()

    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()

    @expose('wiki20.templates.index')
    #def index(self):
    #   """Handle the front-page."""
    #  return dict(hello='=-)',page='index')

    @expose('wiki20.templates.about')
    def about(self):
        """Handle the 'about' page."""
        return dict(page='about')

    @expose('wiki20.templates.environ')
    def environ(self):
        """This method showcases TG's access to the wsgi environment."""
        return dict(environment=request.environ)

    @expose('wiki20.templates.data')
    @expose('json')
    def data(self, **kw):
        """This method showcases how you can use the same controller for a data page and a display page"""
        return dict(params=kw)

    @expose('wiki20.templates.authentication')
    def auth(self):
        """Display some information about auth* on this application."""
        return dict(page='auth')

    @expose('wiki20.templates.index')
    @require(predicates.has_permission('manage', msg=l_('Only for managers')))
    def manage_permission_only(self, **kw):
        """Illustrate how a page for managers only works."""
        return dict(page='managers stuff')

    @expose('wiki20.templates.index')
    @require(predicates.is_user('editor', msg=l_('Only for the editor')))
    def editor_user_only(self, **kw):
        """Illustrate how a page exclusive for the editor works."""
        return dict(page='editor stuff')

    @expose('wiki20.templates.index')
    def hello(self):
        return "Hello world from the controller"

    @expose('wiki20.templates.login')
    def login(self, came_from=url('/')):
        """Start the user login."""
        login_counter = request.environ['repoze.who.logins']
        if login_counter > 0:
            flash(_('Wrong credentials'), 'warning')
        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from)

    @expose()
    def post_login(self, came_from='/'):
        """
        Redirect the user to the initially requested page on successful
        authentication or redirect her back to the login page if login failed.

        """
        if not request.identity:
            login_counter = request.environ['repoze.who.logins'] + 1
            redirect('/login', came_from=came_from, __logins=login_counter)
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)
        redirect(came_from)

    @expose()
    def post_logout(self, came_from=url('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        redirect(came_from)
Esempio n. 28
0
class RootController(BaseController):
    """
    The root controller for the Wiki-20 application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
    secc = SecureController()

    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()

    @expose('wiki20.templates.page')
    def _default(self, pagename="FrontPage"):
        """Handle the front-page."""
        try:
            page = DBSession.query(Page).filter_by(pagename=pagename).one()
        except InvalidRequestError:
            raise redirect("notfound", pagename=pagename)
        content = publish_parts(page.data, writer_name="html")["html_body"]
        root = url('/')
        content = wikiwords.sub(r'<a href="%s\1">\1</a>' % root, content)
        return dict(content=content, wikipage=page)

    @expose("wiki20.templates.edit")
    def notfound(self, pagename):
        page = Page(pagename=pagename, data="")
        DBSession.add(page)
        return dict(wikipage=page)

    @expose(template="wiki20.templates.edit")
    def edit(self, pagename):
        page = DBSession.query(Page).filter_by(pagename=pagename).one()
        return dict(wikipage=page)

    @expose()
    def save(self, pagename, data, submit):
        page = DBSession.query(Page).filter_by(pagename=pagename).one()
        page.data = data
        redirect("/" + pagename)

    @expose("wiki20.templates.pagelist")
    def pagelist(self):
        pages = [
            page.pagename
            for page in DBSession.query(Page).order_by(Page.pagename)
        ]
        return dict(pages=pages)

    @expose('wiki20.templates.about')
    def about(self):
        """Handle the 'about' page."""
        return dict(page='about')

    @expose('wiki20.templates.environ')
    def environ(self):
        """This method showcases TG's access to the wsgi environment."""
        return dict(environment=request.environ)

    @expose('wiki20.templates.data')
    @expose('json')
    def data(self, **kw):
        """This method showcases how you can use the same controller for a data page and a display page"""
        return dict(params=kw)

    @expose('wiki20.templates.authentication')
    def auth(self):
        """Display some information about auth* on this application."""
        return dict(page='auth')

    @expose('wiki20.templates.index')
    @require(predicates.has_permission('manage', msg=l_('Only for managers')))
    def manage_permission_only(self, **kw):
        """Illustrate how a page for managers only works."""
        return dict(page='managers stuff')

    @expose('wiki20.templates.index')
    @require(predicates.is_user('editor', msg=l_('Only for the editor')))
    def editor_user_only(self, **kw):
        """Illustrate how a page exclusive for the editor works."""
        return dict(page='editor stuff')

    @expose('wiki20.templates.login')
    def login(self, came_from=url('/')):
        """Start the user login."""
        login_counter = request.environ['repoze.who.logins']
        if login_counter > 0:
            flash(_('Wrong credentials'), 'warning')
        return dict(page='login',
                    login_counter=str(login_counter),
                    came_from=came_from)

    @expose()
    def post_login(self, came_from='/'):
        """
        Redirect the user to the initially requested page on successful
        authentication or redirect her back to the login page if login failed.

        """
        if not request.identity:
            login_counter = request.environ['repoze.who.logins'] + 1
            redirect('/login',
                     params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)
        redirect(came_from)

    @expose()
    def post_logout(self, came_from=url('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(_('We hope to see you soon!'))
        redirect(came_from)
Esempio n. 29
0
class RootController(BaseController):

    secc = SecureController()
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)

    error = ErrorController()


    def _before(self, *args, **kw):
        tmpl_context.project_name = "licensing_portal"

    #Redirect to login page
    @expose()
    def index(self):
        #If no logged into go to login, else
        redirect('login/')

    #Instructions page
    @expose('licensing_portal.templates.instructions')
    @require(predicates.not_anonymous(msg='Must be logged in.'))
    def instructions(self):
        return dict(page='instructions')

    #Downloads page
    @expose('licensing_portal.templates.downloads')
    @require(predicates.not_anonymous(msg='Must be logged in.'))
    def downloads(self):
        return dict(page='downloads')

    #Serve file for download
    @expose()
    @require(predicates.not_anonymous(msg='Must be logged in.'))
    def serve_file(self, file_path=None, file_name=None):
        import paste.fileapp
        f = paste.fileapp.FileApp('/home/authorityfx/plugin_downloads/' + file_path + file_name, **{'Content-Disposition': 'attachment; filename=' + file_name})
        from tg import use_wsgi_app
        return use_wsgi_app(f)

    #Settings page
    @expose('licensing_portal.templates.settings')
    @require(predicates.not_anonymous(msg='Must be logged in.'))
    def settings(self, **kwargs):
        return dict(page='settings', form=SettingsForm, data=kwargs)

    @expose('licensing_portal.templates.settings')
    @require(predicates.not_anonymous(msg='Must be logged in.'))
    @validate(form=SettingsForm)
    def update_settings_error(self, **kwargs):
        return dict(page='settings', form=SettingsForm, data=kwargs)

    #Update user credentials
    @expose('licensing_portal.templates.settings')
    @require(predicates.not_anonymous(msg='Must be logged in.'))
    @validate(form=SettingsForm, error_handler=update_settings_error)
    def update_settings(self, **kwargs):

        fail = False
        changed = False
        update_password = False
        update_email = False
        msg = ''

        #Get user
        user_name = request.identity['repoze.who.userid']
        user = DBSession.query(model.User).filter(model.User.user_name==user_name).first()

        #Check if current password matches
        if user.validate_password(kwargs['current_password']) == False:
            fail = True
            msg = msg + "  Wrong password!"

        #Update name
        if fail != True and 'name' in kwargs:

            if len(kwargs['name']) > 0:

                #Hash new password
                user.display_name = kwargs['name']
                msg = msg + "  Successfully changed name."
                changed = True

        #Update email
        if fail != True and 'login_email' in kwargs:

            if len(kwargs['login_email']) > 0:

                new_email = kwargs['login_email'].lower()

                count = DBSession.query(model.User).filter(model.User.user_name==new_email).count()

                if count == 0:
                    user.user_name = new_email
                    msg = msg + '  Successfully changed login email.'
                    changed = True
                else:
                    fail = True
                    msg = msg + '  Email address already assigned.'


        #Update passwood
        if fail != True and 'new_password' in kwargs:

            if len(kwargs['new_password']) > 0:

                #Hash new password
                user._set_password(kwargs['new_password'])
                msg = msg + "  Successfully changed password."
                changed = True


        #if no errors write to database
        if fail != True and changed == True:
            DBSession.flush()
            flash(msg.strip())
            redirect('/logout_handler')
        elif fail != True and changed == False:
            flash('No Updates', 'warning')
            return dict(page='settings', form=SettingsForm, data=kwargs)
        else:
            flash(msg.strip(), 'error')
            return dict(page='settings', form=SettingsForm, data=kwargs)


#Admin controllers
#_________________________________________


    def get_admin_panel_data(self, **kwargs):

        user_id_query = DBSession.query(model.User.user_id)

        if 'email_filter' in kwargs:
            if kwargs['email_filter'] != '':
                user_id_query = user_id_query.filter(model.User.user_name==kwargs['email_filter'])
        else:
            kwargs['email_filter'] = ''

        if 'id_filter' in kwargs:
            if kwargs['id_filter'] != '':
                user_id_query = user_id_query.filter(model.User.user_id==kwargs['id_filter'])
        else:
            kwargs['id_filter'] = ''

        if user_id_query.first():
            user_id = user_id_query.first().user_id
        else:
            user_id = 1

        admin_license_data = DBSession.query(model.User, model.License, model.Plugin, model.LicenseType).join(model.License).join(model.Plugin).join(model.LicenseType).filter(model.User.user_id==user_id)

        admin_computer_data = DBSession.query(model.User, model.Computer).join(model.Computer).filter(model.User.user_id==user_id)


        return dict(page='admin_panel', admin_computer_data=admin_computer_data[:10], admin_license_data=admin_license_data, admin_license_grid=admin_license_grid, admin_computer_grid=admin_computer_grid, assign_licences_form=AssignLicensesForm, create_user_form=CreateUserForm, data=kwargs)

    #Admin panel
    @expose('licensing_portal.templates.admin_panel')
    @require(predicates.has_permission('manage'))
    def admin_panel(self, **kwargs):
          return self.get_admin_panel_data(**kwargs)

    #Create user error
    @expose('licensing_portal.templates.admin_panel')
    @require(predicates.has_permission('manage'))
    @validate(form=CreateUserForm)
    def create_user_error(self, **kwargs):
        return self.get_admin_panel_data(**kwargs)

    #Create user
    @expose('licensing_portal.templates.admin_panel')
    @require(predicates.has_permission('manage'))
    @validate(form=CreateUserForm, error_handler=create_user_error)
    def create_user(self, **kwargs):

        name = kwargs['name']
        email = kwargs['login_email'].lower()

        if DBSession.query(model.User).filter(model.User.user_name==email).count() > 0:
            flash(email + ' already exists!', 'error')
            kwargs['login_email']=''
            return self.admin_panel(**kwargs)
            #redirect('/admin_panel', kwargs)

        password = ''.join(random.choice(string.letters + string.digits + string.punctuation) for x in xrange(8))

        u = model.User()
        u.user_name = email
        u.display_name = name
        u.password = password

        licensing_portal_url = "licensing.authorityfx.com"

        subject = "New Authority FX Licensing Portal Account"
        body =    "Dear " + name + ",\n" \
                + "\n" \
                + "Please login into your new Authority FX licensing portal account with the following credentials: \n" \
                + "\n" \
                + licensing_portal_url + "\n" \
                + "\n" \
                + "username: "******"\n" \
                + "password: "******"\n" \
                + "\n" \
                + "We suggest that you change you password upon first login.\n" \
                + "\n" \
                + "Remember that all purchases are added into our licensing portal under the email address provided at checkout.  "\
                + "If you want to make puchases using another email address, please ensure that you change your login email via the " \
                + "settings page prior to making any new purchases.\n" \
                + "\n" \
                + "Thanks!"

        try:
            sender = SendMail()
            sender.send_mail(email, subject, body)
            DBSession.add(u)
            DBSession.flush()
            flash(email + ' added and notified via email.')
        except Exception, e:
            flash(('Could not send new login to ' + name + ", " + email + ": " + str(e)), 'error')

        redirect('/admin_panel')
Esempio n. 30
0
class MyAdminController(BaseController):
    admin = AdminController(model, DBSession, config_type=TGAdminConfig)
    allow_only = in_group('managers')
    tags = TagsController(DBSession)

    @expose('molgears.templates.myadmin.index')
    def index(self):
        """
        Main page for admin controller
        """
        #        userid = request.identity['repoze.who.userid']
        return dict(page='index', pname=None)

    @expose('molgears.templates.myadmin.users')
    def users(self, page=1, *args, **kw):
        """
        Users Managment.
        """
        users = DBSession.query(User)
        page_url = paginate.PageURL_WebOb(request)
        tmpl = ''
        dsc = True
        order = 'user_id'
        if kw:
            if 'desc' in kw and kw['desc'] != u'':
                if kw['desc'] != u'1':
                    dsc = False
            if 'order_by' in kw and kw['order_by'] != u'':
                order = kw['order_by']
        if dsc:
            users = users.order_by(desc(order).nullslast())
        else:
            users = users.order_by((order))

        currentPage = paginate.Page(users,
                                    page,
                                    url=page_url,
                                    items_per_page=30)
        return dict(page='index',
                    currentPage=currentPage,
                    tmpl=tmpl,
                    pname=None)

    @require(
        Any(is_user('manager'),
            has_permission('manage'),
            msg='Permission denied'))
    @expose('molgears.templates.myadmin.new_user')
    def new_user(self, *args, **kw):
        """
        Add new User.
        """
        try:
            come_from = request.headers['Referer']
        except Exception:
            come_from = request.path_url
        groups = DBSession.query(Group).all()
        if kw:
            if 'come_from' in kw and kw['come_from'] != u'':
                come_from = kw['come_from']
            if 'password' in kw and kw['password'] != u'':
                new = kw['password']
                if 'verification' in kw and kw[
                        'verification'] != u'' and new != kw['verification']:
                    flash(l_(u'Password not match'), 'error')
                    redirect(come_from)
                else:
                    flash(l_('Verification error'), 'error')
            else:
                flash(l_(u'Password is required'), 'error')
                redirect(come_from)
            if 'email' in kw and kw['email'] != u'':
                email = kw['email']
            else:
                flash(l_('Email is required'), 'error')
                redirect(come_from)
            if 'items_per_page' in kw and kw['items_per_page'] != u'':
                try:
                    items_per_page = int(kw['items_per_page'])
                except Exception:
                    flash(l_('Compounds per page should be a number'), 'error')
            else:
                flash(l_('Compounds per page required'), 'error')
                redirect(come_from)
            if 'user_name' in kw and kw['user_name'] != u'':
                user = User()
                user.user_name = kw['user_name'].strip().replace(' ', '.')
            else:
                flash(l_('User name is required'), 'error')
                redirect(come_from)
            if 'display_name' in kw and kw['display_name'] != u'':
                user.display_name = kw['display_name']
            if 'groups' in kw and kw['groups'] != u'':
                if isinstance(kw['groups'], basestring):
                    groups = [DBSession.query(Group).get(kw['groups'])]
                else:
                    groups = [
                        DBSession.query(Group).get(group_id)
                        for group_id in kw['groups']
                    ]
            else:
                flash(l_('Group is required'), 'error')
                redirect(come_from)
            if items_per_page:
                if items_per_page > 10 and items_per_page < 150:
                    user.items_per_page = items_per_page
                else:
                    flash(
                        l_(u'Number of Compound per page should be between 10 and 150'
                           ), 'error')
                    redirect(come_from)
            if email:
                import re
                if len(email) >= 6:
                    if re.match(
                            "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$",
                            email) != None:
                        user.email_address = email
                    else:
                        flash(l_(u'Email error'), 'warning')
                        redirect(come_from)
                else:
                    flash(l_(u'Email error'), 'warning')
                    redirect(come_from)
            else:
                flash(l_(u'Email not changed'), 'warning')
            if new:
                if len(new) >= 6:
                    user._set_password(new)
                else:
                    flash(l_(u'Password error'), 'error')
                    redirect(come_from)
            else:
                flash(l_('Password is required'), 'error')
                redirect(come_from)
            if groups:
                for group in groups:
                    group.users.append(user)
            else:
                flash(l_('Gropus error'), 'error')
                redirect(come_from)
            DBSession.add(user)
            DBSession.flush()
            flash(l_(u'Task completed successfully'))
            redirect(come_from)
        return dict(page='index',
                    come_from=come_from,
                    groups=groups,
                    pname=None)

    @require(
        Any(is_user('manager'),
            has_permission('manage'),
            msg='Permission denied'))
    @expose('molgears.templates.myadmin.edit_user')
    def edit_user(self, *args, **kw):
        """
        Edit User record.
        """
        try:
            come_from = request.headers['Referer']
        except Exception:
            come_from = request.path_url
        groups = DBSession.query(Group).order_by('group_id').all()
        try:
            user_id = args[0]
        except Exception:
            redirect("/error")
        user = DBSession.query(User).get(user_id)
        if kw:
            if 'come_from' in kw and kw['come_from'] != u'':
                come_from = kw['come_from']
            if 'password' in kw and kw['password'] != u'':
                new = kw['password']
                if 'verification' in kw and kw[
                        'verification'] != u'' and new != kw['verification']:
                    flash(l_(u'Password not match'), 'error')
                    redirect(come_from)
            else:
                new = None
            if 'email' in kw and kw['email'] != u'':
                email = kw['email']
            else:
                flash(l_('Email is required'), 'error')
                redirect(come_from)
            if 'items_per_page' in kw and kw['items_per_page'] != u'':
                try:
                    items_per_page = int(kw['items_per_page'])
                except Exception:
                    flash(l_('Compounds per page should be a number'), 'error')
            else:
                flash(l_('Compounds per page required'), 'error')
                redirect(come_from)
            if 'user_name' in kw and kw['user_name'] != u'':
                if kw['user_name'] != user.user_name:
                    user.user_name = kw['user_name']
            else:
                flash(l_('User name is required'), 'error')
                redirect(come_from)
            if 'display_name' in kw and kw['display_name'] != u'' and kw[
                    'display_name'] != user.display_name:
                user.display_name = kw['display_name']
            if 'groups' in kw and kw['groups'] != u'':
                if isinstance(kw['groups'], basestring):
                    groups = [DBSession.query(Group).get(kw['groups'])]
                else:
                    groups = [
                        DBSession.query(Group).get(group_id)
                        for group_id in kw['groups']
                    ]
            else:
                flash(l_('Group is required'), 'error')
                redirect(come_from)
            if items_per_page:
                if items_per_page > 10 and items_per_page < 150:
                    if user.items_per_page != items_per_page:
                        user.items_per_page = items_per_page
                else:
                    flash(
                        l_(u'Number of Compound per page should be between 10 and 150'
                           ), 'error')
                    redirect(come_from)
            if email:
                import re
                if len(email) >= 6:
                    if re.match(
                            "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$",
                            email) != None:
                        if email != user.email_address:
                            user.email_address = email
                    else:
                        flash(l_(u'Email error'), 'warning')
                        redirect(come_from)
                else:
                    flash(l_(u'Email error'), 'warning')
                    redirect(come_from)
            if new:
                if len(new) >= 6:
                    user._set_password(new)
                else:
                    flash(l_(u'Password error'), 'error')
                    redirect(come_from)
            if groups:
                for group in groups:
                    if user not in group.users:
                        group.users.append(user)
                for ugroup in user.groups:
                    if ugroup not in groups:
                        ugroup.users.remove(user)
            else:
                flash(l_('Gropus error'), 'error')
                redirect(come_from)
            DBSession.flush()
            flash(l_(u'Task completed successfully'))
            redirect(come_from)
        return dict(page='index',
                    come_from=come_from,
                    groups=groups,
                    user=user,
                    pname=None)

    @require(
        Any(is_user('manager'),
            has_permission('manage'),
            msg='Permission denied'))
    @expose('')
    def delete_user(self, *args, **kw):
        try:
            user_id = args[0]
        except Exception:
            redirect("/error")
        try:
            come_from = request.headers['Referer']
        except Exception:
            come_from = request.path_url
        user = DBSession.query(User).get(user_id)
        if user:
            for group in user.groups:
                group.users.remove(user)
            DBSession.delete(user)
        else:
            flash(l_(u'User error'), 'error')
            redirect(come_from)

        flash(l_(u'Task completed successfully'))
        redirect(come_from)

    @expose('molgears.templates.myadmin.projects')
    def projects(self, page=1, *args, **kw):
        """
        Projects Managment.
        """
        projects = DBSession.query(Projects)
        page_url = paginate.PageURL_WebOb(request)
        tmpl = ''
        dsc = True
        order = 'id'
        if kw:
            if 'desc' in kw and kw['desc'] != u'':
                if kw['desc'] != u'1':
                    dsc = False
            if 'order_by' in kw and kw['order_by'] != u'':
                order = kw['order_by']
        if dsc:
            projects = projects.order_by(desc(order).nullslast())
        else:
            projects = projects.order_by((order))

        currentPage = paginate.Page(projects,
                                    page,
                                    url=page_url,
                                    items_per_page=30)
        return dict(page='index',
                    currentPage=currentPage,
                    tmpl=tmpl,
                    pname=None)

    @expose('molgears.templates.myadmin.new_project')
    @require(
        Any(is_user('manager'),
            has_permission('manage'),
            msg='Permission denied'))
    def new_project(self, *args, **kw):
        """
        Create new project & group with correct permissions asigned.
        If you wish to allow users acces to the project- add them to group named as a project.
        """
        userid = request.identity['repoze.who.userid']
        user = DBSession.query(User).filter_by(user_name=userid).first()
        try:
            come_from = request.headers['Referer']
        except Exception:
            come_from = request.path_url
        if kw:
            if 'come_from' in kw and kw['come_from'] != u'':
                come_from = kw['come_from']
            if 'name' in kw and kw['name'] != u'':
                cell_lines = []
                fp_lines = []
                htrf_lines = []
                for k, v in kw.iteritems():
                    if 'Cell_Line_' in str(k) and v != u'':
                        cell_lines.append(v.strip().replace(' ', '_'))
                    if 'FP_Line_' in str(k) and v != u'':
                        fp_lines.append(v.strip().replace(' ', '_'))
                    if 'HTRF_Line_' in str(k) and v != u'':
                        htrf_lines.append(v.strip().replace(' ', '_'))

                if not cell_lines:
                    flash(l_(u'At least 1 Cell_Line is required'), 'error')
                    redirect(come_from)
                if not fp_lines:
                    flash(l_(u'At least 1 FP_Line is required'), 'error')
                    redirect(come_from)
                if not htrf_lines:
                    flash(l_(u'At least 1 HTRF_Line is required'), 'error')
                    redirect(come_from)
                #create new project:
                project = Projects()
                project.name = kw['name'].strip().replace(' ', '_')
                #add group named as a project:
                gr = Group()
                gr.group_name = kw['name'].strip().replace(' ', '_')
                gr.display_name = kw['name']
                gr.users.append(user)

                #add permission named as a project and assign it to group:
                from molgears.model import Permission
                perm = Permission()
                perm.permission_name = kw['name'].strip().replace(' ', '_')
                perm.groups += [gr]
                #add description:
                if 'description' in kw and kw['description'] != u'':
                    project.description = kw['description']
                #add test and cell lines
                ptest = ProjectTests()
                ptest.name = 'CT'

                fp_ptest = ProjectTests()
                fp_ptest.name = 'FP'
                htrf_ptest = ProjectTests()
                htrf_ptest.name = 'HTRF'
                project.tests = [fp_ptest, ptest, htrf_ptest]
                import pickle
                if cell_lines:
                    pickle_dump1 = pickle.dumps(cell_lines)
                    ptest.cell_line = pickle_dump1
                if fp_lines:
                    pickle_dump2 = pickle.dumps(fp_lines)
                    fp_ptest.cell_line = pickle_dump2
                if htrf_lines:
                    pickle_dump3 = pickle.dumps(htrf_lines)
                    htrf_ptest.cell_line = pickle_dump3
                DBSession.add(perm)
                DBSession.add(gr)
                DBSession.add(ptest)
                DBSession.add(fp_ptest)
                DBSession.add(project)
                DBSession.flush()
                flash(l_(u'Task completed successfully'))
                redirect(come_from)
            else:
                flash(l_(u'Name is required'), 'error')
                redirect(come_from)
        return dict(page='index', userid=userid, come_from=come_from)

    @expose('molgears.templates.myadmin.edit_project')
    @require(
        Any(is_user('manager'),
            has_permission('manage'),
            msg='Permission denied'))
    def edit_project(self, *args, **kw):
        """
        Edit Project.
        If you wish to allow users acces to the project- add them to group named as a project.
        """
        try:
            project_id = args[0]
        except:
            redirect("error")
        userid = request.identity['repoze.who.userid']
        #        user = DBSession.query(User).filter_by(user_name=userid).first()
        try:
            come_from = request.headers['Referer']
        except Exception:
            come_from = request.path_url
        try:
            project = DBSession.query(Projects).get(project_id)
        except:
            flash("Project not exist", "error")
            redirect(come_from)
        if kw:
            if 'come_from' in kw and kw['come_from'] != u'':
                come_from = kw['come_from']
            if 'name' in kw and kw['name'] != u'':
                fp_lines = []
                ct_lines = []
                htrf_lines = []
                for k, v in kw.iteritems():
                    if 'FP_Line_' in str(k) and v != u'':
                        fp_lines.append(v)
                    if 'CT_Line_' in str(k) and v != u'':
                        ct_lines.append(v)
                    if 'HTRF_Line_' in str(k) and v != u'':
                        htrf_lines.append(v)
                if 'CT_Old_Line' in kw and kw['CT_Old_Line'] != u'':
                    if isinstance(kw['CT_Old_Line'], basestring):
                        if kw['CT_Old_Line'] != u'':
                            ct_lines.append(kw['CT_Old_Line'])
                    else:
                        ct_lines += [
                            cell for cell in kw['CT_Old_Line'] if cell != u''
                        ]
                if 'FP_Old_Line' in kw and kw['FP_Old_Line'] != u'':
                    if isinstance(kw['FP_Old_Line'], basestring):
                        if kw['FP_Old_Line'] != u'':
                            fp_lines.append(kw['FP_Old_Line'])
                    else:
                        fp_lines += [
                            cell for cell in kw['FP_Old_Line'] if cell != u''
                        ]
                if 'HTRF_Old_Line' in kw and kw['HTRF_Old_Line'] != u'':
                    if isinstance(kw['HTRF_Old_Line'], basestring):
                        if kw['HTRF_Old_Line'] != u'':
                            htrf_lines.append(kw['HTRF_Old_Line'])
                    else:
                        htrf_lines += [
                            cell for cell in kw['HTRF_Old_Line'] if cell != u''
                        ]
                if not ct_lines:
                    flash(l_(u'At least 1 CT_Line is required'), 'error')
                    redirect(come_from)
                if not fp_lines:
                    flash(l_(u'At least 1 FP_Line is required'), 'error')
                    redirect(come_from)
                if not htrf_lines:
                    flash(l_(u'At least 1 HTRF_Line is required'), 'error')
                    redirect(come_from)
                #edit project name:
                if project.name != kw['name']:

                    #change group name:
                    gr = DBSession.query(Group).filter_by(
                        group_name=project.name).first()
                    gr.group_name = kw['name']
                    gr.display_name = kw['name']

                    #change permission name:
                    perm = DBSession.query(Permission).filter(
                        Permission.permission_name == project.name).first()
                    perm.permission_name = kw['name']

                    project.name = kw['name']
                #add description:
                if 'description' in kw and kw['description'] != u'' and kw[
                        'description'] != project.description:
                    project.description = kw['description']
                #add cell lines
                import pickle
                if ct_lines:
                    pickle_dump1 = pickle.dumps(ct_lines)
                    ct_test = [
                        test for test in project.tests if test.name == 'CT'
                    ][0]
                    ct_test.cell_line = pickle_dump1
                if fp_lines:
                    pickle_dump2 = pickle.dumps(fp_lines)
                    fp_test = [
                        test for test in project.tests if test.name == 'FP'
                    ][0]
                    fp_test.cell_line = pickle_dump2
                if htrf_lines:
                    pickle_dump3 = pickle.dumps(htrf_lines)
                    htrf_test = [
                        test for test in project.tests if test.name == 'HTRF'
                    ][0]
                    htrf_test.cell_line = pickle_dump3

                DBSession.flush()
                flash(l_(u'Task completed successfully'))
                redirect(come_from)
            else:
                flash(l_(u'Name is required'), 'error')
                redirect(come_from)
        return dict(page='index',
                    userid=userid,
                    project=project,
                    come_from=come_from)

    @require(
        Any(is_user('manager'),
            has_permission('manage'),
            msg='Permission denied'))
    @expose('')
    def delete_project(self, *args, **kw):
        try:
            project_id = args[0]
        except Exception:
            redirect("/error")
        try:
            come_from = request.headers['Referer']
        except Exception:
            come_from = request.path_url
        project = DBSession.query(Projects).get(project_id)
        if project:
            DBSession.delete(project)
        else:
            flash(l_(u'Project error'), 'error')
            redirect(come_from)

        flash(l_(u'Task completed successfully'))
        redirect(come_from)