Example #1
0
 def _parseParams(self,params):
     if "resumption_token" in params and len(params) > 1:
         abort(500,"resumption_token must be the only parameter")
     data = {
         'by_doc_ID':False,
         'by_resource_ID':True,
         'ids_only': False,
         'request_IDs': [],            
     }
     if params.has_key('by_doc_ID') and params['by_doc_ID'] in trues:
         data['by_doc_ID'] = True
         data['by_resource_ID'] = False                    
     if params.has_key('by_resource_ID'):            
         data['by_resource_ID'] = params['by_resource_ID'] in trues
     if params.has_key('ids_only'):
         data['ids_only'] = params['ids_only'] in trues
     if params.has_key('resumption_token'):
         data['resumption_token'] = rt.parse_token('obtain',params['resumption_token'])
     if params.has_key('callback'):
         data['callback'] = params['callback']
     if params.has_key('request_ID'):
         data['request_IDs'].append(params['request_ID'])
     elif params.has_key('request_id'):
         data['request_IDs'].append(params['request_id'])            
     if params.has_key('request_IDs'):
         data['request_IDs'].extend(params['request_IDs'])
     if data['by_resource_ID']:
         data['request_IDs'] = [unquote_plus(id) for id in data['request_IDs']]        
     return data        
Example #2
0
 def run(self, cid):
     if cid:
         try:
             cid = int(cid, 36)
             return Comment._byID(cid, True)
         except (NotFound, ValueError):
             abort(404, 'page not found')
Example #3
0
def ratelimit_agent(agent):
    key = 'rate_agent_' + agent
    if g.cache.get(key):
        request.environ['retry_after'] = 1
        abort(429)
    else:
        g.cache.set(key, 't', time = 1)
Example #4
0
    def _search_teachers(self, location, text, sub_department_id=None):
        locations = [loc.id for loc in location.flatten]

        query = meta.Session.query(Teacher)\
                .filter(Teacher.location_id.in_(locations))

        if sub_department_id:
            query = query.filter_by(sub_department_id=sub_department_id)

        if text:
            query = query.filter(Teacher.fullname.contains(text))

        try:
            page_no = int(request.params.get('page', 1))
        except ValueError:
            abort(404)
        c.page = page_no

        c.results = paginate.Page(
            query,
            page=c.page,
            items_per_page=30,
            item_count=search_query_count(query),
            obj_type='teacher')
        c.searched = True
Example #5
0
 def run(self, message_id):
     if message_id:
         try:
             aid = int(message_id, 36)
             return Message._byID(aid, True)
         except (NotFound, ValueError):
             abort(404, 'page not found')
Example #6
0
def check_session():
    '''
    This function checks the session cookie for management API
    and compares it to the session parameter
    '''
    if isSelfTest():
        return

    # check if the client is in the allowed IP range
    no_session_clients = [c.strip() for c in config.get("linotpNoSessionCheck", "").split(",")]
    client = request.environ.get('REMOTE_ADDR', None)
    log.debug("[check_session] checking %s in %s" % (client, no_session_clients))
    for network in no_session_clients:
        if not network:
            continue
        try:
            if IPAddress(client) in IPNetwork(network):
                log.debug("[check_session] skipping session check since client %s in allowed: %s" % (client, no_session_clients))
                return
        except Exception as ex:
            log.warning("[check_session] misconfiguration in linotpNoSessionCheck: %r - %r" % (network, ex))

    if request.path.lower() == '/admin/getsession':
        log.debug('[check_session] requesting a new session cookie')
    else:
        cookie = request.cookies.get('admin_session')
        session = request.params.get('session')
        # doing any other request, we need to check the session!
        log.debug("[check_session]: session: %s" % session)
        log.debug("[check_session]: cookie:  %s" % cookie)
        if session is None or session == "" or session != cookie:
            log.error("[check_session] The request did not pass a valid session!")
            abort(401, "You have no valid session!")
            pass
Example #7
0
    def _vote_save(self):
        post = request.POST

        # Fetch POST data
        vote = post.get(u'vote')
        email = post.get(u'email')
        op = post.get(u'op')
        attachment = post.get(u'vote-attachment')
        comment = post.get(u'vote-comment')
        fp = attachment.file if isinstance(attachment, cgi.FieldStorage) else None
        attachment_data = fp.read(256).decode('utf-8') if fp else '<None>' # Note: assume plain text utf-8 file
        #raise Exception('Inspect POST data')

        # Validate request
        if not (post.get(secure_form.token_key, None) == secure_form.authentication_token()):
            abort (403, detail=u'Not permitted (possible CSRF attack)')

        # Validate POST data: in practice we should not abort but rather redirect to the form
        # with all the errors highlighted
        vote = int(vote)
        if not (vote >= 0 and vote <= 10):
            abort (400, detail=u'Bad value for vote')

        # Done with validation, now just log this and store the (vote,email) in the underlying model
        log.info ('Saving vote for poll (%r)' %(dict(vote=vote, email=email, op=op, attachment_data=attachment_data)))
        db_session = model.Session()
        v = model.Vote (vote=vote, email=email, created_at=None, description=comment);
        db_session.add(v)
        db_session.commit()

        # Done with form processing, redirect to a normal (GET) request ...
        h.flash('Your vote is saved!')
        redirect (url(controller='poll', action='results'))
        return
Example #8
0
    def _location_action(self, path, obj_type=None):
        location = LocationTag.get(path)
        if location is None:
            abort(404)

        c.security_context = location
        c.object_location = None
        c.location = location

        c.selected_sub_department_id = request.params.get('sub_department_id', None)
        c.selected_sub_department = None
        if c.selected_sub_department_id:
            subdepartment = SubDepartment.get(c.selected_sub_department_id)
            c.selected_sub_department = subdepartment
            c.menu_items = subdepartment_menu_items(subdepartment)

        else:
            c.tabs = location_feed_subtabs(location)
            if c.user:
                c.menu_items = location_menu_items(location)
            else:
                c.menu_items = location_menu_public_items(location)

        c.breadcrumbs = location_breadcrumbs(location)

        c.theme = location.get_theme()
        c.notabs = True


        c.current_menu_item = None
        if obj_type is None:
            return method(self, location)
        else:
            return method(self, location, obj_type)
    def rate(self, slug, up=None, down=None, **kwargs):
        """Say 'I like this' for the given media.

        :param slug: The media :attr:`~mediadrop.model.media.Media.slug`
        :rtype: unicode
        :returns:
            The new number of likes

        """
        media = fetch_row(Media, slug=slug)
        request.perm.assert_permission(u'view', media.resource)

        if up:
            if not request.settings['appearance_show_like']:
                abort(status_code=403)
            media.increment_likes()
        elif down:
            if not request.settings['appearance_show_dislike']:
                abort(status_code=403)
            media.increment_dislikes()

        if request.is_xhr:
            return u''
        else:
            redirect(action='view')
Example #10
0
 def index(self):
     c.pins = []
     try:
         c.pins = Session.query(ModeratorPin).filter(ModeratorPin.username==session.get('username')).all()
     except Exception, e:
         log.critical('Could not get pins: %s' % e)
         abort(500)
Example #11
0
    def _subdepartmnet_action(self, path, subdept_id, obj_type=None):
        location = LocationTag.get(path)
        if location is None:
            abort(404)

        subdepartment = meta.Session.query(SubDepartment).filter_by(id=subdept_id).one()
        if subdepartment is None:
            abort(404)

        c.security_context = location
        c.object_location = None
        c.location = location
        c.breadcrumbs = subdepartment_breadcrumbs(subdepartment)
        c.subdepartment = subdepartment

        c.theme = location.get_theme()
        c.notabs = True

        c.menu_items = subdepartment_menu_items(subdepartment)

        c.current_menu_item = None
        if obj_type is None:
            return method(self, location, subdepartment)
        else:
            return method(self, location, subdepartment, obj_type)
Example #12
0
    def _reset(self, username=None):
        username = username or request.environ.get('REMOTE_USER', False)
        if not username:
            abort(401)

        try:
            user = h.get_user(username)
        except:
            abort(400)
            
        new_password = user.reset_password()


        msg = Message("*****@*****.**", user.email,
                      "InPhO password reset")
        msg.plain = """
%(name)s, your password at the Indiana Philosophy Ontology (InPhO) has been changed to:
Username: %(uname)s
Password: %(passwd)s

The Indiana Philosophy Ontology (InPhO) Team
[email protected]
                       """ % {'passwd' : new_password,
                              'uname' : user.username,
                              'name' : user.fullname or user.username or ''}
        msg.send()

        Session.commit()

        h.redirect(h.url(controller='account', action='reset_result'))
 def getrecord():
   data = self.get_base_response(verb,body)
   by_doc_ID = self._check_bool_param(params,'by_doc_ID')
   by_resource_ID = self._check_bool_param(params,'by_resource_ID') 
   if not params.has_key(self.REQUESTID):
     data['OK'] = False
     data['error'] = 'badArgument'
     return json.dumps(data)
   if by_doc_ID and by_resource_ID:
     data['OK'] = False
     data['error'] = 'badArgument'
     return json.dumps(data)          
   request_id = params[self.REQUESTID]
   if by_doc_ID:
     document = h.get_record(request_id)
     if document is not None:
         records = map(lambda doc: {"header":{'identifier':doc['_id'], 'datestamp':helpers.convertToISO8601Zformat(datetime.today()),'status':'active'},'resource_data':doc},[document])
     else:
         records = []
   else:
     records = map(lambda doc: {"header":{'identifier':doc['_id'], 'datestamp':helpers.convertToISO8601Zformat(datetime.today()),'status':'active'},'resource_data':doc},h.get_records_by_resource(request_id))
   if len(records) == 0:
     abort(500,'idDoesNotExist')
   data['getrecord'] ={
     'record': records
   }
   data['request']['identifier']  = request_id
   data['request']['by_doc_ID'] = by_doc_ID
   data['request']['by_resource_ID'] = by_resource_ID
   return json.dumps(data)
Example #14
0
 def show(self, id):
     try:
         task = Session.query(Task).filter_by(id=id).one()
     except:
         abort(404)
     notes = Session.query(Note).filter_by(task=id).all()
     return render("tasks/show.html", {"task": task, "notes": notes})
Example #15
0
 def update(self, id):
     slug = id.lower().strip()
     snippets = list(Snippet.by_slug(self.db)[slug]) or abort(404)
     snippet = snippets[0]
     if snippet.displayname:
         author = Human.load(self.db, snippet.human_id)
     is_owner = self._check_owner(snippet, c.user, check_session=True)
     if not is_owner:
         abort(401)
     
     snippet.title = self.form_result['title']
     snippet.content = self.form_result['content']
     snippet.description = self.form_result['description']
     
     ## generate the slug
     slug = snippet.title.replace(" ", "_")
     slug = slug.lower()
     slug = re.sub('[^A-Za-z0-9_]+', '', slug)
     
     snippet.slug = slug
     if 'tags' in self.form_result:
         snippet.tags = self.form_result['tags'].replace(',', ' ').strip().split(' ')
     snippet.store(self.db)
     success_flash('Snippet has been updated')
     redirect(url('snippet', id=slug))
Example #16
0
    def revoke(self, redirect_url=None):
        v_id = request.params.get('id', None)

        if v_id is None:
            abort(401, "id of velruse account not specified")

        v = Velruse.by_id(v_id)
        if v is None:
            self._failure(_("You are trying to disconnect from a provider"
                            " you are disconnected from already."))
            return None

        elif not (v.user == c.user or can.user.manage()):
            abort(403, _("You're not authorized to change %s's settings.")
                  % c.user.id)
        else:
            v.delete_forever()
            model.meta.Session.commit()

            h.flash(_("You successfully disconnected from %(provider)s.")
                    % {'provider': v.domain},
                    'success')

            if redirect_url is None:
                redirect(h.entity_url(c.user, member='settings/login'))
            else:
                redirect(redirect_url)
Example #17
0
    def save(self, id=None):
        """
        """
        if id is None:
            abort(404)
        assay_q = Session.query(Assay)
        assay = assay_q.filter_by(id=id).first()
        if assay is None:
            abort(404)

        reload_sequences = False
        for k, v in self.form_result.items():
            if k in ("primer_fwd", "primer_rev", "chromosome", "probe_pos", "amplicon_width", "snp_rsid"):
                if getattr(assay, k) != v:
                    reload_sequences = True
            if k not in ("id"):
                setattr(assay, k, v)

        # blow away previous sequences; on view, this will update.
        if reload_sequences:
            cached_sequences = assay.cached_sequences
            for i in range(len(cached_sequences)):
                cs = cached_sequences[-1]
                snps = cs.snps
                for j in range(len(snps)):
                    snp = snps.pop()
                    Session.delete(snp)
                cached_sequences.pop()
                Session.delete(cs)

        self.__update_tms(assay)

        Session.commit()
        session.save()
        redirect(url(controller="assay", action="view", id=assay.id))
Example #18
0
    def submit_changes(self):
        ''' 
        This function validates the submitted profile edit form and commits the 
        changes. Restricted to ``POST`` requests. If successful, redirects to 
        the result action to prevent resubmission.
        ''' 
        if not h.auth.is_logged_in():
            abort(401)

        c.user = h.get_user(request.environ['REMOTE_USER'])
       
        if self.form_result['password'] != '':
            c.user.set_password(self.form_result['password'])

        # TODO: Enable area editing
        #c.user.first_area_id=self.form_result['first_area'],
        #user.first_area_level=self.form_result['first_area_level'],
        #if self.form_result['second_area']:
        #    c.user.second_area_id=self.form_result['second_area'],
        #    c.user.second_area_level=self.form_result['second_area_level']
        c.user.fullname = self.form_result['fullname']

        Session.flush()

        Session.commit()

        h.redirect(h.url(controller='account', action='profile', message='edited'))
Example #19
0
    def catalog(self, location, obj_type):
        c.current_menu_item = obj_type + 's'
        self.form_result['tagsitem'] = location.hierarchy()
        self.form_result['obj_type'] = obj_type

        c.text = self.form_result.get('text', '')

        if obj_type == 'teacher':
            self._search_teachers(location, c.text, c.selected_sub_department_id)
        elif obj_type == 'department':
            self._list_departments(location, c.text)
        elif obj_type == 'sub_department':
            self._list_sub_departments(location, c.text)
        else:
            self._search()

        c.sub_departments = []
        if obj_type == 'teacher':
            c.sub_departments = [sub_department
                                 for sub_department in c.location.sub_departments
                                 if bool(sub_department.teachers)]
        elif obj_type == 'subject':
            c.sub_departments = [sub_department
                                 for sub_department in c.location.sub_departments
                                 if bool(sub_department.subjects)]

        # render template by object type

        if obj_type in self.catalog_template_names:
            c.current_menu_item = obj_type
            return render(self.catalog_template_names[obj_type])
        else:
            abort(404)
Example #20
0
    def evaluate(self, id=None):
        if not h.auth.is_logged_in():
            abort(401)

        c.idea = h.fetch_obj(Idea, id, new_id=True)
        node_q = Session.query(Node).filter_by(concept_id=id)
        c.node = node_q.first()
        if request.environ.get('REMOTE_USER', False):
            user = h.get_user(request.environ['REMOTE_USER'])

            sq = Session.query(IdeaEvaluation.cons_id)
            sq = sq.filter(IdeaEvaluation.ante==c.idea)
            sq = sq.filter(IdeaEvaluation.uid==user.ID)
            sq = sq.subquery()

            to_evaluate = c.idea.related.outerjoin((sq, Idea.ID==sq.c.cons_id))
            to_evaluate = to_evaluate.filter(sq.c.cons_id==None)

        else:
            to_evaluate = c.idea.related

        c.paginator = paginate.Page(
            to_evaluate,
            page=int(request.params.get('page', 1)),
            items_per_page=10,
            controller='idea',
            action='edit',
            id=id
        )


        return render('idea/idea-edit.html')
Example #21
0
    def _evaluate(self, evaltype, id, id2=None, uid=None, username=None, degree=-1, maxdegree=4):
        """
        Function to submit an evaluation. Takes a POST request containing the consequesnt id and 
        all or none of: generality, relatedness, hyperrank, hyporank.
        """
        if not h.auth.is_logged_in():
            abort(401)

        id2 = request.params.get('id2', id2)
        uid = request.params.get('uid', uid)
        username = request.environ.get('REMOTE_USER', username)

        print "grabbing eval for", username, uid

        if request.environ.get('REMOTE_USER', False):
            evaluation = self._get_evaluation(id, id2, None, username)
        else:
            evaluation = self._get_anon_evaluation(id, id2, request.environ.get('REMOTE_ADDR', '0.0.0.0'))

        # Populate proper generality, relatedness, hyperrank and hyporank values
        # Attempt to convert to integers, if unable, throw HTTP 400
        try: 
            setattr(evaluation, evaltype, 
                    int(request.params.get('degree', getattr(evaluation, evaltype))))
        except TypeError:
            abort(400)


        # Create and commit evaluation
        Session.flush()
        Session.commit()

        # Issue an HTTP success
        response.status_int = 200
        return "OK"
Example #22
0
    def enzyme_conc_edit(self, id=None):
        if id is None:
            abort(404)

        conc = Session.query(EnzymeConcentration).get(id)
        if not conc:
            abort(404)

        c.conc = conc

        enzyme_field = fl.enzyme_field(selected=unicode(conc.enzyme_id))
        assay_field = fl.assay_field(blank=True, selected=unicode(conc.assay.id))
        author_field = fl.person_field(selected=unicode(conc.author_id))
        c.plate = None
        c.form = h.LiteralFormSelectPatch(
            value={
                "enzyme_id": enzyme_field["value"],
                "assay_id": assay_field["value"],
                "author_id": author_field["value"],
                "minimum_conc": conc.minimum_conc,
                "maximum_conc": conc.maximum_conc,
                "source_plate_id": conc.source_plate_id,
                "notes": conc.notes,
            },
            option={
                "enzyme_id": enzyme_field["options"],
                "assay_id": assay_field["options"],
                "author_id": author_field["options"],
            },
        )
        return render("/assay/enzyme/edit.html")
Example #23
0
    def delete(self, userid):
        """/accounts/delete/id"""
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = EditUserForm(request.POST, user, csrf_context=session)
        del c.form.domains

        if request.POST and c.form.validate():
            username = user.username
            user_id = unicode(user.id)
            Session.delete(user)
            Session.commit()
            update_serial.delay()
            flash(_('The account has been deleted'))
            info = DELETEACCOUNT_MSG % dict(u=username)
            audit_log(c.user.username,
                    4, unicode(info), request.host,
                    request.remote_addr, now())
            if userid == user_id:
                redirect(url('/logout'))
            redirect(url(controller='accounts', action='index'))
        else:
            flash_info(_('The account: %(a)s and all associated data'
                ' will be deleted, This action is not reversible.') %
                dict(a=user.username))
        c.fields = FORM_FIELDS
        c.id = userid
        return render('/accounts/delete.html')
Example #24
0
    def index(self, slave=None):
        if 'numbuilds' in request.GET:
            count = int(request.GET.getone('numbuilds'))
        else:
            count = 25

        if 'format' in request.GET:
            format = request.GET.getone('format')
        else:
            format = 'html'
        if format not in ('html', 'json'):
            abort(400, detail='Unsupported format: %s' % format)

#        if slave is not None:
#            slave = slave[0]
        if 'slave' in request.GET:
            slave = request.GET.getall('slave')

        builds = GetHistoricBuilds(slave=slave, count=count)

        # Return a rendered template
        # or, return a json blob
        if format == "html":
            c.recent_builds = builds
            return render("/recent.mako")
        else:
            for b in builds:
                for k,v in b.items():
                    if isinstance(v, datetime.datetime):
                        v = times.UTC.localize(v)
                        b[k] = times.dt2ts(v)
            return self.jsonify(builds)
Example #25
0
    def login(self):
        "login"
        if request.remote_addr in session:
            if session[request.remote_addr] > now():
                abort(409, _('You have been banned after'
                            ' several failed logins'))
            else:
                del session[request.remote_addr]
                session.save()

        identity = request.environ.get('repoze.who.identity')
        came_from = unquote(str(request.GET.get('came_from', '')))
        if not came_from or ' ' in came_from:
            came_from = url('home')
        if '://' in came_from:
            from_url = urlparse(came_from)
            came_from = from_url[2]

        if identity:
            redirect(url(came_from))
        else:
            c.came_from = came_from
            c.login_counter = request.environ['repoze.who.logins']
            if c.login_counter >= 3:
                ban_until = now() + timedelta(minutes=5)
                if request.remote_addr not in session:
                    session[request.remote_addr] = ban_until
                    session.save()
                else:
                    if now() > session[request.remote_addr]:
                        del session[request.remote_addr]
                        session.save()
            c.form = ResetPwForm(request.POST, csrf_context=session)
            return render('/accounts/login.html')
Example #26
0
    def view(self, dataset, dimension, format='html'):
        self._get_dataset(dataset)
        try:
            c.dimension = c.dataset[dimension]
        except KeyError:
            abort(404, _('This is not a dimension'))
        if not isinstance(c.dimension, model.Dimension):
            abort(404, _('This is not a dimension'))

        page = self._get_page('page')
        cache = AggregationCache(c.dataset)
        result = cache.aggregate(drilldowns=[dimension], page=page, 
                                 pagesize=PAGE_SIZE)
        items = result.get('drilldown', [])
        c.values = [(d.get(dimension), d.get('amount')) for d in items]

        if format == 'json':
            return to_jsonp({
                "values": c.values,
                "meta": c.dimension.as_dict()})

        c.page = Page(c.values, page=page,
                      item_count=result['summary']['num_drilldowns'],
                      items_per_page=PAGE_SIZE,
                      presliced_list=True)
        return render('dimension/view.html')
Example #27
0
 def pwchange(self, userid):
     """Reset a user password"""
     user = self._get_user(userid)
     if not user:
         abort(404)
     c.form = ChangePasswordForm(request.POST, csrf_context=session)
     if request.POST and c.form.validate():
         if user.local and not user.is_superadmin:
             user.set_password(c.form.password1.data)
             Session.add(user)
             Session.commit()
             flash(_('The account password for %(name)s has been reset')
                 % dict(name=user.username))
             info = PASSWORDCHANGE_MSG % dict(u=user.username)
             audit_log(c.user.username,
                     2, unicode(info), request.host,
                     request.remote_addr, now())
         else:
             if user.is_superadmin:
                 flash(_('Admin accounts can not be modified via the web'))
             else:
                 flash(_('This is an external account, use'
                     ' external system to reset the password'))
         redirect(url('account-detail', userid=user.id))
     c.id = userid
     c.username = user.username
     c.posturl = 'accounts-pw-change'
     return render('/accounts/pwchange.html')
Example #28
0
 def upwchange(self, userid):
     """User change own password"""
     user = self._get_user(userid)
     if not user:
         abort(404)
     if user.id != c.user.id or c.user.is_superadmin:
         abort(403)
     c.form = UserPasswordForm(request.POST, csrf_context=session)
     if (request.POST and c.form.validate() and
         user.validate_password(c.form.password3.data)):
         if user.local:
             user.set_password(c.form.password1.data)
             Session.add(user)
             Session.commit()
             flash(_('The account password for %(name)s has been reset')
                 % dict(name=user.username))
             info = PASSWORDCHANGE_MSG % dict(u=user.username)
             audit_log(c.user.username,
                     2, unicode(info), request.host,
                     request.remote_addr, now())
         else:
             flash(_('This is an external account, use'
                 ' external system to reset the password'))
         redirect(url('account-detail', userid=user.id))
     elif (request.POST and not
         user.validate_password(c.form.password3.data)
         and not c.form.password3.errors):
         flash_alert(_('The old password supplied does'
                     ' not match our records'))
     c.id = userid
     c.username = user.username
     c.posturl = 'accounts-pw-uchange'
     return render('/accounts/pwchange.html')
Example #29
0
 def detail(self, userid):
     """GET /accounts/userid/ Show a specific item"""
     user = self._get_user(userid)
     if not user:
         abort(404)
     c.account = user
     return render('/accounts/account.html')
    def index(self, format='json'):
        """GET /: return all features."""
        # If no filter argument is passed to the protocol index method
        # then the default MapFish filter is used.
        #
        # If you need your own filter with application-specific params 
        # taken into acount, create your own filter and pass it to the
        # protocol read method.
        #
        # E.g.
        #
        # from sqlalchemy.sql import and_
        #
        # default_filter = create_default_filter(request, BroadbandSpeed)
        # filter = and_(default_filter, BroadbandSpeed.columname.ilike('%value%'))
        # return self.protocol.read(request, filter=filter)
        default_filter = create_default_filter(request, BroadbandSpeed)

        if "zones_f" in request.params:
            #zones will be a javascript list
            zones_q = request.params["zones_f"].split(",")
            #zones = Session.query(functions.geometry_type(functions.collect(Zone.geom))).filter(and_(Zone.zone_general.in_(zones_q),
            #                                                                                       Zone.geom != None)).scalar()
            zones = Session.query(functions.union(Zone.geom)).filter(Zone.zone_general.in_(zones_q)).first()
            filter = and_(default_filter, BroadbandSpeed.geom.within(zones))
        else:
            filter = default_filter

        if format != 'json':
            abort(404)
        return self.protocol.read(request, filter=filter)
Example #31
0
    def check_status(self):
        """
        simple check if LinOTP backend services  are up and running

        - support for checking that the Config database could be accessed

        """
        try:
            opt = {}

            config_count = Session.query(Config).count()
            opt['config'] = {'entries': config_count}

            return sendResult(response, True, 0, opt=opt)

        except Exception as exx:
            Session.rollback()
            log.exception(exx)
            abort(500, "%r" % exx.message)

        finally:
            Session.close()
Example #32
0
def set_subreddit():
    #the r parameter gets added by javascript for POST requests so we
    #can reference c.site in api.py
    sr_name = request.environ.get("subreddit", request.POST.get('r'))
    domain = request.environ.get("domain")

    c.site = Default
    if not sr_name:
        #check for cnames
        sub_domain = request.environ.get('sub_domain')
        if sub_domain and not sub_domain.endswith(g.media_domain):
            c.site = Subreddit._by_domain(sub_domain) or Default
    elif sr_name == 'r':
        #reddits
        c.site = Sub
    else:
        try:
            if '+' in sr_name:
                srs = set()
                sr_names = sr_name.split('+')
                real_path = sr_name
                for sr_name in sr_names:
                    srs.add(Subreddit._by_name(sr_name))
                sr_ids = [sr._id for sr in srs]
                c.site = MultiReddit(sr_ids, real_path)
            else:
                c.site = Subreddit._by_name(sr_name)
        except NotFound:
            sr_name = chksrname(sr_name)
            if sr_name:
                redirect_to("/reddits/search?q=%s" % sr_name)
            elif not c.error_page:
                abort(404, "not found")
    #if we didn't find a subreddit, check for a domain listing
    if not sr_name and c.site == Default and domain:
        c.site = DomainSR(domain)

    if isinstance(c.site, FakeSubreddit):
        c.default_sr = True
Example #33
0
    def milestones(self, id, format=u'html'):
        if not c.instance.display_category_pages:
            abort(404)
        category = get_entity_or_abort(model.CategoryBadge, id)

        milestones = model.Milestone.all_future_q(instance=c.instance)\
            .filter(model.Milestone.category_id == category.id)\
            .limit(int(request.params.get('count', 50))).all()

        enable_sorts = asbool(request.params.get('enable_sorts', 'true'))
        enable_pages = asbool(request.params.get('enable_pages', 'true'))

        data = {
            'milestone_pager':
            pager.milestones(milestones,
                             enable_sorts=enable_sorts,
                             enable_pages=enable_pages),
        }
        return render('/category/milestones.html',
                      data,
                      overlay=format == 'overlay',
                      overlay_size=OVERLAY_SMALL)
Example #34
0
    def featured(self, limit=None, skip=0, **kwargs):
        """Generate a media rss (mRSS) feed of the sites featured media."""
        if request.settings['rss_display'] != 'True':
            abort(404)

        response.content_type = content_type_for_response(
            ['application/rss+xml', 'application/xml', 'text/xml'])

        media_query = Media.query.in_category(get_featured_category())\
            .published()\
            .order_by(Media.publish_on.desc())
        media = viewable_media(media_query)
        if limit is not None:
            media = media.limit(limit)

        if skip > 0:
            media = media.offset(skip)

        return dict(
            media=media,
            title='Featured Media',
        )
Example #35
0
    def search_fail(self, exception):
        from r2.lib.contrib.pysolr import SolrError
        from r2.lib.indextank import IndextankException
        if isinstance(exception, SolrError):
            errmsg = "SolrError: %r" % exception

            if (str(exception) == 'None'):
                # Production error logs only get non-None errors
                g.log.debug(errmsg)
            else:
                g.log.error(errmsg)
        elif isinstance(exception, (IndextankException, socket.error)):
            g.log.error("IndexTank Error: %s" % repr(exception))

        sf = pages.SearchFail()

        us = filters.unsafe(sf.render())

        errpage = pages.RedditError(_('search failed'), us)
        request.environ['usable_error_content'] = errpage.render()
        request.environ['retry_after'] = 60
        abort(503)
Example #36
0
    def __before__(self, *args, **kwargs):
        """This method is called before your action is.

        It should be used for setting up variables/objects, restricting access
        to other actions, or other tasks which should be executed before the
        action is called.

        NOTE: If this method is wrapped in an ActionProtector, all methods of
              the class will be protected it. See :meth:`__init__`.
        """
        self.setup_translator()
        response.scripts = Scripts()
        response.stylesheets = StyleSheets()
        response.facebook = None
        request.perm = request.environ['mediacore.perm']

        action_method = getattr(self, kwargs['action'], None)
        # The expose decorator sets the exposed attribute on controller
        # actions. If the method does not exist or is not exposed, raise
        # an HTTPNotFound exception.
        if not getattr(action_method, 'exposed', False):
            abort(status_code=404)
Example #37
0
    def check_url(self):
        '''
        This function works with pam_url.
        '''
        ok = False
        param = {}
        try:
            param.update(request.params)

            try:
                (ok, opt) = self._check(param)
            except AuthorizeException as acc:
                log.warning("[check_url] authorization failed for validate/check_url: %r" % acc)
                c.audit['success'] = False
                c.audit['action_detail'] = unicode(acc)
                ok = False

            Session.commit()
            response.headers['blablafoo'] = 'application/json'

            ## TODO: this code seems not to be finished
            if not ok:
                abort(403)
            else:
                return "Preshared Key Todo"

        except webob.exc.HTTPUnauthorized as acc:
            ## the exception, when an abort() is called if forwarded
            log.exception("[__before__::%r] webob.exception %r" % acc)
            Session.rollback()
            raise acc

        except Exception as exx:
            log.exception("[check_url] validate/check_url failed: %r" % exx)
            Session.rollback()
            return sendResult(response, False, 0)

        finally:
            Session.close()
Example #38
0
    def _delete_evaluation(self, evaltype, id, id2, uid=None, username=None):
        id2 = request.params.get('id2', id2)
        uid = request.params.get('uid', uid)
        username = request.params.get('username', username)

        # look for a specific user's feedback
        evaluation = self._get_evaluation(evaltype,
                                          id,
                                          id2,
                                          uid,
                                          username,
                                          autoCreate=False)

        # if that feedback does not exist, unleash the nuclear option and delete
        # ALL evaluation facts for this relation, wiping it from the database.
        if h.auth.is_admin() and not evaluation:
            eval_q = Session.query(evaltype)
            eval_q = eval_q.filter_by(ante_id=id, cons_id=id2)
            evals = eval_q.all()

            # wipe them out. all of them.
            for evaluation in evals:
                h.delete_obj(evaluation)

            # return ok, with how many were deleted
            response.status_int = 200
            return "OK %d" % len(evals)

        elif not evaluation:
            abort(404)  # simply return an error (not evaluated), if not admin

        current_uid = h.get_user(request.environ['REMOTE_USER']).ID
        if evaluation.uid != current_uid and not h.auth.is_admin():
            abort(401)

        h.delete_obj(evaluation)

        response.status_int = 200
        return "OK"
    def featured(self, limit=30, skip=0, **kwargs):
        """Generate a media rss (mRSS) feed of the sites featured media."""
        if request.settings['rss_display'] != 'True':
            abort(404)

        response.content_type = mimeparse.best_match(
            ['application/rss+xml', 'application/xml', 'text/xml'],
            request.environ.get('HTTP_ACCEPT', '*/*')
        )

        media = Media.query.in_category(get_featured_category())\
            .published()\
            .order_by(Media.publish_on.desc())\
            .limit(limit)

        if skip > 0:
            media = media.offset(skip)

        return dict(
            media = media,
            title = 'Featured Media',
        )
Example #40
0
def fetch_obj(type, id, error=404, new_id=False):
    """
    Fetches the object with the given id from the collection of type type. If
    the object does not exist, throw an HTTP error (default: 404 Not Found).

    :param type: object type
    :type type: class in :mod:`inpho.model`
    :param id: object id
    :type id: integer or None
    :param error: HTTP error code.
    :rtype: *type*
    """
    if id is None:
        abort(error)
    obj_q = Session.query(type)
    obj = obj_q.get(int(id))
    #else:
    #    obj = obj_q.filter(type.ID==int(id)).first()

    if obj is None:
        abort(error)
    return obj
Example #41
0
 def render(self, *a, **kw):
     """Overrides default Wrapped.render with two additions
        * support for rendering API requests with proper wrapping
        * support for space compression of the result
     In adition, unlike Wrapped.render, the result is in the form of a pylons
     Response object with it's content set.
     """
     try:
         res = Wrapped.render(self, *a, **kw)
         if is_api():
             res = json_respond(res)
         elif self.space_compress:
             res = spaceCompress(res)
         c.response.content = res
     except NoTemplateFound, e:
         # re-raise the error -- development environment
         if g.debug:
             s = sys.exc_info()
             raise s[1], None, s[2]
         # die gracefully -- production environment
         else:
             abort(404, "not found")
    def _dispatch(self, state, remainder):
        """returns: populated DispachState object
        """
        if not hasattr(state, 'http_method'):
            method = pylons.request.method.lower()
            params = state.params

            #conventional hack for handling methods which are not supported by most browsers
            request_method = params.get('_method', None)
            if request_method:
                request_method = request_method.lower()
                #make certain that DELETE and PUT requests are not sent with GET
                if method == 'get' and request_method == 'put':
                    abort(405)
                if method == 'get' and request_method == 'delete':
                    abort(405)
                method = request_method
            state.http_method = method

        r = self._check_for_sub_controllers(state, remainder)
        if r:
            return r

        if state.http_method in self._handler_lookup.keys():
            r = self._handler_lookup[state.http_method](self,
                                                        state.http_method,
                                                        state, remainder)
        else:
            r = self._handle_custom_method(state.http_method, state, remainder)

        #clear out the method hack
        if '_method' in pylons.request.POST:
            del pylons.request.POST['_method']
            del state.params['_method']
        if '_method' in pylons.request.GET:
            del pylons.request.GET['_method']
            del state.params['_method']

        return r
Example #43
0
    def mailq(self, serverid=None, queue='inbound', page=1, direction='dsc',
        order_by='timestamp'):
        "Display mailqueue"
        server = None
        if not serverid is None:
            server = self._get_server(serverid)
            if not server:
                abort(404)

        c.queue = queue
        c.server = server
        c.direction = direction
        c.order_by = desc(order_by) if direction == 'dsc' else order_by
        if queue == 'inbound':
            qdirection = 1
        else:
            qdirection = 2

        num_items = session.get('mailq_num_items', 10)

        query = Session.query(MailQueueItem).filter(
                MailQueueItem.direction == qdirection).order_by(order_by)

        if server:
            query = query.filter(MailQueueItem.hostname == server.hostname)

        uquery = UserFilter(Session, c.user, query, model=MailQueueItem)
        query = uquery.filter()

        c.form = MailQueueProcessForm(request.POST, csrf_context=session)
        pages = paginate.Page(query, page=int(page), items_per_page=num_items)
        choices = [(str(item.id), item.id) for item in pages.items]
        session['queue_choices'] = choices
        session.save()

        c.page = paginate.Page(query, page=int(page),
                                items_per_page=num_items)
        return render('/status/mailq.html')
Example #44
0
    def delete_account_sigs(self, sigid):
        "Delete account signatures"
        sign = self._get_usrsign(sigid)
        if not sign:
            abort(404)

        c.form = SigForm(request.POST, sign, csrf_context=session)
        del c.form['signature_type']
        if request.POST and c.form.validate():
            user_id = sign.user_id
            user_name = sign.user.username
            files = []
            basedir = config.get('ms.signatures.base',
                                 '/etc/MailScanner/signatures')
            if sign.signature_type == 1:
                user = self._get_user(user_id)
                if user:
                    sigfile = os.path.join(basedir, 'users', user.username,
                                           'sig.txt')
                    files.append(sigfile)
            else:
                if sign.image:
                    imgfile = os.path.join(basedir, 'users', user.username,
                                           sign.image.name)
                    files.append(imgfile)
                sigfile = os.path.join(basedir, 'users', user.username,
                                       'sig.html')
                files.append(sigfile)
            Session.delete(sign)
            Session.commit()
            delete_sig.apply_async(args=[files], queue='msbackend')
            info = DELETEACCSIG_MSG % dict(u=user_name)
            audit_log(c.user.username, 4, info, request.host,
                      request.remote_addr, now())
            flash(_('The signature has been deleted'))
            redirect(url('account-detail', userid=user_id))
        c.sign = sign
        return render('/settings/account_deletesig.html')
Example #45
0
    def index(self, slave=None):
        if 'numbuilds' in request.GET:
            count = int(request.GET.getone('numbuilds'))
        else:
            count = 25

        if 'format' in request.GET:
            format = request.GET.getone('format')
        else:
            format = 'html'
        if format not in ('html', 'json'):
            abort(400, detail='Unsupported format: %s' % format)

        greedy = True
        if 'greedy' in request.GET:
            greedy = request.GET.getone('greedy')
            if greedy in ('false', 'False'):
                greedy = False

#        if slave is not None:
#            slave = slave[0]
        if 'slave' in request.GET:
            slave = request.GET.getall('slave')

        builds = GetHistoricBuilds(slave=slave, count=count, greedy=greedy)

        # Return a rendered template
        # or, return a json blob
        if format == "html":
            c.recent_builds = builds
            return render("/recent.mako")
        else:
            for b in builds:
                for k, v in b.items():
                    if isinstance(v, datetime.datetime):
                        v = times.UTC.localize(v)
                        b[k] = times.dt2ts(v)
            return self.jsonify(builds)
Example #46
0
 def create(self, request, response, execute=True):
     """ Read the GeoJSON feature collection from the request body and
         create new objects in the database. """
     if self.readonly:
         abort(403)
     content = request.environ['wsgi.input'].read(
         int(request.environ['CONTENT_LENGTH']))
     factory = lambda ob: GeoJSON.to_instance(ob)
     collection = loads(content, object_hook=factory)
     if not isinstance(collection, FeatureCollection):
         abort(400)
     objects = []
     for feature in collection.features:
         create = False
         obj = None
         if feature.id is not None:
             obj = self.Session.query(self.mapped_class).get(feature.id)
         if self.before_create is not None:
             self.before_create(request, feature, obj)
         if obj is None:
             obj = self.mapped_class()
             create = True
         self.__copy_attributes(feature, obj)
         if create:
             self.Session.add(obj)
         objects.append(obj)
     # We call flush, create the feature collection, and then commit. Commit
     # expires the session, so we create the feature collection before
     # commit to avoid SELECT queries in toFeature.
     if execute:
         self.Session.flush()
     collection = None
     if len(objects) > 0:
         collection = FeatureCollection([o.toFeature() for o in objects])
     if execute:
         self.Session.commit()
     response.status = 201
     return collection
Example #47
0
    def index(self):
        group_type = self._guess_group_type()

        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'for_view': True,
            'with_private': False
        }

        q = c.q = http_request.params.get('q', '')
        data_dict = {'all_fields': True, 'q': q}

        sort_by = c.sort_by_selected = http_request.params.get('sort')
        if sort_by:
            data_dict['sort'] = sort_by
        try:
            self._check_access('site_read', context)
        except NotAuthorized:
            abort(401, _('Not authorized to see this page'))

        # pass user info to context as needed to view private datasets of
        # orgs correctly
        if c.userobj:
            context['user_id'] = c.userobj.id
            context['user_is_admin'] = c.userobj.sysadmin

        # results = self._action('group_list_authz')(context, data_dict)
        results = self._action('group_list_authz')(context, {
            'all_fields': True,
            'q': q
        })
        c.page = h.Page(collection=results,
                        page=self._get_page_number(http_request.params),
                        url=h.pager_url,
                        items_per_page=21)
        return base.render(self._index_template(group_type))
Example #48
0
    def delete_domain_sigs(self, sigid):
        "Delete domain signature"
        sign = self._get_domsign(sigid)
        if not sign:
            abort(404)

        c.form = SigForm(request.POST, sign, csrf_context=session)
        del c.form['signature_type']
        if request.POST and c.form.validate():
            domain_id = sign.domain_id
            domain_name = sign.domain.name
            files = []
            basedir = config.get('ms.signatures.base',
                                 '/etc/MailScanner/signatures')
            if sign.signature_type == 1:
                domain = self._get_domain(domain_id)
                if domain:
                    sigfile = os.path.join(basedir, 'domains', domain.name,
                                           'sig.txt')
                    files.append(sigfile)
            else:
                if sign.image:
                    imgfile = os.path.join(basedir, 'domains', domain.name,
                                           sign.image.name)
                    files.append(imgfile)
                sigfile = os.path.join(basedir, 'domains', domain.name,
                                       'sig.html')
                files.append(sigfile)
            Session.delete(sign)
            Session.commit()
            delete_sig.apply_async(args=[files], queue='msbackend')
            info = DELETEDOMSIG_MSG % dict(d=domain_name)
            audit_log(c.user.username, 4, info, request.host,
                      request.remote_addr, now())
            flash(_('The signature has been deleted'))
            redirect(url('domain-settings-sigs', domainid=domain_id))
        c.sign = sign
        return render('/settings/domain_deletesig.html')
Example #49
0
def authenticate_form(func, *args, **kwargs):
    """Decorator for authenticating a form

    This decorator uses an authorization token stored in the client's
    session for prevention of certain Cross-site request forgery (CSRF)
    attacks (See
    http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
    information).

    For use with the ``webhelpers.html.secure_form`` helper functions.

    """
    request = get_pylons(args).request
    if authenticated_form(request.params):
        try:
            del request.POST[secure_form.token_key]
        except KeyError:
            del request.GET[secure_form.token_key]
        return func(*args, **kwargs)
    else:
        log.warn('Cross-site request forgery detected, request denied: %r '
                 'REMOTE_ADDR: %s' % (request, request.remote_addr))
        abort(403, detail=csrf_detected_message)
Example #50
0
    def deleteaddress(self, addressid):
        "Delete address"
        address = self._get_address(addressid)
        if not address:
            abort(404)

        c.form = AddressForm(request.POST, address, csrf_context=session)
        if request.POST and c.form.validate():
            user_id = address.user_id
            addr = address.address
            username = address.user.username
            Session.delete(address)
            Session.commit()
            update_serial.delay()
            info = ADDRDELETE_MSG % dict(a=addr, ac=username)
            audit_log(c.user.username, 4, info, request.host,
                      request.remote_addr, now())
            flash(_('The address has been deleted'))
            redirect(
                url(controller='accounts', action='detail', userid=user_id))
        c.id = addressid
        c.userid = address.user_id
        return render('/accounts/deleteaddress.html')
Example #51
0
    def data_integrity(self, filetype='html', redirect=False):
        if not h.auth.is_logged_in():
            abort(401)
        if not h.auth.is_admin():
            abort(403)

        school_q = Session.query(SchoolOfThought)
        c.schools = list(school_q)

        # Missing sep_dir
        c.missing_sep_dir = [
            school for school in c.schools if not getattr(school, "sep_dir")
        ]

        # Duplicates
        c.duplicate = []
        c.sorted_schools = sorted(c.schools, key=lambda school: school.label)
        for i in range(len(c.sorted_schools) - 1):
            if c.sorted_schools[i].label == c.sorted_schools[i + 1].label:
                c.duplicate.append(c.sorted_schools[i])
                c.duplicate.append(c.sorted_schools[i + 1])

        return render('school_of_thought/data_integrity.%s' % filetype)
Example #52
0
    def delete_relay(self, settingid):
        "Delete a mail relay"
        relay = self._get_setting(settingid)
        if not relay:
            abort(404)

        c.form = RelayForm(request.POST, relay, csrf_context=session)
        c.relayname = relay.address or relay.username
        c.relayid = relay.id
        c.orgid = relay.org_id
        if request.POST and c.form.validate():
            orgid = relay.organization_id
            try:
                Session.delete(relay)
                Session.commit()
                info = DELETERELAY_MSG % dict(r=c.relayname)
                audit_log(c.user.username, 4, info, request.host,
                          request.remote_addr, datetime.now())
                flash(_('The outbound settings have been deleted'))
            except:
                flash(_('The outbound settings could not be deleted'))
            redirect(url('org-detail', orgid=orgid))
        return render('/organizations/deleterelay.html')
Example #53
0
    def update_visualization_link(self, dataset_name):
        json_body = json.loads(http_request.body,
                               encoding=http_request.charset)
        try:
            dataset = DatasetService.get_dataset(dataset_name)
        except toolkit.ObjectNotFound:
            abort(404)

        view_param = json_body.get('view')
        request_view = 'chart' if view_param in ['table', 'column', 'line'
                                                 ] else view_param
        request_filters = json_body.get('filters')
        data = {}
        data['link'] = _link_to_dataset_with_filters(
            dataset_name, json.dumps(request_filters), view_param)
        query_builder = QueryBuilderFactory.get_query_builder(
            request_view, dataset)
        view = ViewFactory.get_view(request_view, query_builder)
        data['compatibles'] = view.get_compatibles(request_filters)

        http_response.headers['Content-type'] = 'application/json'
        self.session.close()
        return json.dumps(data)
Example #54
0
 def update(self, id):
     """PUT /users/id: Update an existing item"""
     body = request.environ['wsgi.input'].read()
     log.debug(body)
     param = json.loads(body)
     log.debug(param)
     try:
         result = User.update(id, param)
     except (IndexError, HTTPBadRequest):
         abort(400)
     except HTTPNotFound:
         abort(404)
     except HTTPConflict:
         abort(409)
     except HTTPInternalServerError:
         abort(500)
Example #55
0
    def upload_handle(self):
        bucket_id = BUCKET
        params = dict(request.params.items())
        stream = params.get('file')
        label = params.get('key')
        authorize('POST', BUCKET, label, c.userobj, self.ofs)
        if not label:
            abort(400, "No label")
        if not isinstance(stream, FieldStorage):
            abort(400, "No file stream.")
        del params['file']
        params['filename-original'] = stream.filename
        #params['_owner'] = c.userobj.name if c.userobj else ""
        params['uploaded-by'] = c.userobj.name if c.userobj else ""

        self.ofs.put_stream(bucket_id, label, stream.file, params)
        success_action_redirect = h.url_for('storage_upload_success',
                                            qualified=True,
                                            bucket=BUCKET,
                                            label=label)
        # Do not redirect here as it breaks js file uploads (get infinite loop
        # in FF and crash in Chrome)
        return self.success(label)
Example #56
0
    def __before__(self, action, **params):

        c.browser_language = self.browser_language

        identity = request.environ.get('repoze.who.identity')
        if identity is None:
            response.delete_cookie('userauthcookie')
            abort(401, _("You are not authenticated"))

        log.debug("getAuthFromIdentity in action %s" % action)
        if ';' in identity['repoze.who.userid']:
            self.userid, self.auth_cookie = identity['repoze.who.userid'].split(';', 1)
        else:
            self.userid = identity['repoze.who.userid']
            self.auth_cookie = None
        try:
            self.context = self.get_context({"user" :self.userid})
        except Exception as exx:
            log.error("linotp context lookup failed %r" % exx)
            response.delete_cookie('userauthcookie')
            abort(401, _("You are not authenticated"))

        copy_context_(self.context)
Example #57
0
    def delete_relay(self, settingid):
        "Delete a mail relay"
        relay = get_relay(settingid)
        if not relay:
            abort(404)

        c.relayname = relay.address or relay.username
        c.relayid = relay.id
        c.orgid = relay.org_id
        c.form = RelayForm(request.POST, relay, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            orgid = relay.org_id
            try:
                delete_relay(relay, c.user, request.host, request.remote_addr)
                msg = _('The outbound settings have been deleted')
                flash(msg)
                log.info(msg)
            except:
                msg = _('The outbound settings could not be deleted')
                flash(msg)
                log.info(msg)
            redirect(url('org-detail', orgid=orgid))
        return self.render('/organizations/deleterelay.html')
Example #58
0
    def wrapper(func, *args, **kwargs):
        """Decorator Wrapper function"""
        request = get_pylons(args).request
        if request.scheme.lower() == 'https':
            return func(*args, **kwargs)
        if request.method.upper() == 'POST':
            # don't allow POSTs (raises an exception)
            abort(405, headers=[('Allow', 'GET')])

        if url_or_callable is None:
            url = request.url
        elif callable(url_or_callable):
            url = url_or_callable()
        else:
            url = url_or_callable
        # Ensure an https scheme, which also needs a host
        parts = urlparse.urlparse(url)
        url = urlparse.urlunparse(('https', parts[1] or request.host) +
                                  parts[2:])

        log.debug('Redirecting non-https request: %s to: %s',
                  request.path_info, url)
        redirect(url)
Example #59
0
 def show(self):
     """
     Force an error message.
     """
     status = request.GET.get('force_status')
     if status is None:
         raise abort(404)
     data = {
         'hide_code': 'hide_code' in request.GET,
         'hide_notify': 'hide_notify' in request.GET,
         'error_code': int(status),
         'error_message': ERROR_MESSAGES.get(int(status)),
     }
     return render("/error/http.html", data)
Example #60
0
    def save(self):
        """Update OLD Home Page with newly altered data.
        
        """

        # Get the homepage from the model
        homepage_q = meta.Session.query(model.Page).filter(
            model.Page.name==u'home')
        homepage = homepage_q.first()
        if homepage is None:
            abort(404)
            
        homepage.name = h.NFD(self.form_result['name'])
        homepage.heading = h.NFD(self.form_result['heading'])
        homepage.content = h.NFD(self.form_result['content'])
        
        # Update the data
        meta.Session.commit()

        # Issue an HTTP redirect
        response.status_int = 302
        response.headers['location'] = url(controller='home', action='index')
        return "Moved temporarily"