示例#1
0
    def put_delete_undo(self, item_id):
        require_current_user_is_owner(int(item_id))

        item_id = int(item_id)
        content_api = ContentApi(tmpl_context.current_user, True, True) # Here we do not filter deleted items
        item = content_api.get_one(item_id, self._item_type, tmpl_context.workspace)
        try:
            next_url = tg.url('/workspaces/{}/folders/{}/threads/{}').format(tmpl_context.workspace_id,
                                                                             tmpl_context.folder_id,
                                                                             tmpl_context.thread_id)
            msg = _('{} undeleted.').format(self._item_type_label)
            content_api.undelete(item)
            content_api.save(item, ActionDescription.UNDELETION)

            tg.flash(msg, CST.STATUS_OK)
            tg.redirect(next_url)

        except ValueError as e:
            logger.debug(self, 'Exception: {}'.format(e.__str__))
            back_url = tg.url('/workspaces/{}/folders/{}/threads/{}').format(tmpl_context.workspace_id,
                                                                             tmpl_context.folder_id,
                                                                             tmpl_context.thread_id)
            msg = _('{} not un-deleted: {}').format(self._item_type_label, str(e))
            tg.flash(msg, CST.STATUS_ERROR)
            tg.redirect(back_url)
示例#2
0
    def post_login( self, came_from = url( '/' ) ):
        if not request.identity:
            login_counter = request.environ['repoze.who.logins'] + 1
            redirect( url( '/login', came_from = came_from, __logins = login_counter ) )
        userid = request.identity['repoze.who.userid']
#        flash('Welcome back, %s!' % userid)
        redirect( came_from )
示例#3
0
    def put_delete(self, item_id):
        require_current_user_is_owner(int(item_id))

        # TODO - CHECK RIGHTS
        item_id = int(item_id)
        content_api = ContentApi(tmpl_context.current_user)
        item = content_api.get_one(item_id, self._item_type, tmpl_context.workspace)

        try:

            next_url = tg.url('/workspaces/{}/folders/{}/threads/{}').format(tmpl_context.workspace_id,
                                                                             tmpl_context.folder_id,
                                                                             tmpl_context.thread_id)
            undo_url = tg.url('/workspaces/{}/folders/{}/threads/{}/comments/{}/put_delete_undo').format(tmpl_context.workspace_id,
                                                                                                         tmpl_context.folder_id,
                                                                                                         tmpl_context.thread_id,
                                                                                                         item_id)

            msg = _('{} deleted. <a class="alert-link" href="{}">Cancel action</a>').format(self._item_type_label, undo_url)
            content_api.delete(item)
            content_api.save(item, ActionDescription.DELETION)

            tg.flash(msg, CST.STATUS_OK, no_escape=True)
            tg.redirect(next_url)

        except ValueError as e:
            back_url = tg.url('/workspaces/{}/folders/{}/threads/{}').format(tmpl_context.workspace_id,
                                                                             tmpl_context.folder_id,
                                                                             tmpl_context.thread_id)
            msg = _('{} not deleted: {}').format(self._item_type_label, str(e))
            tg.flash(msg, CST.STATUS_ERROR)
            tg.redirect(back_url)
示例#4
0
文件: user.py 项目: jness/dmirr
    def delete(self, user_name=None, *a, **kw):
        u = db.query(model.User).filter_by(user_name=user_name).first()
        admins = db.query(model.Group).filter_by(group_name='dmirr_admin')\
                 .all()

        _display_name = u.display_name
        if not u:
            raise HTTPNotFound
        
        _h.protect_user_obj(u)
        
        came_from = url('/user/%s/edit' % u.user_name)
        
        if u.user_name in admins and len(admins) == 1:
            flash(_("Can not delete the only site administrator."), 'warning')
            redirect(came_from)
            
        confirmed = kw.get('confirmed', None)        
        if not confirmed:
            display_name = u.display_name
            action = url('/user/%s/delete' % u.user_name)
            return dict(errors={}, display_name=display_name, action=action, 
                        came_from=came_from)
        else:
            db.delete(u)
            transaction.commit()
            flash(_("%s and all associated data have been deleted." % \
                    _display_name), 'info')
            redirect(url('/logout_handler'))
示例#5
0
文件: root.py 项目: mbbui/Jminee
    def test_url_sop(self):
        from tg import url

        eq_("/foo", url("/foo"))

        u = url("/foo", bar=1, baz=2)
        assert u in ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"], u
示例#6
0
文件: site.py 项目: jness/dmirr
    def assign_project(self, site_id, *a, **kw):
        errors = _h.get_validation_errors()
        s = DBSession.query(Site).filter_by(id=site_id).first()
        p = DBSession.query(Project).filter_by(id=kw.get('project_id', None))\
            .first()
        all_p = DBSession.query(Project).all()
        
        _h.protect_obj(s)
        _h.protect_obj(p)

        if not s:
            raise HTTPNotFound
        if not p:
            raise HTTPNotFound    
        
        all_projects = [x for x in all_p if x not in s.projects]
        
        if errors:
            transaction.doom()
            return dict(errors=errors, site=s, all_projects=all_projects)

        _s_label = s.label
        s.projects.append(p)

        if kw.get('sync_path', None):
            self._add_site_sync_path(s.id, p.id, kw['sync_path'])
        else:
            transaction.doom()
            flash(_('Site sync path required for each project.'), 'warning')
            redirect(url("/site/%s/edit#mirrored_projects" % _s_label))

        transaction.commit()    
        redirect(url("/site/%s/edit#projects" % _s_label))
示例#7
0
文件: root.py 项目: mbaez/SAP
	def post_logout(self, came_from=url('/')):
		"""
		Redirect the user to the initially requested page on logout and say
		goodbye as well.

		"""
		redirect(url('/login'))
示例#8
0
文件: root.py 项目: mbaez/SAP
	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=url('/proyectos'))
示例#9
0
 def get_one(self, idpds):
     # pylint:disable-msg=C0111,R0201
     idhost = get_parent_id("hosts")
     pds = get_pds(idpds, idhost)
     result = {
             "id": pds.idperfdatasource,
             "href": tg.url("/api/v%s/hosts/%s/perfdatasources/%s"
                    % (self.apiver, pds.host.idhost, pds.idperfdatasource)),
             "host": {
                 "id": pds.host.idhost,
                 "name": pds.host.name,
                 "href": tg.url("/api/v%s/hosts/%s" % (self.apiver, pds.host.idhost)),
                 },
             "name": pds.name,
             "type": pds.type,
             "label": pds.label,
             "factor": pds.factor,
             "max": pds.max,
             }
     graphs = []
     for graph in pds.graphs:
         graphs.append({
             "id": graph.idgraph,
             "href": tg.url("/api/v%s/graphs/%s" % (self.apiver, graph.idgraph)),
             "name": graph.name,
             })
     result["graphs"] = graphs
     return dict(pds=result)
示例#10
0
    def document(self, *args, **kwargs):
        """Render the error document"""
        resp = request.environ.get('pylons.original_response')
        if not resp:
            log.info('ErrorDocument without original_response')
            redirect(url('/'))
        code = request.params.get('code', resp.status_int)
        status = resp.status or code

        req = request.environ.get('pylons.original_request')
        if not req:
            log.info('ErrorDocument without original_request')
            redirect(url('/'))

        log.info('Error %s, Request: %s %s, Referer: %s', status,
            req.method, req.url, req.referer)

        message = messages.get(code, default_message)
        if req.referer:
            message += ('<p><a href="%s" class="btn btn-inverse">'
                '<i class="icon-arrow-left icon-white"></i>'
                '&nbsp;Go back</a></p>' % req.referer)

        values = dict(prefix=request.environ.get('SCRIPT_NAME', ''),
            status=status, code=code,
            message=request.params.get('message', message))
        return values
示例#11
0
 def get_one(self, idhost):
     # pylint:disable-msg=C0111,R0201
     host = get_host(idhost)
     baseurl = tg.url("/api/v%s/hosts/%s" % (self.apiver, host.idhost))
     result = {"id": host.idhost,
               "name": host.name,
               "href": baseurl,
               "description": host.description,
               "address": host.address,
               "status": {
                   "name": host.state.name.statename,
                   "message": host.state.message,
                   "datetime": host.state.timestamp.isoformat(),
                   "order": host.state.name.order,
                   },
               "tags": [t.name for t in host.tags],
               }
     result["lls"] = baseurl+"/lls/"
     result["perfdatasources"] = baseurl+"/perfdatasources/"
     result["graphs"] = baseurl+"/graphs/"
     groups = []
     for group in host.groups:
         groups.append({
             "id": group.idgroup,
             "name": group.name,
             "href": tg.url("/api/v%s/supitemgroups/%s"
                            % (self.apiver, group.idgroup)),
             })
     result["groups"] = groups
     return dict(host=result)
示例#12
0
文件: user.py 项目: jness/dmirr
    def reset_pwd(self, **kw):
        u = DBSession.query(User).filter_by(email_address=kw['e'])\
            .filter_by(verify_code=kw['vc'])\
            .first()
        if not u:
            flash(_('Invalid email address or verification code!'), 'warn')
            redirect(url('/'))

        new_pass = _h.gen_password()
        u.password = new_pass

        # the email           
        msg = turbomail.Message(
            "*****@*****.**",
            u.email_address,
            "Neighbor Farms Password Reset"
            )
        msg.plain = PASSWORD_RESET_MSG % (u.display_name, u.email_address, new_pass, config['base_url'])

        DBSession.flush()
        transaction.commit()
        msg.send()

        flash(_("You're password has been reset, and sent via email."), 'info')
        redirect(url('/login'))
示例#13
0
    def events(self, *args, **kw):
        """Handle the events page."""
        e = model.events.Events()
        event_list = e.getAll()
        geojson = e.getAllGeoJson()
        #geojson_l = e.getLastGeoJson()
        #json_l = e.getLastJson()

        b = model.bsb.BoletimSismico()
        bsb_list = b.getAll()
        geojson_l = b.getLastGeoJson()

        f = ef.EventFilterForm().req()
        bsb_f = bf.BsbFilterForm().req()

        return dict(page='events',
                    filterForm = f,
                    bsbFilterForm = bsb_f,
                    events = event_list,
                    bsb = bsb_list,
                    cycle = cycle,
                    geojson = geojson,
                    geojson_l = geojson_l,
                    evt_png = url("/images/event.png"),
                    last_evt_png = url("/images/star2.png"),
                    )
示例#14
0
 def new_projects(self, **kwargs):
     start_dt = kwargs.pop('start-dt', '')
     end_dt = kwargs.pop('end-dt', '')
     try:
         start_dt = datetime.strptime(start_dt, '%Y/%m/%d %H:%M:%S')
     except ValueError:
         start_dt = datetime.utcnow() + timedelta(days=1)
     try:
         end_dt = datetime.strptime(end_dt, '%Y/%m/%d %H:%M:%S')
     except ValueError:
         end_dt = start_dt - timedelta(days=3) if not end_dt else end_dt
     start = bson.ObjectId.from_datetime(start_dt)
     end = bson.ObjectId.from_datetime(end_dt)
     nb = M.Neighborhood.query.get(name='Users')
     projects = (M.Project.query.find({
         'neighborhood_id': {'$ne': nb._id},
         'deleted': False,
         '_id': {'$lt': start, '$gt': end},
     }).sort('_id', -1))
     step = start_dt - end_dt
     params = request.params.copy()
     params['start-dt'] = (start_dt + step).strftime('%Y/%m/%d %H:%M:%S')
     params['end-dt'] = (end_dt + step).strftime('%Y/%m/%d %H:%M:%S')
     newer_url = tg.url(params=params).lstrip('/')
     params['start-dt'] = (start_dt - step).strftime('%Y/%m/%d %H:%M:%S')
     params['end-dt'] = (end_dt - step).strftime('%Y/%m/%d %H:%M:%S')
     older_url = tg.url(params=params).lstrip('/')
     return {
         'projects': projects,
         'newer_url': newer_url,
         'older_url': older_url,
         'window_start': start_dt,
         'window_end': end_dt,
     }
示例#15
0
    def submit(self, *args, **kwargs):
        '''Create new submission for this assignment'''
        if 'manage' not in request.permissions and \
                request.user not in set(self.event.members) | set(self.event.tutorsandteachers):
            abort(403)
        if (not self.assignment.is_active and
                not request.allowance(self.assignment)):
            flash('This assignment is not active, you may not create a submission', 'warning')
            redirect(url(self.assignment.url))

        submission = Submission(
            assignment=self.assignment,
            filename=self.assignment.submission_filename or None,
            source=self.assignment.submission_template or None,
            language=self.assignment.allowed_languages[0] if self.assignment.allowed_languages else None,
            user=request.user,
            created=datetime.now(),
            modified=datetime.now(),
        )
        DBSession.add(submission)
        try:
            DBSession.flush()
        except SQLAlchemyError:
            DBSession.rollback()
            log.warn('Error creating new submission', exc_info=True)
            flash('Error creating new submission', 'error')
            redirect(url(self.assignment.url))
        else:
            redirect(url(submission.url + '/edit'))
示例#16
0
文件: public.py 项目: bbcf/biorepo
    def extern_create(self, *args, **kw):
        '''
        used to upload a file from another web application
        kw must contain :
        :file_path == file path
        :description == verbose to explain some stuff
        :project_name == name of the external web app
        :sample_name == name of the plugin web app / or another thing
        :sample_type == name of the webapp (and type of analysis if asked)
        kw can contain :
        :project_description == HTSstation project description
        :task_id == task_id for BioScript files from HTSstation/BioScript
        '''
        #test if the essential kw are here
        essential_kws = ["file_path", "description", "project_name", "sample_name", "sample_type"]
        missing_kw = []
        for k in essential_kws:
            if k not in kw.keys():
                missing_kw.append(k)
        if len(missing_kw) > 0:
            flash(str(missing_kw) + " not found in keywords. External application error.", "error")
            raise redirect(url("/"))

        session['backup_kw'] = kw
        session.save()
        #test if the user who was redirected on BioRepo is logged in it
        if not 'repoze.who.identity' in request.environ:
            session['extern_meas'] = True
            session.save()
            raise redirect(url('/login'))

        else:
            raise redirect(url('/measurements/external_add'))
示例#17
0
    def login(self, came_from=url('/')):
        """Start the user login."""
        if session.get('userid') is None and request.identity is not None:
            self.redirect_to(url('/user_logout'))
#        login_counter = request.environ['repoze.who.logins']
#        if login_counter > 0:
#            flash(_('Wrong credentials'), 'warning')
        return dict(page='login',came_from=came_from)
示例#18
0
文件: project.py 项目: ravenoak/VXWeb
 def get(self, proj_id = None):
     if not proj_id:
         redirect(url('/project/list'))
     try:
         proj_id = int(proj_id)
     except ValueError:
         redirect(url('/project/list'))
     return self._r(proj_id)
示例#19
0
文件: auth.py 项目: LamCiuLoeng/jcp
 def default_url(self):
     """Return the default page after user login."""
     search_groups = set(DBSession.query(Group).filter(Group.group_name.in_(['BUYER', 'AE'])).all())
     
     if len(search_groups.intersection(set(self.groups))) > 0:
         return url('/order/search')
     else:
         return url('/order/index')
示例#20
0
文件: root.py 项目: TurboGears/tg2
    def test_url_sop(self):
        from tg import url
        eq_('/foo', url('/foo'))


        u = url("/foo", params=dict(bar=1, baz=2))
        assert u in \
                ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"], u
示例#21
0
    def index(self, *p, **kw):
        if self.wp is None:
            redirect(url('./%s/edit' % self.title))
        content = publish_parts(self.wp.text, writer_name="html")["html_body"]
        root = url('/')
        content = wikiwords.sub(r'<a href="%s\1">\1</a>' % root, content)

        return {'pagetitle': self.wp.title, 'content': content}
示例#22
0
文件: root.py 项目: LamCiuLoeng/vat
 def post_login(self, came_from=url('/')):
     if not request.identity:
         login_counter=request.environ['repoze.who.logins']+1
         redirect(url('/login', came_from=came_from, __logins=login_counter))
     #userid = request.identity['repoze.who.userid']
     #flash('Welcome back, %s!' % userid)
     session['company_code'] = config['company_code']
     session.save()
     redirect(came_from)
示例#23
0
 def prepare(self):
     self.resources.append(c3_min_js)
     self.resources.append(d3_min_js)
     self.resources.append(c3_min_css)
     self.aoption_url = url('/attributes/option')
     self.hoption_url = url('/hosts/option')
     self.coption_url = url('/attribute_client_option')
     self.gtoption_url = url('/graphs/types_option')
     self.atoption_url = url('/attributes/type_option')
示例#24
0
    def index(self):
        """Pagina de inicio, si no esta autenticado todavia!
           redirije a la pagina de login   
        """
	if not request.identity:
        
             redirect(url('/login', came_from=url('/')))
       
        return dict(pagina='index')
示例#25
0
 def extra_actions(self, obj):
     return Button(url('/admin/graphtypelines/',
                       {'graph_type_id': obj.id}),
                   'list', 'info',
                   tooltip='Show Lines') +\
         Button(url('/admin/attributetypetsdbs/',
                    {'attribute_type_id': obj.attribute_type_id}),
                'signal', 'info',
                tooltip='Show TS Data')
示例#26
0
 def login(self, came_from=url('/')):
     if request.identity:
         redirect(url('/'))
     
     login_counter = request.environ['repoze.who.logins']
     if login_counter > 0:
         flash(_('Wrong credentials'), 'warning')
     return dict(login_counter=str(login_counter),
                 came_from=came_from)
示例#27
0
    def index(self):
        """Pagina de inicio, si no esta autenticado todavia!
        redirije a la pagina de login   
        """
        nom_proyecto = Variables.get_valor_by_nombre("nombre_proyecto_actual")
        nom_fase = Variables.get_valor_by_nombre("nombre_fase_actual")

        if not request.identity:
            redirect(url("/login", came_from=url("/")))
        return dict(pagina="index", nom_proyecto=nom_proyecto, nom_fase=nom_fase)
示例#28
0
文件: project.py 项目: ravenoak/VXWeb
 def _c(self, confirmed = False, **kw):
     if confirmed:
         project = Project()
         try:
             DBSession.add(project)
             DBSession.flush()
         except:
             flash(u'Could not add Project: "%s"' % (project.label), 'error')
         flash(u'Added Project: "%s"' % (project.label))
         redirect(url('/project/' + project.id))
     redirect(url('/project/'))
示例#29
0
文件: root.py 项目: mbaez/SAP
	def post_login(self, came_from=url('/')):
		"""
		Redirect the user to the initially requested page on successful
		authentication or redirect her back to the login page if login failed.

		"""
		if not request.identity:
			login_counter = request.environ['repoze.who.logins'] + 1
			redirect(url('/login', came_from=came_from, __logins=login_counter))
		userid = request.identity['repoze.who.userid']
		redirect('/proyectos')
示例#30
0
 def extra_actions(self, obj):
     return Button(
         url('/admin/attributetypefields',
             {'attribute_type_id': obj.id}),
         'list', 'info',
         tooltip='Show Fields for this Attribute Type') +\
         Button(
         url('/admin/attributetypetsdbs',
             {'attribute_type_id': obj.id}),
         'signal', 'info',
         tooltip='Show TS Data for this Attribute Type')
示例#31
0
def plug_url(pluggable_name, path, params=None, lazy=False, qualified=False):
    if not params:
        params = {}

    conditional_options = {}
    if qualified is not False:
        conditional_options['qualified'] = qualified

    if lazy:
        return tg.lurl(DeferredMountPointPath(pluggable_name, path),
                       params=params,
                       **conditional_options)
    else:
        return tg.url(DeferredMountPointPath(pluggable_name, path),
                      params=params,
                      **conditional_options)
示例#32
0
    def update_params(self, d):
        super(GlobalResourceInjectionWidget, self).update_params(d)

        d['base_url'] = url('/')

        if asbool(config.get('debug')):
            d['debug'] = 'true'
        if asbool(config['global_conf'].get('profile')):
            d['profile'] = 'true'

        d['csrf_trusted_domains'] = self.csrf_trusted_domains_hash

        identity = request.environ.get('repoze.who.identity')
        if identity:
            d['csrf_token'] = identity.get(self.csrf_token_id, '')
            d['user_id'] = identity.get('user_id', '')
示例#33
0
    def profile(self, *args, **kwargs):
        '''Profile modifying page'''

        value = request.user
        if config.features.get('externalauth', False):  # pragma: no cover
            value.disable_submit = True
            flash(
                'Profile changes are not possible because external authentication is used!',
                'error')
        else:
            value.disable_submit = False

        c.form = ProfileForm(value=value, action=url('/user/post'))

        return dict(page='user',
                    heading=u'User profile: %s' % request.user.display_name)
示例#34
0
文件: widget.py 项目: decause/moksha
    def prepare(self):
        super(GlobalResourceInjectionWidget, self).prepare()

        self.base_url = url('/')

        if asbool(config.get('debug')):
            self.debug = 'true'
        if asbool(config['global_conf'].get('profile')):
            self.profile = 'true'

        self.csrf_trusted_domains = self.csrf_trusted_domains_hash

        identity = request.environ.get('repoze.who.identity')
        if identity:
            self.csrf_token = identity.get(self.csrf_token_id, '')
            self.user_id = identity.get('user_id', '')
示例#35
0
文件: form.py 项目: puria/ksweb
    def create(self,
               questionary_title=None,
               document_id=None,
               email_to_share=None,
               **kw):
        owner = request.identity["user"]
        if email_to_share:
            user = model.User.by_email_address(email_to_share)

            if not user:
                user = model.User(
                    user_name=email_to_share,
                    email_address=email_to_share,
                    display_name=email_to_share,
                )
        else:
            user = owner

        questionary = model.Questionary(
            title=questionary_title,
            _user=user._id,
            _owner=owner._id,
            _document=ObjectId(document_id),
        )

        if email_to_share:
            from tgext.mailer import get_mailer
            from tgext.mailer import Message

            mailer = get_mailer(request)
            share_url = tg.url("/dashboard",
                               params={"share_id": user._id},
                               qualified=True)
            message = Message(
                subject=_("Invite to a KSWEB document"),
                sender="*****@*****.**",
                recipients=[user.email_address],
                body=_(
                    "Hi, you were invited to compile the following document %s "
                    "at the following url %s" %
                    (questionary_title, share_url)),
            )
            mailer.send_immediately(message)
            flash(
                _("Questionary succesfully created and shared to %s" %
                  email_to_share))
        return dict(questionary=questionary)
示例#36
0
    def reject(self, id, subject=None, body=None, token=None, silent=False):
        t = queue.Ticket.get(int(id))
        if t.state != 'open':
            flash("This ticket's not open!")
            redirect('/ticket/%s' % id)
        if t.rtid is None:
            flash("This ticket has no RT ID!")
            redirect('/ticket/%s' % id)
        if (subject and body) or silent:
            if token != auth.token():
                flash("Invalid token!")
            else:
                # Send mail and records it as an event
                if not silent:
                    mail.send_correspondence(subject, body, t.rtid,
                                             auth.current_user())
                    t.addEvent(type=u'mail',
                               state=u'rejected',
                               target=u'user',
                               subject=subject,
                               body=body)
                    flash("Ticket rejected; mail sent to user.")
                else:
                    mail.send_comment(subject,
                                      "Ticket rejected silently.\n\n" + body,
                                      t.id, t.rtid, auth.current_user())
                    t.addEvent(type=u'mail',
                               state=u'rejected',
                               target=u'rt',
                               subject=subject,
                               body=body)
                    flash("Ticket rejected silently.")
                redirect('/queue')
        return dict(tickets=[t],
                    action=url('/reject/%s' % id),
                    subject="Re: Request for hostname %s" % t.hostname,
                    body="""Hello,

Unfortunately, the hostname %(hostname)s is not available.  You can go to http://pony.scripts.mit.edu/ to request a different one.

Sorry for the inconvenience,
-%(first)s

/set status=rejected
""" % dict(hostname=t.hostname, first=auth.first_name()),
                    submit='Send to %s' % t.requestor,
                    extra_buttons={'silent': 'Send as Comment'})
示例#37
0
    def post(self, *args, **kw):
        # Inject
        kw['teacher'] = request.user
        # Force CrudController.post to return a dict
        request.response_type = 'application/json'
        result = super(EventRequestController, self).post(*args, **kw)
        value = result['value']
        sendmail(u'[SAUCE] Event requested',
                 u'''
A new Event has been requested in SAUCE.
Review the request at %s.
''' % url('/events/request', qualified=True),
                 cc_managers=True)
        flash(
            'Event "%s" successfully requested. Now awaiting administrator approval.'
            % (value.name), 'ok')
        return redirect('/')
示例#38
0
    def ref_order(self, cls, came_from='/'):

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

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

        class_ = SapnsClass.by_name(cls)

        return dict(page='reference order',
                    reference=class_.reference(all=True),
                    came_from=came_from)
示例#39
0
    def post(self, label='', file_data=None):
        # TODO - SECURE THIS
        workspace = tmpl_context.workspace

        api = ContentApi(tmpl_context.current_user)

        file = api.create(ContentType.File, workspace, tmpl_context.folder,
                          label)
        api.update_file_data(file, file_data.filename, file_data.type,
                             file_data.file.read())
        api.save(file, ActionDescription.CREATION)

        tg.flash(_('File created'), CST.STATUS_OK)
        tg.redirect(
            tg.url('/workspaces/{}/folders/{}/files/{}').format(
                tmpl_context.workspace_id, tmpl_context.folder_id,
                file.content_id))
示例#40
0
    def get_title(self):
        current_ordering = request.GET.get('order_by')
        if current_ordering == self.options[
                'sort_field'] and not request.GET.get('desc'):
            desc = 1
        else:
            desc = 0

        new_params = dict(request.GET)
        if desc:
            new_params['desc'] = 1
        else:
            new_params.pop('desc', None)
        new_params['order_by'] = self.options['sort_field']

        return Markup('<a href="%s">%s</a>' % (escape(
            url(request.path_url, params=new_params)), escape(self._title_)))
示例#41
0
文件: trackhub.py 项目: bbcf/biorepo
 def delete(self, *args, **kw):
     th_name = str(args[0])
     user = handler.user.get_user_in_session(request)
     user_lab = session.get("current_lab", None)
     mail = user.email
     mail_tmp = mail.split("@")
     mail_final = mail_tmp[0] + "AT" + mail_tmp[1]
     user_path = trackhubs_path() + "/" + user_lab + "/" + mail_final
     th_path = user_path + "/" + th_name
     try:
         shutil.rmtree(th_path)
         flash("Your trackhub " + th_name + " was deleted.")
     except:
         flash(
             "Error : your trackhub was not deleted. Contact the administrator please.",
             'error')
     raise redirect(url('/trackhubs'))
示例#42
0
 def challenge(self, environ, status, app_headers, forget_headers):
     """
     Provide ``IChallenger`` interface.
     """
     challenger = environ.get('repoze.who.challenge')
     if challenger and challenger != 'mpapi':
         return None
     request = Request(environ)
     return_url = tg.url(request.application_url + '/post_login',
                         {'came_from': request.path_qs})
     headers = [('Location',
                 '{}?{}'.format(self.mpapi_sso,
                                urlencode({'return':
                                           return_url}))), *forget_headers,
                *((h, v)
                  for h, v in app_headers if h.lower() == 'set-cookie')]
     return HTTPFound(headers=headers)
示例#43
0
    def put(self, user_id, name, email, next_url=None):
        user_id = tmpl_context.current_user.user_id
        current_user = tmpl_context.current_user
        assert user_id == current_user.user_id

        # Only keep allowed field update
        updated_fields = self._clean_update_fields({
            'name': name,
            'email': email
        })

        api = UserApi(tmpl_context.current_user)
        api.update(current_user, do_save=True, **updated_fields)
        tg.flash(_('profile updated.'))
        if next_url:
            tg.redirect(tg.url(next_url))
        tg.redirect(self.url())
示例#44
0
    def user_login(self, came_from=url('/'), **kwargs):
        result = None

        try:
            status = self.controller_impl.user_login(kwargs)

            if status.get('success'):
                user = status.get('user')
                result = self.post_login(user, came_from)
                return result
            else:
                msg = status.get('msg')
                return "{success:false,msg:'" + msg.replace("'", " ") + "'}"
        except Exception, e:
            print "Exception: ", e
            import traceback
            traceback.print_exc()
            return "{success:false,msg:'" + str(e).replace("'", " ") + "'}"
示例#45
0
    def put(self, categoryid, name, languageid, description=None):
        """Edit a category"""
        category = DBSession.query(Category).get(categoryid.decode())

        modified = False
        if category.name[languageid] != name:
            category.name[languageid] = name
            modified = True

        if category.description[languageid] != description:
            category.description[languageid] = description
            modified = True

        if modified:
            flash('%s %s' % (_('Updated Category:'), category.id), 'ok')
        else:
            flash('%s %s' % (_('Category is unchanged:'), category.id), 'info')
        return dict(redirect_to=url('/admin/category/'))
示例#46
0
文件: user.py 项目: samsemilia7/SAUCE
    def profile(self, **kwargs):
        '''Profile modifying page'''

        c.form = ProfileForm

        options = request.user
        if config.get('externalauth', False):
            options.disable_submit = True
            flash(
                'Profile changes are not possible because external authentication is used!',
                'error')
        else:
            options.disable_submit = False

        return dict(page='user',
                    heading=u'User profile: %s' % request.user.display_name,
                    options=options,
                    action=url('/user/post'))
示例#47
0
    def revoke_auth_token(self, token_id):
        try:
            token_id = int(token_id)
        except ValueError:
            tg.abort(400, "token_id must be an integer")

        user = tg.request.identity["user"]
        query = model.DBSession.query(
            model.AuthToken).filter(model.AuthToken.id == token_id)
        token = query.one_or_none()

        if not user.admin and token.user_id != user.id:
            tg.abort(403, "You don't have permission to revoke this token")

        client_name = token.client_name
        query.delete()
        model.DBSession.flush()
        tg.flash(f"Client {client_name} revoked!", "success")
        tg.redirect(tg.url("/pref/cli"))
示例#48
0
def get_GViz_link(obj_id):
    '''
    Return a HTML link to Gviz HTSstation
    '''
    meas = DBSession.query(Measurements).filter(
        Measurements.id == obj_id).first()
    status = meas.status_type

    if status and len(meas.fus) > 0:
        list_fus = meas.fus
        for x in list_fus:
            f_sha1 = x.sha1
            ext = x.extension
        if ext.lower() == "bam":
            return '''
            <a class='action GViz_link'  href="%s" target="_blank" title="view in GViz" style="text-decoration:none" target="_blank"></a> ''' % (
                url('./public/Gviz_link',
                    params=dict(sha1=f_sha1, meas_id=obj_id)))
    return ''
示例#49
0
    def stations(self):
        """Handle the events page."""
        #s = model.stations.Stations()

        f = sf.StationFilterForm().req()

        _s = model.stations.Stations()

        stations_list = _s.getAll()
        json = _s.getAllJson()
        return dict(
            page='stations',
            filterForm=f,
            data={},
            stations=stations_list,
            cycle=cycle,
            json=json,
            map_symbol=url("/images") + "/station.png",
        )
示例#50
0
    def toggle_group(self, **kwargs):
        group_id = kwargs.get('group')
        user_id = kwargs.get('user')
        user = model.provider.get_obj(app_model.User,
                                      {get_primary_field('User'): user_id}) or abort(404)
        groups_list = [instance_primary_key(g, True) for g in user.groups]

        if group_id in groups_list:
            groups_list.remove(group_id)
            model.provider.update(app_model.User, {get_primary_field('User'): user_id,
                                                   'groups': groups_list})
        else:
            if config['_pluggable_tgapppermissions_config']['exclusive_permissions']:
                groups_list = [group_id]
            else:
                groups_list.append(group_id)
            model.provider.update(app_model.User, {get_primary_field('User'): user_id,
                                                   'groups': groups_list})
        return redirect(url(self.mount_point + '/users'))
示例#51
0
class ProyectoForm(TableForm):

    #template = "toscasample.widgets.templates.table_form"
    #template = "sap.templates.administrar.proyecto.new"
    css = [CSSLink(link=url('/css/tooltips.css'))]
    show_errors = True

    lider_options = []
    fields = [
        TextField('nombre', validator=NotEmpty, label_text='Nombre'),
        Spacer(),
        TextField('descripcion', label_text='Descripcion'),
        #TextArea('descripcion', attrs=dict(rows=3, cols=10)),
        Spacer(),
        SingleSelectField('liderProyecto', options=lider_options),
        #TextField('liderProyecto', label_text='Lider de Proyecto')
    ]

    submit_text = 'Crear Proyecto'
示例#52
0
    def post_logout(self, came_from='/', **kw):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        #self._end_mex_session()
        #flash(_('We hope to see you soon!'))
        log.debug("post_logout")
        try:
            self._end_mex_session()
            session.delete()
            transaction.commit()
        except Exception:
            log.exception("post_logout")
        #redirect(came_from)
        log.debug("POST_LOGOUT")

        redirect(tg.url('/'))
示例#53
0
def get_public_link(obj_id):
    '''
   Return a HTML public download link.
   '''
    #TODO : understand and fix the bug...
    meas = DBSession.query(Measurements).filter(
        Measurements.id == obj_id).first()
    status = meas.status_type
    f_sha1 = ''
    #have to be public
    if status and len(meas.fus) > 0:
        list_fus = meas.fus
        for x in list_fus:
            f_sha1 = x.sha1
        return '''
              <a class='action public_link'  href="%s" title="public link for this measurement" style="text-decoration:none"></a> ''' % (
            url('./public/public_link', params=dict(sha1=f_sha1, m_id=obj_id)))
    else:
        return '''
示例#54
0
文件: trackhub.py 项目: bbcf/biorepo
    def index(self, *args, **kw):
        user = handler.user.get_user_in_session(request)
        user_lab = session.get("current_lab", None)
        mail = user.email
        mail_tmp = mail.split("@")
        mail_final = mail_tmp[0] + "AT" + mail_tmp[1]
        user_TH_path = trackhubs_path() + "/" + user_lab + "/" + mail_final
        trackhubs = []
        if os.path.exists(user_TH_path):
            list_trackhubs = os.listdir(user_TH_path)
            for t in list_trackhubs:
                th_path = user_TH_path + "/" + t
                #the only one directory into at this th level is named by the assembly used for it
                for i in os.listdir(th_path):
                    path_to_test = th_path + "/" + i
                    if os.path.isdir(path_to_test):
                        assembly = i
                if not assembly:
                    break
                else:
                    #hub_url = th_path + "/hub.txt"
                    hostname = socket.gethostname().lower()
                    #because of aliasing
                    if hostname == "ptbbsrv2.epfl.ch":
                        hostname = "biorepo.epfl.ch"
                    hub_url = "http://" + hostname + url(
                        "/trackHubs/"
                    ) + user_lab + "/" + mail_final + "/" + t + "/hub.txt"
                    th = Trackhub(
                        t, 'http://genome.ucsc.edu/cgi-bin/hgTracks?hubUrl=' +
                        hub_url + "&db=" + assembly)
                    trackhubs.append(th)

        all_trackhubs = [
            util.to_datagrid(TrackhubGrid(), trackhubs, " UCSC's Trackhub(s)",
                             len(trackhubs) > 0)
        ]

        return dict(page='trackhubs',
                    model=trackhubs,
                    items=all_trackhubs,
                    value=kw)
示例#55
0
文件: content.py 项目: qyqx/tracim
    def post(self, label='', content=''):
        workspace = tmpl_context.workspace

        api = ContentApi(tmpl_context.current_user)

        with DBSession.no_autoflush:
            page = api.create(ContentType.Page, workspace, tmpl_context.folder,
                              label)
            page.description = content

            if not self._path_validation.validate_new_content(page):
                return render_invalid_integrity_chosen_path(page.get_label(), )

        api.save(page, ActionDescription.CREATION, do_notify=True)

        tg.flash(_('Page created'), CST.STATUS_OK)
        redirect = '/workspaces/{}/folders/{}/pages/{}'
        tg.redirect(
            tg.url(redirect).format(tmpl_context.workspace_id,
                                    tmpl_context.folder_id, page.content_id))
示例#56
0
    def put(self, articleid, categoryid, tagids=None):
        """Edit a article"""
        lang = tmpl_context.lang or DBSession.query(Language).first().id
        article = DBSession.query(Article).get(articleid.decode())

        modified = False
        if article.category_id != categoryid:
            article.category_id = categoryid
            modified = True

        tags = tags_from_string(tagids, lang=lang)
        if article.tags != tags:
            article.tags[:] = tags
            modified = True

        if modified:
            flash('%s %s' % (_('Updated Article:'), articleid), 'ok')
        else:
            flash('%s %s' % (_('Article is unchanged:'), articleid), 'info')
        return dict(redirect_to=url('/article/%s/edit' % article.id))
示例#57
0
文件: content.py 项目: qyqx/tracim
    def post(self, label='', file_data=None):
        # TODO - SECURE THIS
        workspace = tmpl_context.workspace
        folder = tmpl_context.folder

        api = ContentApi(tmpl_context.current_user)
        with DBSession.no_autoflush:
            file = api.create(ContentType.File, workspace, folder, label)
            api.update_file_data(file, file_data.filename, file_data.type,
                                 file_data.file.read())
            # Display error page to user if chosen label is in conflict
            if not self._path_validation.validate_new_content(file):
                return render_invalid_integrity_chosen_path(
                    file.get_label_as_file(), )
        api.save(file, ActionDescription.CREATION)

        tg.flash(_('File created'), CST.STATUS_OK)
        redirect = '/workspaces/{}/folders/{}/files/{}'
        tg.redirect(
            tg.url(redirect).format(tmpl_context.workspace_id,
                                    tmpl_context.folder_id, file.content_id))
示例#58
0
 def _edit_permissions(self):
     '''Check current users permissions for editing and generate appropriate warnings'''
     if (request.user in self.event.tutorsandteachers or
             'manage' in request.permissions):
         if self.submission.user == request.user:
             # Teacher on Teachers own submission
             if not self.assignment.is_active:
                 flash('The assignment is not active, you should not edit this submission anymore.', 'warning')
         else:
             # Teacher on Students Submission
             flash('You are a teacher trying to edit a student\'s submission. '
                   'You probably want to go to the judgement page instead!', 'warning')
     else:
         if self.submission.user != request.user:
             abort(403)
         # Student on own Submission
         if not self.assignment.is_active:
             flash('This assignment is not active, you can not edit this submission anymore.', 'warning')
             redirect(url(self.submission.url + '/show'))
         elif self.submission.judgement:
             flash('This submission has already been judged, you should not edit it anymore.', 'warning')
示例#59
0
    def settings_set(self, name=None, value=None):
        """Set settings values"""
        query = DBSession.query(Setting)
        settings = dict([(s.id, s) for s in query])
        if not len(name) == len(value):
            raise HTTPBadRequest("names and values don't match")

        modified = False
        for n, v in zip(name, value):
            if n in settings:
                if not settings[n].value == v:
                    settings[n].value = v
                    modified = True
            else:
                DBSession.add(Setting(n, v))
                modified = True

        if modified:
            flash(_('Updated Settings'), 'ok')
        else:
            flash(_('Settings are unchanged'), 'info')
        redirect(url('/admin/settings/'))
示例#60
0
    def put(self, _id, title, category, question, answer_type,
            interested_response, **kw):

        check = self.get_related_entities(_id)
        if check.get("entities"):
            entity = dict(_id=_id,
                          title=title,
                          condition=[question, interested_response],
                          _category=category,
                          entity='precondition/simple')
            session[
                'entity'] = entity  # overwrite always same key for avoiding conflicts
            session.save()
            return dict(redirect_url=tg.url('/resolve',
                                            params=dict(workspace=category)))

        precondition = model.Precondition.query.get(_id=ObjectId(_id))
        precondition.title = title
        precondition.condition = [ObjectId(question), interested_response]
        precondition._category = category

        return dict(errors=None, redirect_url=None)