Beispiel #1
0
def render_notifications():
    current_user = get_current_user()
    notifications = [notif.mark_read() for notif in current_user.notifications]
    db.session.commit()
    return render_template(
        'pages/list.html',
        page_data=NotificationListTableData(
            get_current_user(),
            [notif.mark_read() for notif in current_user.notifications]))
Beispiel #2
0
def resultados(password):
    current_user = get_current_user()

    password_compare = os.environ["PASSWORD_RESULTS"] if os.environ.has_key(
        "PASSWORD_RESULTS") else "kyb@1234"
    if password == password_compare:
        users = get_all_users()
        top_bands, len_bands = get_top_bands(sort=True)
        funcionalidades_fa = get_answers_and_counters_from_question(
            ['fa-funcionalidades'])
        funcionalidades_musico = get_answers_and_counters_from_question(
            ['musico-funcionalidades'])

        newsletters = get_all_newsletters()

        return render_template('resultados_gerais.html',
                               current_user=current_user,
                               users=users,
                               funcionalidades_fa=funcionalidades_fa,
                               funcionalidades_musico=funcionalidades_musico,
                               bands=top_bands,
                               len_bands=len_bands,
                               newsletters=newsletters)
    else:
        abort(404)
def assinou():
    current_user = get_current_user()
    all_users = get_all_users_by_datetime()
    ultimos_5 = all_users[:5]
    maximo = get_maximo_meta()

    return render_template("assinou.html", current_user=current_user, all_users=all_users, maximo=maximo, ultimos_5=ultimos_5)
Beispiel #4
0
 def get_answers(self):
     query = Answer.all()
     cookies = h.get_default_cookies(self)
     current_user = h.get_current_user(cookies)
     query.filter("user =", current_user)
     answers = query.fetch(1000)
     return answers
Beispiel #5
0
def render_upload_sample_group():
    try:
        current_user = get_current_user()
        if request.method == 'POST':
            files = request.files.getlist('files')
            filenames = [
                os.path.join(UPLOADDIR, secure_filename(file.filename))
                for file in files
            ]
            [file.save(filename) for file, filename in zip(files, filenames)]
            metadata = process_input_dict(request.form.to_dict(), True)
            workflow_data = create_sample_creation_workflow(
                current_user, filenames, metadata)
            metadata['samples'] = [
                get_sample(current_user, sample_id)
                for sample_id in workflow_data['output_ids']
            ]
            sample_group = create_sample_group(current_user, metadata)
            job = start_job(workflow_data['workflow'], workflow_data['job'],
                            current_user, 'upload')
            update_sample_group(current_user, sample_group,
                                {'upload_job_id': job.id})
            return redirect(
                url_for('sample_groups.render_sample_group',
                        sample_group_id=sample_group.id))
        return render_template('pages/create.html',
                               page_data=SampleCreateFormData(current_user))
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #6
0
def render_create_collection():
    try:
        current_user = get_current_user()
        if request.method == 'POST':
            form_data = process_input_dict(request.form.to_dict(), True)
            samples = [
                dt.samples.get_sample(current_user, sample_id)
                for sample_id in request.form.getlist('sample_ids')
            ]
            if 'sample_ids' in form_data:
                del form_data['sample_ids']
            sort_by = form_data['sort_by']
            del form_data['sort_by']
            collection = dt.wrappers.collections.create_collection(
                current_user, samples, form_data, sort_by=sort_by)
            return redirect(
                url_for('collections.render_collection',
                        collection_id=collection.id))
        if request.method == 'GET':
            if request.args.get('sample_ids', ''):
                sample_ids = [
                    int(token) for token in request.args.get(
                        'sample_ids').strip('"').split(',')
                ]
                selected_samples = Sample.query.filter(
                    Sample.id.in_(sample_ids)).all()
            else:
                selected_samples = None
            return render_template('pages/create.html',
                                   page_data=CollectionCreateFormData(
                                       current_user, selected_samples))
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #7
0
def render_analysis(analysis_id=None):
    try:
        current_user = get_current_user()
        return render_template('pages/analysis_entry.html',
                               page_data=AnalysisPageData(current_user, get_analysis(current_user, analysis_id)))
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #8
0
def render_create_user_group():
    try:
        current_user = get_current_user()
        if request.method == 'POST':
            data = {
                'admin_ids':
                [int(val) for val in request.form.getlist('admin_ids')],
                'member_ids':
                [int(val) for val in request.form.getlist('member_ids')],
                'name':
                request.form.get('name'),
                'description':
                request.form.get('description')
            }
            user_group = create_user_group(current_user, data)
            return redirect(
                url_for('user_groups.render_user_group',
                        user_group_id=user_group.id))
        if request.method == 'GET':
            selected_user_ids = {int(token) for token in request.args.get('sample_ids').strip('"').split(',')} \
                if request.args.get('user_ids', '') else {}
            selected_users = get_all_read_permitted_records(current_user, User)
            return render_template('pages/create.html',
                                   page_data=UserGroupCreateFormData(
                                       current_user, selected_users))
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #9
0
def get_sample_group(sample_group_id=None):
    try:
        user = get_current_user()
        sample_group = dt.sample_groups.get_sample_group(user, sample_group_id)
        if request.method == 'GET':
            return jsonify({
                **sample_group.to_dict(), 'is_write_permitted':
                dt.users.is_write_permitted(user, sample_group)
            })
        if request.method == 'DELETE':
            samples_to_delete = [
                sample for sample in sample_group.samples
                if len(sample.sample_groups) < 2
            ]
            data = dt.sample_groups.delete_sample_group(user, sample_group)
            sample_messages = []
            for sample in samples_to_delete:
                try:
                    sample_messages.append(
                        dt.samples.delete_sample(user, sample)['message'])
                except AuthException:
                    pass
            messages = [data['message']] + sample_messages
            return jsonify({'messages': messages})
        if request.method == 'POST':
            return jsonify(
                dt.sample_groups.update_sample_group(
                    user, sample_group,
                    request.get_json(force=True)).to_dict())
    except Exception as e:
        return handle_exception(e)
Beispiel #10
0
def render_analysis_list():
    try:
        current_user = get_current_user()
        return render_template('pages/list.html',
                               page_data=ListTableData(current_user, get_analyses(current_user), 'Analyses'))
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #11
0
def upload_external_file():
    try:
        user = get_current_user()
        # for request from MATLAB client that doesn't support multipart/form-data
        # file is base64 encoded.
        new_data = {}
        try:
            new_data.update(process_input_dict(request.get_json()))
        except:
            new_data.update(process_input_dict(request.form))
        if 'file' not in new_data and 'file' not in request.files:
            raise ValueError('No file uploaded')
        filename = os.path.join(UPLOADDIR, secure_filename(str(uuid.uuid4())))
        if 'file' in request.files:
            if request.files['file'].filename == '':
                raise ValueError('No file uploaded')
            request.files['file'].save(filename)
        else:
            with open(filename, 'wb') as file:
                collection_file_data = base64.b64decode(
                    bytes(new_data['file'], 'utf-8'))
                file.write(collection_file_data)
                del new_data['file']
        external_file = dt.external_files.upload_external_file(
            user, filename, new_data)
        return jsonify(external_file.to_dict())
    except Exception as e:
        return handle_exception(e)
Beispiel #12
0
      def post(self):
        cookies = h.get_default_cookies(self)
        if '_pvk' not in cookies or (cookies['_pvk'] == None or cookies['_pvk'] == ''):
            new_session_key = str(datetime.datetime.utcnow()).replace(' ', '') + '-' + str(random.getrandbits(50))
            cookies['_pvk'] = new_session_key

        previous_page_view_for_session = db.GqlQuery("SELECT * FROM PageView WHERE session_id = :1 ORDER BY created_at DESC", cookies['_pvk']).get()

        page_view = PageView()
        current_user = h.get_current_user(cookies)
        
        if current_user != None:
              page_view.user = current_user

        page_view.url = self.request.get('u')
        page_view.normalized_url = self.request.get('u')[:500] # TODO actually normalize URLs according to some logic (e.g. stripping out fb params)
        page_view.referrer = self.request.get('referrer')
        page_view.session_id = cookies['_pvk']
        page_view.ip_address = self.request.remote_addr
        
        
        try: 
          page_view.user_agent = self.request.headers['User-Agent'][:500]
        except:
          page_view.user_agent = None
        
        if previous_page_view_for_session:
            page_view.session_order = previous_page_view_for_session.session_order + 1
        else:
            page_view.session_order = 0
        
        page_view.put()

        self.response.out.write('{status: \'ok\'}')
Beispiel #13
0
 def post(self):
     cookies = h.get_default_cookies(self)
     current_user = h.get_current_user(cookies)
     
   	if current_user != None and '_pvk' in cookies and cookies['_pvk'] != None and cookies['_pvk'] != '':
         unlinked_result_views = ResultView.gql("WHERE session_id = :1 AND user = NULL", cookies['_pvk']).fetch(5)
         for result_view in unlinked_result_views:
             result_view.user = current_user
             if current_user.fb_user_id != None:
                 result_view.fb_user_id = current_user.fb_user_id
             
             # Create a "backdated" version for this query, because the user probably made the query while 
             # logged out, and it's worthwile knowing that that happened
             if result_view.query_string != None and result_view.query_string != '':
                 query = Query(query_string = result_view.query_string, referrer = self.request.referer, url = "__ARTIFICIALLY_CREATED_FOR_USER__")
                 
                 query.user = current_user
                 if current_user.fb_user_id != None:
                     query.fb_user_id = current_user.fb_user_id
                 if '_pvk' in cookies and cookies['_pvk'] != None and cookies['_pvk'] != '':
                     query.session_id = cookies['_pvk']
                 
                 query.put()
             
                 result_view.query = query
                 result_view.put()
                 fb_post_id = QueryFacebookWallpostHelper.postToWallIfNecessary(current_user, result_view, query, result_view.image_url)
             
             else:
                 result_view.put()
     
     self.response.out.write('{status: \'ok\'}')
Beispiel #14
0
def render_home():
    try:
        current_user = get_current_user()
        page_data = DashboardPageData(current_user)
        return render_template('pages/home.html', page_data=page_data)
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #15
0
def submit_job():
    try:
        user = get_current_user()
        body = request.get_json(force=True)
        return jsonify(dt.jobserver_control.start_job(body['workflow'], body['job'], user, 'analysis').to_dict())
    except Exception as e:
        return handle_exception(e)
Beispiel #16
0
def loja_virtual():
    current_user = get_current_user()
    produtos_section = True if request.args.get('produtos-section') else False
    dark = True if request.args.get('dark') else False

    return render_template('loja_virtual.html', current_user=current_user, formulario_pag_seguro=formulario_pag_seguro,
        range_quantidade=range(2, 10), range_tamanhos=range_tamanhos, produtos_section=produtos_section, dark=dark,
        camisas=BANDAS_CAMISAS)
Beispiel #17
0
def unlike():
    slug = request.form['band']
    user = get_current_user()
    if user:
        unlike_band(slug, user)
        return 'unliked'
    else:
        return "Ninguem logado"
Beispiel #18
0
def unlike():
    slug = request.form['band']
    user = get_current_user()
    if user:
        unlike_band(slug, user)
        return 'unliked'
    else:
        return "Ninguem logado"
Beispiel #19
0
def add_band():
    name = request.form['band']
    user = get_current_user()
    if user:
        band = get_or_create_band({'slug': get_slug(name), 'name': name, 'user': user})
        return "%s\n%s" % (band.name, band.slug)
    else:
        return "Ninguem logado"
Beispiel #20
0
 def wrapper(handler):
     user = get_current_user()
     if user:
         context = {'error': 'You are already logged in!'}
         return handler.response.out.write(
             render_template('error_general.html', context))
     else:
         return f(handler)
Beispiel #21
0
def minhas_bandas():
    current_user = get_current_user()
    bands = random_top_bands(user=current_user)
    bands_user = get_user_bands(user=current_user)

    resp = make_response(render_template('minhas_bandas.html', current_user=current_user, bands=bands, bands_user=bands_user))
    set_cookie_login(resp, oauth_token=get_facebook_oauth_token()[0])
    return resp
Beispiel #22
0
def related_bands(slug):
    related_bands = get_related_bands(get_band(slug), max=10, user=get_current_user())
    result = ""

    for slug in related_bands:
        result += slug + "\n"
        result += get_band(slug).name + "\n"

    return result
def meta(maximo):
    current_user = get_current_user()
    all_users = get_all_users_by_datetime()
    if (current_user.name.startswith("Bernardo") and current_user.name.endswith("Ainbinder")) or\
        (current_user.name.startswith("Guilherme") and current_user.name.endswith("Bruzzi")):
        set_maximo_meta(maximo)
    else:
        maximo = get_maximo_meta()
    return render_template("meta.html", current_user=current_user, all_users=all_users, maximo=maximo)
Beispiel #24
0
def render_user_group_list():
    try:
        current_user = get_current_user()
        return render_template('pages/list.html',
                               page_data=ListTableData(
                                   current_user, get_user_groups(current_user),
                                   'User Groups'))
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #25
0
def render_user_profile(user_id=None):
    try:
        current_user = get_current_user()
        return render_template('pages/user_entry.html',
                               page_data=UserPageData(
                                   current_user,
                                   get_user(current_user, user_id)))
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #26
0
def list_invitations():
    try:
        current_user = helpers.get_current_user()
        return jsonify([
            invitation.to_dict()
            for invitation in dt.users.get_invitations(current_user)
        ])
    except Exception as e:
        return handle_exception(e)
Beispiel #27
0
 def wrapper(handler):
     user = get_current_user()
     if user:
         context = {
             'error':'You are already logged in!'
         }
         return handler.response.out.write(render_template('error_general.html', context))
     else:
         return f(handler)
Beispiel #28
0
def list_users():
    try:
        user = get_current_user()
        if request.method == 'POST':
            data = request.get_json(force=True)
            return jsonify(dt.users.create_user(user, data).to_dict())
        return jsonify([target_user.to_dict() for target_user in dt.users.get_users(user)])
    except Exception as e:
        return handle_exception(e)
Beispiel #29
0
def render_workflow(workflow_id=None):
    try:
        current_user = get_current_user()
        return render_template('pages/workflow_entry.html',
                               page_data=WorkflowPageData(
                                   current_user,
                                   get_workflow(current_user, workflow_id)))
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #30
0
 def add_answer(self, atext, qkey):
     answer = Answer()
     cookies = h.get_default_cookies(self)
     current_user = h.get_current_user(cookies)
     if current_user:
         answer.user = current_user
     answer.atext = atext
     answer.qkey = db.Key(qkey)
     answer.put()
     return answer
Beispiel #31
0
def toggle_memes_only(message):
    user = get_current_user(message.from_user.id)
    if user.is_meme_only:
        user.is_meme_only = False
        text_message = 'Режим "смешных картинок" деактивирован!\nТеперь ты будешь получать случайные посты со всего Реддита.'
    else:
        user.is_meme_only = True
        text_message = 'Режим "смешных картинок" активирован!\nТеперь ты будешь получать только посты со смешнявками.'
    session.commit()
    bot.send_message(message.chat.id, text_message)
Beispiel #32
0
def render_external_file(external_file_id=None):
    try:
        current_user = get_current_user()
        return render_template('pages/external_file_entry.html',
                               page_data=ExternalFilePageData(
                                   current_user,
                                   dt.external_files.get_external_file(
                                       current_user, external_file_id)))
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #33
0
def list_user_groups():
    try:
        user = get_current_user()
        if request.method == 'GET':
            return jsonify([user_group.to_dict() for user_group in dt.user_groups.get_user_groups(user)])
        if request.method == 'POST':
            data = request.get_json(force=True)
            return jsonify(dt.user_groups.create_user_group(user, data).to_dict())
    except Exception as e:
        return handle_exception(e)
Beispiel #34
0
def los_bife():
    current_user = get_current_user()

    produtos_section = True if request.args.get('produtos-section') else False
    dark = True if request.args.get('dark') else False
    return render_template('venda_los_bife.html', current_user=current_user, formulario_pag_seguro=formulario_pag_seguro,
        range_quantidade=range(2, 10), range_tamanhos=range_tamanhos, produtos_section=produtos_section, dark=dark,
        camisas=[{ "tipo": "amarela", "preco": "35,00" },
                 { "tipo": "vermelha", "preco": "35,00" },
                 { "tipo": "azul", "preco": "35,00" }],
        sem_estoque=sem_estoque)
Beispiel #35
0
def get_invitation(invitation_id=None):
    try:
        current_user = helpers.get_current_user()
        invitation = dt.users.get_invitation(current_user, invitation_id)
        if request.method == 'DELETE':
            return jsonify(dt.users.delete_invitation(current_user,
                                                      invitation))
        else:
            return jsonify(invitation.to_dict())
    except Exception as e:
        handle_exception(e)
Beispiel #36
0
def render_external_file_list():
    try:
        current_user = get_current_user()
        return render_template(
            'pages/list.html',
            page_data=ListTableData(
                current_user,
                dt.external_files.get_external_files(current_user),
                'External File Records'))
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #37
0
def related_bands(slug):
    related_bands = get_related_bands(get_band(slug),
                                      max=10,
                                      user=get_current_user())
    result = ""

    for slug in related_bands:
        result += slug + "\n"
        result += get_band(slug).name + "\n"

    return result
def register_place_hook():
    """Hook to take the place from the view arguments and set it in context globals.

    The place set in context globals is used by some legacy code.
    """
    if request.view_args and 'place' in request.view_args:
        g.place = request.view_args['place']

        # initialize the permissions
        user = h.get_current_user()
        if user:
            g.permissions = h.get_permissions(user, g.place)
Beispiel #39
0
def render_user_group(user_group_id=None):
    try:
        current_user = get_current_user()
        user_group = get_user_group(current_user, user_group_id)
        if request.method == 'DELETE':
            delete_user_group(current_user, user_group)
            return redirect(url_for('user_groups.render_user_group_list'))
        return render_template('pages/user_group_entry.html',
                               page_data=UserGroupPageData(
                                   current_user, user_group))
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #40
0
def list_sample_groups():
    try:
        current_user = get_current_user()
        if request.method == 'POST':
            new_data = process_input_dict(request.get_json(force=True))
            if 'sample_ids' in new_data:
                new_data['samples'] = [
                    dt.samples.get_sample(current_user, sample_id)
                    for sample_id in new_data['sample_ids']
                ]
                del new_data['sample_ids']
            return jsonify(
                dt.sample_groups.create_sample_group(current_user,
                                                     new_data).to_dict())

        return jsonify([
            sample_group.to_dict() for sample_group in
            dt.sample_groups.get_sample_groups(get_current_user())
        ])
    except Exception as e:
        return handle_exception(e)
Beispiel #41
0
def register_place_hook():
    """Hook to take the place from the view arguments and set it in context globals.

    The place set in context globals is used by some legacy code.
    """
    if request.view_args and 'place' in request.view_args:
        g.place = request.view_args['place']

        # initialize the permissions
        user = h.get_current_user()
        if user:
            g.permissions = h.get_permissions(user, g.place)
Beispiel #42
0
def render_create_workflow():
    try:
        current_user = get_current_user()
        if request.method == 'POST':
            workflow = create_workflow(
                current_user, process_input_dict(request.form.to_dict(), True))
            return redirect(
                url_for('workflows.render_workflow', workflow_id=workflow.id))
        return render_template('pages/create.html',
                               page_data=WorkflowCreateFormData(current_user))
    except Exception as e:
        return handle_exception_browser(e)
Beispiel #43
0
def add_band():
    name = request.form['band']
    user = get_current_user()
    if user:
        band = get_or_create_band({
            'slug': get_slug(name),
            'name': name,
            'user': user
        })
        return "%s\n%s" % (band.name, band.slug)
    else:
        return "Ninguem logado"
Beispiel #44
0
def minhas_bandas():
    current_user = get_current_user()
    bands = random_top_bands(user=current_user)
    bands_user = get_user_bands(user=current_user)

    resp = make_response(
        render_template('minhas_bandas.html',
                        current_user=current_user,
                        bands=bands,
                        bands_user=bands_user))
    set_cookie_login(resp, oauth_token=get_facebook_oauth_token()[0])
    return resp
Beispiel #45
0
def add_question(qtype, qtext, hint, img, handler):
    question = Question()
    cookies = h.get_default_cookies(handler)
    current_user = h.get_current_user(cookies)
    if current_user:
        question.user = current_user
    question.qtype = int(qtype)
    question.qtext = qtext
    question.hint = hint
    question.img = img
    question.status = 1
    question.put()
    return question
Beispiel #46
0
    def post(self):
        logging.info("***rvlh")
        cookies = h.get_default_cookies(self)
        current_user = h.get_current_user(cookies)
        result_view = ResultView()
      	result_view.source = self.request.get('src')
      	result_view.referrer = self.request.get('referrer')
      	result_view.url = self.request.get('u')
        result_view.ip_address = self.request.remote_addr
        result_view.image_url = self.request.get('image_url')
        result_view.query_string = self.request.get('q')
      	#logging.info(" ".join((result_view.source, result_view.referrer, result_view.url, result_view.ip_address,
        #                       result_view.image_url, result_view.query_string)))
      	if '_pvk' in cookies and cookies['_pvk'] != None and cookies['_pvk'] != '':
            result_view.session_id = cookies['_pvk']
        
        if current_user != None:
            result_view.user = current_user
            if current_user.fb_user_id != None:
                result_view.fb_user_id = current_user.fb_user_id
                
            query = Query.gql(
                "WHERE user = :1 AND query_string = :2 ORDER BY created_at DESC", 
                current_user.key(), 
                self.request.get('q')).get()

            if query != None:
                result_view.query = query

        result_view.put()
        
        # Post to facebook wall for the query if the query hasn't already posted to wall
        if current_user != None and query != None and query.fb_wall_post_id == None:
            logging.info("***Posting")
            image_url = self.request.get('image_url')
            if not image_url:
                from google.appengine.api import urlfetch
                from django.utils import simplejson
                q = 'site:'+result_view.url+" "+result_view.query_string
                ue_query = urllib.quote_plus(q)
                url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q='\
                      +ue_query+'&key='\
                      +h.cfg['gs_api_key']
                result = urlfetch.fetch(url)
                o = simplejson.loads(result.content)
                image_url = o['responseData']['results'][0]['tbUrl']
            fb_post_id = QueryFacebookWallpostHelper.postToWallIfNecessary(current_user, result_view, query, image_url)
            self.response.out.write('{status: \'ok\', fb_wall_post_id: \'%s\', result_view_key: \'%s\'}' % (fb_post_id, str(result_view.key())))
        else:
            # logging.info("***NoPost : "+current_user+" "+query+" "+query.fb_wall_post_id)
            self.response.out.write('{status: \'ok\', result_view_key: \'%s\', result_view_has_user: \'%s\'}' % (str(result_view.key()), str(current_user != None)))
Beispiel #47
0
def cadastro():
    current_user = get_current_user()
    data = request.form

    if request.method == 'POST':
        if validate_answers(data):
            set_user_tipo(current_user, data["musico-ou-fa"])

            if data["banda"]:
                get_or_create_band({"name": data["banda"], "musician": current_user})

            return redirect(url_for('minhas_bandas'))

    return render_template('cadastro.html', current_user=current_user, main_questions=MAIN_QUESTIONS, post_data=data)
Beispiel #48
0
def bandas_locais():
    minhas_bandas_shows = []

    current_user = get_current_user()
    current_city = current_user.city if current_user and current_user.city else "Rio de Janeiro"

    shows_locais = get_shows_from_bands_by_city(city=current_city)
    for show_local in shows_locais:
        main_artist = show_local.artists[0]
        minhas_bandas_shows.append((main_artist, [show_local]))

    return render_template("bandas_locais.html", minhas_bandas_shows=minhas_bandas_shows,
        current_user=current_user,
        notas=range(11), BANDAS_CAMISAS=BANDAS_CAMISAS, formulario_pag_seguro=formulario_pag_seguro)
Beispiel #49
0
    def f(key, *a, **kw):
        place = Place.find(key)
        if not place:
            abort(404)
        user = h.get_current_user()
        if not user:
            return render_template("permission_denied.html")

        perms = get_permissions(user, place)
        # Put permissions in context globals, so that it can be added
        # to the template from helpers.py
        g.permissions = perms
        if permission and permission not in perms:
            return render_template("permission_denied.html")
        
        return func(place, *a, **kw)
Beispiel #50
0
    def get(self):
        c = h.context()
        s = self.request.get("s")
        c["s"] = s
        c["data"] = xrange(6)
        r = list()
        r += [[0, 0]]
        r += [[253, 0]]
        r += [[506, 0]]
        r += [[0, 253]]
        r += [[253, 253]]
        r += [[506, 253]]
        c["rects"] = r
        c["stash_items"] = xrange(7)
        cookies = h.get_default_cookies(self)
        u = h.get_current_user(cookies)
        if u:
            c["uid"] = u.fb_user_id

        # get some appropriate questions
        query = Question.all()
        query.filter("qtype =", 1).filter("status =", 1)
        questions = query.fetch(1000)
        building = list()
        for o in questions:
            d = dict()
            # d['qtype'] = o.qtype
            d["key"] = str(o.key())
            d["qtext"] = o.qtext
            d["hint"] = o.hint
            d["img"] = str(o.img.key())
            # d['status'] = o.status
            # d['created_at'] = str(o.created_at)
            building += [d]
        c["questions"] = simplejson.dumps(building)

        answers = self.get_answers()
        building = list()
        for o in answers:
            d = dict()
            d["key"] = str(o.key())
            d["atext"] = o.atext
            d["qkey"] = str(o.qkey)
            building += [d]
        c["answers"] = simplejson.dumps(building)

        h.render_out(self, "questions.tplt", c)
Beispiel #51
0
def resultados(password):
    current_user = get_current_user()

    password_compare = os.environ["PASSWORD_RESULTS"] if os.environ.has_key("PASSWORD_RESULTS") else "kyb@1234"
    if password == password_compare:
        users = get_all_users()
        top_bands, len_bands = get_top_bands(sort=True)
        funcionalidades_fa = get_answers_and_counters_from_question(['fa-funcionalidades'])
        funcionalidades_musico = get_answers_and_counters_from_question(['musico-funcionalidades'])

        newsletters = get_all_newsletters()

        return render_template('resultados_gerais.html', current_user=current_user, users=users,
            funcionalidades_fa=funcionalidades_fa, funcionalidades_musico=funcionalidades_musico,
            bands=top_bands, len_bands=len_bands, newsletters=newsletters)
    else:
        abort(404)
        def wrapped(*a, **kw):
            user = h.get_current_user()
            if not user:
                return render_template("permission_denied.html")

            # Find the current place from the view args
            # or use the top-level place
            place = request.view_args.get("place") or Place.get_toplevel_place()

            perms = h.get_permissions(user, place)
            # Put permissions in context globals, so that it can be added
            # to the template from helpers.py
            g.permissions = perms
            if permission and not h.has_permission(permission):
                return render_template("permission_denied.html")

            return f(*a, **kw)
Beispiel #53
0
    def post(self):
        cookies = h.get_default_cookies(self)
        current_user = h.get_current_user(cookies)
        query = Query(query_string = self.request.get('q'))
        
      	query.referrer = self.request.get('referrer')
      	query.url = self.request.get('u')
        query.ip_address = self.request.remote_addr
        if current_user != None:
            query.user = current_user
            if current_user.fb_user_id != None:
                query.fb_user_id = current_user.fb_user_id

        if '_pvk' in cookies and cookies['_pvk'] != None and cookies['_pvk'] != '':
            query.session_id = cookies['_pvk']
        
        query.put()
        self.response.out.write('{status: \'ok\'}')
Beispiel #54
0
 def get(self):
   arg_method = self.request.get('method')
   user = get_current_user()
   if user:
       grab_collections(user)
   
   templ_vars = { 'user':user }
   if not arg_method:
     return self.response.out.write(render_template('root.html', templ_vars))
   
   if arg_method == 'delete':
     arg_what = self.request.get('what')
     if not arg_what:
       return self.request.out.write('no what specified.')
     
     if arg_what == 'users':
       all_users = User.all()
       for user in all_users:
         user.delete()
       return self.redirect('/')
       
     if arg_what == 'collections':
       all_colls = MovieCollection.all()
       for col in all_colls:
         col.delete()
       return self.redirect('/')
     
     if arg_what == 'movies':
       movies = Movie.all()
       for movie in movies:
         movie.delete()
       return self.redirect('/')
     
     if arg_what == 'user_session':
         get_current_session().terminate()
         return self.redirect('/')
     return self.response.out.write(' no valid what')
   
   return self.response.out.write(' no valid method')
def index():
    current_user = get_current_user()
    if current_user:
        return redirect(url_for('assinou'))

    msg = session['msg'] if 'msg' in session else None

    form = get_form()

    if request.method == 'GET' and not msg and not isinstance(form, UserCaptchaForm):
        return pagina_principal()

    if msg:
        del session['msg']

    if request.method == 'POST':
        incr_redis_count(request)
        name = request.form.get("name")
        email = request.form.get("email")
        celular = request.form.get("celular")
        bairro = request.form.get("bairro")
        if form.validate():
            assinar_com_dados(dados={"name": name, "email": email, "bairro": bairro, "celular": celular})
            return redirect(url_for('assinou'))
        else:
            if not name or not email:
                session['msg'] = u'Os campos "nome" e "email" são obrigatórios.'
            elif hasattr(form, "captcha") and len(form.captcha.errors) > 0:
                session['msg'] = u'Preencha corretamente o campo "texto da imagem".'
            elif email and len(form.email.errors) > 0:
                session['msg'] = u'Preencha um email válido.'
            else:
                session['msg'] = u'Preencha corretamente os campos abaixo.'

            return redirect(url_for('index'))

    return render_template("index.html", BAIRROS=BAIRROS, msg=msg, form=form)
Beispiel #56
0
def novo():
    if has_cookie_login(request) and not user_logged():
        make_login(oauth_token=get_cookie_login(request))

    current_user = get_current_user()
    current_city = current_user.city if current_user and current_user.city else "Rio de Janeiro"

    minhas_bandas_shows = []
    if current_user:
        minhas_bandas = get_user_bands(user=current_user)

        if request.args.get('band'):
            minhas_bandas.insert(0, get_band(slug=request.args.get('band')))

        minhas_bandas_shows.extend(get_shows_from_bands(minhas_bandas, 1, city=current_city))
    else:
        top_bands = [
                        get_band("legiao-urbana"),
                        get_band("the-beatles"),
                        get_band("linkin-park"),
                        get_band("queen"),
                        get_band("guns-n-roses")
        ]

        if request.args.get('band'):
            top_bands.insert(0, get_band(slug=request.args.get('band')))

        minhas_bandas_shows = get_shows_from_bands(top_bands, 1, city=current_city, force_to_include_band=True)
        los_bife_band = get_band(slug="los-bife")
        minhas_bandas_shows.append((los_bife_band, los_bife_band.shows[:1]))



    return render_template("novo.html", current_user=current_user,
        minhas_bandas_shows=minhas_bandas_shows, notas=range(11), BANDAS_CAMISAS=BANDAS_CAMISAS,
        formulario_pag_seguro=formulario_pag_seguro, range_tamanhos=range_tamanhos)
Beispiel #57
0
 def wrapper(handler):
     user = get_current_user()
     if user:
         return f(handler, user)
     else:
         return f
Beispiel #58
0
def before_request():
    g.user = get_current_user()
Beispiel #59
0
 def get(self):
     user = get_current_user()
     if user:
         return self.redirect()
     else:
         return self.response.out.write(render_template('signup.html', {}))
Beispiel #60
0
 def load_current_user():
     g.user = get_current_user()