def global_template_context(): if current_user.is_authenticated(): if (current_user.email_addr == current_user.name or current_user.email_addr == "None"): flash(lazy_gettext("Please update your e-mail address in your profile page," " right now it is empty!"), 'error') # Announcement sections if app.config.get('ANNOUNCEMENT'): announcement = app.config['ANNOUNCEMENT'] if current_user.is_authenticated(): for key in announcement.keys(): if key == 'admin' and current_user.admin: flash(announcement[key], 'info') if key == 'owner' and len(current_user.apps) != 0: flash(announcement[key], 'info') if key == 'user': flash(announcement[key], 'info') return dict( brand=app.config['BRAND'], title=app.config['TITLE'], logo=app.config['LOGO'], copyright=app.config['COPYRIGHT'], description=app.config['DESCRIPTION'], terms_of_use=app.config['TERMSOFUSE'], data_use=app.config['DATAUSE'], enforce_privacy=app.config['ENFORCE_PRIVACY'], version=pybossa.__version__, current_user=current_user)
def global_template_context(): if current_user.is_authenticated(): if (current_user.email_addr == current_user.name or current_user.email_addr == "None"): flash( lazy_gettext( "Please update your e-mail address in your profile page," " right now it is empty!"), 'error') # Announcement sections if app.config.get('ANNOUNCEMENT'): announcement = app.config['ANNOUNCEMENT'] if current_user.is_authenticated(): for key in announcement.keys(): if key == 'admin' and current_user.admin: flash(announcement[key], 'info') if key == 'owner' and len(current_user.apps) != 0: flash(announcement[key], 'info') if key == 'user': flash(announcement[key], 'info') return dict(brand=app.config['BRAND'], title=app.config['TITLE'], logo=app.config['LOGO'], copyright=app.config['COPYRIGHT'], description=app.config['DESCRIPTION'], terms_of_use=app.config['TERMSOFUSE'], data_use=app.config['DATAUSE'], enforce_privacy=app.config['ENFORCE_PRIVACY'], version=pybossa.__version__, current_user=current_user)
def global_template_context(): if current_user.is_authenticated(): if current_user.email_addr == current_user.name or current_user.email_addr == "None": flash( lazy_gettext("Please update your e-mail address in your profile page," " right now it is empty!"), "error", ) # Announcement sections if app.config.get("ANNOUNCEMENT"): announcement = app.config["ANNOUNCEMENT"] if current_user.is_authenticated(): for key in announcement.keys(): if key == "admin" and current_user.admin: flash(announcement[key], "info") if key == "owner" and len(current_user.apps) != 0: flash(announcement[key], "info") if key == "user": flash(announcement[key], "info") return dict( brand=app.config["BRAND"], title=app.config["TITLE"], logo=app.config["LOGO"], copyright=app.config["COPYRIGHT"], description=app.config["DESCRIPTION"], terms_of_use=app.config["TERMSOFUSE"], data_use=app.config["DATAUSE"], enforce_privacy=app.config["ENFORCE_PRIVACY"], version=pybossa.__version__, current_user=current_user, )
def tickets(): if app.config.get("FULL_TICKETS", False): if not (current_user.is_authenticated() and current_user.tickets.count()): return redirect(url_for("tickets_choose")) form = ChoosePrepayTicketsForm(request.form) form.count.values = range(1, TicketType.Prepay.limit + 1) if request.method == "POST" and form.validate(): session["basket"] = [TicketType.Prepay.id] * form.count.data if current_user.is_authenticated(): return redirect(url_for("pay_choose")) else: return redirect(url_for("signup", next=url_for("pay_choose"))) if current_user.is_authenticated(): tickets = current_user.tickets.all() payments = current_user.payments.filter(Payment.state != "canceled", Payment.state != "expired").all() else: tickets = [] payments = [] # # go through existing payments # and make cancel and/or pay buttons as needed. # # We don't allow canceling of inprogress gocardless payments cos there is # money in the system and then we have to sort out refunds etc. # # With canceled Bank Transfers we mark the payment as canceled in # case it does turn up for some reason and we need to do something with # it. # retrycancel_forms = {} for p in payments: if p.provider == "gocardless" and p.state == "new": retrycancel_forms[p.id] = GoCardlessTryAgainForm(formdata=None, payment=p.id, yesno="no") if p.provider == "googlecheckout" and p.state == "new": retrycancel_forms[p.id] = GoogleCheckoutTryAgainForm(formdata=None, payment=p.id, yesno="no") elif p.provider == "banktransfer" and p.state == "inprogress": retrycancel_forms[p.id] = BankTransferCancelForm(formdata=None, payment=p.id, yesno="no") # the rest are inprogress or complete gocardless payments # or complete banktransfers, # or canceled payments of either provider. return render_template( "tickets.html", form=form, tickets=tickets, payments=payments, price=TicketType.Prepay.cost, retrycancel_forms=retrycancel_forms, )
def home(): print current_app.config['FEATURE'] if current_user.is_authenticated(): return render_template('microblog/index.html' if current_app.config['FEATURE'] is 1 else 'index.html') login_form = signup_form = None if not current_user.is_authenticated(): login_form= LoginForm(next=request.args.get('next')) signup_form = SignupForm(nex=request.args.get('next')) return render_template('microblog/index.html' if current_app.config['FEATURE'] is 1 else 'index.html', login_form=login_form, signup_form=signup_form)
def tickets(): form = ChoosePrepayTicketsForm(request.form) form.count.values = range(1, TicketType.Prepay.limit + 1) if request.method == 'POST' and form.validate(): session["count"] = form.count.data if current_user.is_authenticated(): return redirect(url_for('pay_choose')) else: return redirect(url_for('signup', next=url_for('pay_choose'))) if current_user.is_authenticated(): tickets = current_user.tickets.all() payments = current_user.payments.filter(Payment.state != "canceled", Payment.state != "expired").all() else: tickets = [] payments = [] # # go through existing payments # and make cancel and/or pay buttons as needed. # # We don't allow canceling of inprogress gocardless payments cos there is # money in the system and then we have to sort out refunds etc. # # With canceled Bank Transfers we mark the payment as canceled in # case it does turn up for some reason and we need to do something with # it. # gc_try_again_forms = {} btcancel_forms = {} for p in payments: if p.provider == "gocardless" and p.state == "new": gc_try_again_forms[p.id] = GoCardlessTryAgainForm(formdata=None, payment=p.id, yesno='no') elif p.provider == "banktransfer" and p.state == "inprogress": btcancel_forms[p.id] = BankTransferCancelForm(formdata=None, payment=p.id, yesno='no') # the rest are inprogress or complete gocardless payments # or complete banktransfers, # or canceled payments of either provider. count = 1 if "count" in session: count = session["count"] return render_template("tickets.html", form=form, tickets=tickets, payments=payments, amount=count, price=TicketType.Prepay.cost, tryagain_forms=gc_try_again_forms, btcancel_forms=btcancel_forms )
def download_ajax(file_id): file_id=url2mid(file_id) try: data = filesdb.get_file(file_id, bl = None) except filesdb.BogusMongoException as e: logging.exception(e) abort(503) if data: if not data["bl"] in (0, None): if data["bl"] == 1: flash("link_not_exist", "error") elif data["bl"] == 3: flash("error_link_removed", "error") goback = True abort(404) else: flash("link_not_exist", "error") abort(404) #si el usuario esta logueado se comprueba si ha votado el archivo para el idioma activo vote=None if current_user.is_authenticated(): vote=usersdb.get_file_vote(file_id,current_user,g.lang) if vote is None: vote={"k":0} return render_template('files_ajax/download_ajax.html',file=fill_data(data,True),vote=vote)
def home(): try: # in case we have not set up database yet app_count = model.Session.query(model.App).filter(model.App.hidden == 0).count() task_count = model.Session.query(model.Task).count() taskrun_count = model.Session.query(model.TaskRun).count() user_count = model.Session.query(model.User).count() stats = {"app": app_count, "task": task_count, "taskrun": taskrun_count, "user": user_count} apps = model.Session.query(model.App).filter(model.App.hidden == 0).filter(model.App.tasks != None).all() threeApps = False if len(apps) > 0: if len(apps) == 1 or len(apps) == 2: frontPageApps = apps tmp = model.App(name="Your application", description="Could be here!") frontPageApps.append(tmp) else: frontPageApps = [] for i in range(0, 3): app = random.choice(apps) apps.pop(apps.index(app)) frontPageApps.append(app) threeApps = True else: frontPageApps = [] except UnboundExecutionError: stats = {"app": 0, "task": 0, "taskrun": 0, "user": 0} if current_user.is_authenticated() and current_user.email_addr == "None": flash("Please update your e-mail address in your profile page, right now it is empty!") return render_template("/home/index.html", stats=stats, frontPageApps=frontPageApps, threeApps=threeApps)
def register_post(): if current_user.is_authenticated(): return redirect("/") current_app.logger.debug('Attempting to register a user') # Always clear out any verified phone numbers #session.pop('verified_phone', None) form = UserRegistrationForm() if form.validate(): # Register the user user = cdw.register_website_user( form.username.data, form.email.data, form.password.data, session.pop('verified_phone', None)) # Try connecting their facebook account if a token # is in the session try: handler = current_app.social.facebook.connect_handler conn = handler.get_connection_values( {"access_token": session['facebooktoken']}) conn['user_id'] = str(user.id) current_app.logger.debug('Saving connection: %s' % conn) connection_service.save_connection(**conn) except KeyError, e: current_app.logger.error(e) pass except Exception, e: current_app.logger.error( 'Could not save connection to Facebook: %s' % e)
def register_post(): if current_user.is_authenticated(): return redirect("/") current_app.logger.debug("Attempting to register a user") # Always clear out any verified phone numbers # session.pop('verified_phone', None) form = UserRegistrationForm() if form.validate(): # Register the user user = cdw.register_website_user( form.username.data, form.email.data, form.password.data, session.pop("verified_phone", None) ) # Try connecting their facebook account if a token # is in the session try: handler = current_app.social.facebook.connect_handler conn = handler.get_connection_values({"access_token": session["facebooktoken"]}) conn["user_id"] = str(user.id) current_app.logger.debug("Saving connection: %s" % conn) connection_service.save_connection(**conn) except KeyError, e: current_app.logger.error(e) pass except Exception, e: current_app.logger.error("Could not save connection to Facebook: %s" % e)
def verify_code(): session.pop('verified_phone', None) msg = 'no match' try: pva_id = session['phone_verify_id'] pva = current_app.cdw.phoneverifications.with_id(pva_id) if pva.expires < datetime.datetime.utcnow(): msg = 'expired' if request.form['code'] == pva.token: session.pop('phone_verify_id', None) if current_user.is_authenticated(): current_user.phoneNumber = pva.phoneNumber cdw.users.save(current_user) else: # Save it in the session for a little bit # in case this is a registration process session['verified_phone'] = pva.phoneNumber current_app.logger.debug('Verified phone number: %s' % pva.phoneNumber) return 'success' except: pass raise BadRequest(msg)
def post(post_id): post = Post.query.get_or_404(post_id) form = PostForm(request.form) comment = CommentForm(post_id=post_id) if current_user.is_authenticated(): del comment.recaptcha return render_template("show_post.html", post=post, comment=comment)
def ctx_proc_userdata(): userdata = {} userdata['username'] = '******' if current_user.is_anonymous( ) else current_user.name userdata['user_is_authenticated'] = current_user.is_authenticated() userdata['user_is_admin'] = current_user.is_admin() return userdata
def verify_code(): session.pop("verified_phone", None) msg = "no match" try: pva_id = session["phone_verify_id"] pva = current_app.cdw.phoneverifications.with_id(pva_id) if pva.expires < datetime.datetime.utcnow(): msg = "expired" if request.form["code"] == pva.token: session.pop("phone_verify_id", None) if current_user.is_authenticated(): current_user.phoneNumber = pva.phoneNumber cdw.users.save(current_user) else: # Save it in the session for a little bit # in case this is a registration process session["verified_phone"] = pva.phoneNumber current_app.logger.debug("Verified phone number: %s" % pva.phoneNumber) return "success" except: pass raise BadRequest(msg)
def verify_code(): session.pop('verified_phone', None) msg = 'no match' try: pva_id = session['phone_verify_id'] pva = current_app.cdw.phoneverifications.with_id(pva_id) if pva.expires < datetime.datetime.utcnow(): msg = 'expired' if request.form['code'] == pva.token: session.pop('phone_verify_id', None) if current_user.is_authenticated(): current_user.phoneNumber = pva.phoneNumber cdw.users.save(current_user) else: # Save it in the session for a little bit # in case this is a registration process session['verified_phone'] = pva.phoneNumber current_app.logger.debug( 'Verified phone number: %s' % pva.phoneNumber) return 'success' except: pass raise BadRequest(msg)
def index(year=None, month=None): today = to_user_timezone(datetime.today()) year = year or today.year month = month or today.month d = date(year, month, 1) hours = 0.0 weekly_hours = {} if current_user.is_authenticated(): times = WorkingUnit.query.get_by_year_and_month(year, month) if times.first(): d = times.first().date for time in times: hours += time.working_time wh = weekly_hours.setdefault(time.week, 0.0) weekly_hours[time.week] = wh + time.working_time else: times = [] return render_template( "index.html", times=times, hours=hours, weekly_hours=weekly_hours, date=d, projects=get_projects(), companies=get_companies(), dates=get_dates(), )
def maker(slug): forms = {} maker = Maker.get(slug) if maker is None: if current_user.is_authenticated(): forms['maker_form'] = MakerForm() html = render_template('maker-new.html', slug=slug, **forms) return make_response(html, 404) parties = list(maker.parties) if current_user.is_authenticated(): forms['maker_form'] = MakerForm(obj=maker) return render_template('maker.html', maker=maker, parties=parties, **forms)
def auth_links(): if current_user.is_authenticated(): links = '<a href="' + url_for('logout') + '">logout</a><span> | </span>' else: links = '<a href="' + url_for('login') + '">login</a><span> | </span>' links = links + '<a href="' + url_for('register') + '">register</a>' return links
def create(user=None): if current_user.is_authenticated(): if current_user.admin: return True else: return False else: return False
def vote(): messageid = ObjectId(request.args.get('messageid')) voteval = int(request.args.get('voteval')) if not current_user.is_authenticated(): return jsonify(result=0) voteresult, score = User.do_vote(messageid, voteval) return jsonify(result=1, voteresult=voteresult, score=score, messageid = request.args.get('messageid'))
def login(): if current_user.is_authenticated(): return redirect(oid.get_next_url()) if request.method == "POST": return oid.try_login(COMMON_PROVIDERS["google"], ask_for=["email"]) return render_template("login.html", next=oid.get_next_url(), errors=[oid.fetch_error()])
def index(): num_users = User.objects().count() if current_user.is_authenticated(): user = str(current_user.first_name + " " + current_user.last_name) return '%d active users ' % num_users + ' ' + "</br>Welcome, " + user + "." + "</br><a href = " + url_for("logout") +">Log out</a>" else: user = "******" return "Welcome to OccuDopt. <a href=" + url_for("login") + ">Log In</a>"
def do_vote(cls, messageid, voteval): """ return 0 if not voted, -1 means vote down, 1 means vote up message_id: an ObjectId of message, voteval should be integer """ #print messageid #print voteval if not current_user.is_authenticated(): return 0 message_doc = g.db.messages.find_one({'_id':messageid}) # cannot vote self! if current_user.id == message_doc['author_id']: return 0, int(message_doc['score']) vote_doc = g.db.votes.find_one({'message_id':messageid, 'user_id':current_user.id}) #print vote_doc if vote_doc is None: vote_doc = {'user_id':current_user.id, 'message_id':messageid, 'vote':voteval } g.db.votes.insert(vote_doc, safe=True) if voteval==1: message_doc['vote_up_count'] = message_doc['vote_up_count'] + 1 message_doc['score'] = message_doc['score'] + 1 else: message_doc['vote_down_count'] = message_doc['vote_down_count'] + 1 message_doc['score'] = message_doc['score'] - 1 g.db.messages.save(message_doc, safe=True) return voteval, int(message_doc['score']) if vote_doc['vote']<>voteval: if vote_doc['vote']==1: message_doc['vote_up_count'] = message_doc['vote_up_count'] - 1 message_doc['vote_down_count'] = message_doc['vote_down_count'] + 1 message_doc['score'] = message_doc['score'] - 2 elif vote_doc['vote']==-1: message_doc['vote_up_count'] = message_doc['vote_up_count'] + 1 message_doc['vote_down_count'] = message_doc['vote_down_count'] - 1 message_doc['score'] = message_doc['score'] + 2 vote_doc['vote'] = voteval g.db.votes.save(vote_doc, safe=True) else: if vote_doc['vote']==1: message_doc['vote_up_count'] = message_doc['vote_up_count'] - 1 message_doc['score'] = message_doc['score'] - 1 else: message_doc['vote_down_count'] = message_doc['vote_down_count'] - 1 message_doc['score'] = message_doc['score'] + 1 voteval = 0 g.db.votes.remove(vote_doc, safe=True) g.db.messages.save(message_doc, safe=True) return voteval, int(message_doc['score'])
def get_locale(): if current_user.is_authenticated(): lang = current_user.locale else: lang = session.get('lang', request.accept_languages.best_match(app.config['LOCALES'])) if lang is None: lang = 'en' return lang
def get_locale(): if current_user.is_authenticated(): lang = current_user.locale else: lang = session.get( 'lang', request.accept_languages.best_match(app.config['LOCALES'])) if lang is None: lang = 'en' return lang
def get_new_message(): if not current_user.is_authenticated(): g.my_new_message = None return jsonify(messageid="", messagepubdate="", imgsrc="") else: g.my_new_message = get_latest_message(current_user.id) #print g.my_new_message return jsonify(messageid="%s"%g.my_new_message['_id'], messagepubdate=format_datetime(g.my_new_message['pub_date']), imgsrc=gravatar_url(current_user.email, 48))
def project(slug): forms = {} proj = Project.get(slug) if proj is None: if current_user.is_authenticated(): forms['project_form'] = ProjectForm() html = render_template('project-new.html', slug=slug, **forms) return make_response(html, 404) parties = list(proj.parties) if current_user.is_authenticated(): forms['project_form'] = ProjectForm(obj=proj) forms['add_party_form'] = ProjectAddParticipationForm() for party in parties: party.form = ParticipationForm(obj=party) return render_template('project.html', project=proj, parties=parties, **forms)
def home(): """ Render home page with the cached apps and users""" d = {"featured": cached_apps.get_featured_front_page(), "top_apps": cached_apps.get_top(), "top_users": None} if app.config["ENFORCE_PRIVACY"] and current_user.is_authenticated(): if current_user.admin: d["top_users"] = cached_users.get_top() if not app.config["ENFORCE_PRIVACY"]: d["top_users"] = cached_users.get_top() return render_template("/home/index.html", **d)
def maker(slug): forms = {} maker = Maker.get(slug) if maker is None: if current_user.is_authenticated(): forms['maker_form'] = MakerForm() if request.args.get('create'): forms['create'] = True html = render_template('maker-new.html', slug=slug, **forms) return make_response(html, 404) parties = sorted(maker.parties, key=lambda p: (p.start_year, p.start_month, getattr(p, 'end_year', None), getattr(p, 'end_month', None), p.maker.name)) if current_user.is_authenticated(): forms['maker_form'] = MakerForm(obj=maker) return render_template('maker.html', maker=maker, parties=parties, **forms)
def add_comment(): form = CommentForm(request.form) if current_user.is_authenticated(): del form.recaptcha if request.method == "POST" and form.validate() and Post.query.get_or_403(form.post_id.data): db.session.add(Comment(form.title.data, form.text.data, form.post_id.data, session.get("user_id"))) db.session.commit() flash("Successfully added comment! Woot!") return redirect(url_for("public.post", post_id=form.post_id.data)) return render_template("show_post.html", post=Post.query.get(form.post_id.data), comment=form)
def logout(): ''' Página para desloguear usuario. ''' if current_user.is_authenticated(): logout_user() logout_oauth() del(session["user"]) return redirect(url_for('index.home',lang=None))
def user_timeline(username): """Display's a users tweets.""" profile_user_doc = g.db.users.find_one({"_id":username}) if profile_user_doc is None: abort(404) followed = False if current_user.is_authenticated(): followed = g.db.followers.find_one({"who_id":session['user_id'], "whom_id":username}) is not None messages = g.db.messages.find({"author_id":username, "host_id":None}, sort=[("pub_date",pymongo.DESCENDING)]).limit(PER_PAGE) return render_template('microblog/timeline.html', messages=messages, followed=followed, profile_user=profile_user_doc)
def login(): if current_user.is_authenticated(): return redirect(request.args.get('next', url_for('tickets'))) form = LoginForm(request.form, next=request.args.get('next')) if request.method == 'POST' and form.validate(): user = User.query.filter_by(email=form.email.data).first() if user and user.check_password(form.password.data): login_user(user) return redirect(form.next.data or url_for('tickets')) else: flash("Invalid login details!") return render_template("login.html", form=form)
def get_dates(): if current_user.is_authenticated(): dates = [] results = WorkingUnit.query.filter_by(user=current_user).values("date") for t in results: d = date(t[0].year, t[0].month, 1) app.logger.debug(d) if d not in dates: dates.append(d) return sorted(dates, reverse=True) else: return []
def edit_comment(comment_id): comment = Comment.query.get_or_404(comment_id) form = CommentForm(request.form) post = Post.query.get(comment.post_id) if current_user.is_authenticated(): del form.recaptcha if request.method == "POST": if not (current_user.is_authenticated() and comment.owner(current_user)): return login_manager.unauthorized() if form.validate(): populate_titletext(form, comment) db.session.commit() flash("Successfully edited comment") return redirect(url_for("public.post", post_id = comment.post_id)) elif form.method.data == "DELETE": db.session.delete(comment) db.session.commit() flash("Successfully deleted comment") return redirect(url_for("public.post", post_id=post.id)) return render_template('edit_comment.html', comment = form) return render_template("show_comment.html", post=post, comment=comment)
def edit_comment(comment_id): comment = Comment.query.get_or_404(comment_id) form = CommentForm(request.form) post = Post.query.get(comment.post_id) if current_user.is_authenticated(): del form.recaptcha if request.method == "POST": if not (current_user.is_authenticated() and comment.owner(current_user)): return login_manager.unauthorized() if form.validate(): populate_titletext(form, comment) db.session.commit() flash("Successfully edited comment") return redirect(url_for("public.post", post_id=comment.post_id)) elif form.method.data == "DELETE": db.session.delete(comment) db.session.commit() flash("Successfully deleted comment") return redirect(url_for("public.post", post_id=post.id)) return render_template('edit_comment.html', comment=form) return render_template("show_comment.html", post=post, comment=comment)
def home(): """ Render home page with the cached apps and users""" d = { 'featured': cached_apps.get_featured_front_page(), 'top_apps': cached_apps.get_top(), 'top_users': None } if app.config['ENFORCE_PRIVACY'] and current_user.is_authenticated(): if current_user.admin: d['top_users'] = cached_users.get_top() if not app.config['ENFORCE_PRIVACY']: d['top_users'] = cached_users.get_top() return render_template('/home/index.html', **d)
def reset_api_key(): """Reset API-KEY for user""" if current_user.is_authenticated(): title = "User: %s · Settings - Reset API KEY" % current_user.fullname if request.method == 'GET': return render_template('account/reset-api-key.html', title=title) else: user = db.session.query(model.User).get(current_user.id) user.api_key = model.make_uuid() db.session.commit() msg = lazy_gettext('New API-KEY generated') flash(msg, 'success') return redirect(url_for('account.settings')) else: return abort(403)
def add_comment(): form = CommentForm(request.form) if current_user.is_authenticated(): del form.recaptcha if request.method == "POST" and form.validate() and Post.query.get_or_403( form.post_id.data): db.session.add( Comment(form.title.data, form.text.data, form.post_id.data, session.get("user_id"))) db.session.commit() flash("Successfully added comment! Woot!") return redirect(url_for("public.post", post_id=form.post_id.data)) return render_template("show_post.html", post=Post.query.get(form.post_id.data), comment=form)
def login(provider_id): if current_user.is_authenticated(): return redirect("/") callback_url = get_authorize_callback('/login/%s' % provider_id) current_app.logger.debug( 'Starting login via %s account. Callback ' 'URL = %s' % (get_display_name(provider_id), callback_url)) session['post_oauth_login_url'] = request.form.get( 'next', current_app.config['AUTH']['post_login_view']) remote_app = get_remote_app(provider_id).remote_app return remote_app.authorize(callback_url)
def global_template_context(): if current_user.is_authenticated(): if (current_user.email_addr == current_user.name or current_user.email_addr == "None"): flash( "Please update your e-mail address in your profile page," " right now it is empty!", 'error') return dict( brand=app.config['BRAND'], title=app.config['TITLE'], copyright=app.config['COPYRIGHT'], description=app.config['DESCRIPTION'], version=pybossa.__version__, current_user=current_user, )
def index(): """Get the last activity from users and apps""" # Top 20 users limit = 20 sql = text(''' WITH global_rank AS ( WITH scores AS ( SELECT user_id, COUNT(*) AS score FROM task_run WHERE user_id IS NOT NULL GROUP BY user_id) SELECT user_id, score, rank() OVER (ORDER BY score desc) FROM scores) SELECT rank, id, name, fullname, email_addr, score FROM global_rank JOIN public."user" on (user_id=public."user".id) ORDER BY rank LIMIT :limit; ''') results = db.engine.execute(sql, limit=20) top_users = [] user_in_top = False if current_user.is_authenticated(): for user in results: if (user.id == current_user.id): user_in_top = True top_users.append(user) if not user_in_top: sql = text(''' WITH global_rank AS ( WITH scores AS ( SELECT user_id, COUNT(*) AS score FROM task_run WHERE user_id IS NOT NULL GROUP BY user_id) SELECT user_id, score, rank() OVER (ORDER BY score desc) FROM scores) SELECT rank, id, name, fullname, email_addr, score FROM global_rank JOIN public."user" on (user_id=public."user".id) WHERE user_id=:user_id ORDER BY rank; ''') user_rank = db.engine.execute(sql, user_id=current_user.id) for row in user_rank: top_users.append(row) else: top_users = results return render_template('/stats/index.html', title="Community Leaderboard", top_users=top_users)
def home(): try: # in case we have not set up database yet app_count = model.Session.query( model.App).filter(model.App.hidden == 0).count() task_count = model.Session.query(model.Task).count() taskrun_count = model.Session.query(model.TaskRun).count() user_count = model.Session.query(model.User).count() stats = { 'app': app_count, 'task': task_count, 'taskrun': taskrun_count, 'user': user_count } apps = model.Session.query(model.App).filter( model.App.hidden == 0).filter(model.App.tasks != None).all() threeApps = False if (len(apps) > 0): if (len(apps) == 1 or len(apps) == 2): frontPageApps = apps tmp = model.App(name="Your application", description="Could be here!") frontPageApps.append(tmp) else: frontPageApps = [] for i in range(0, 3): app = random.choice(apps) apps.pop(apps.index(app)) frontPageApps.append(app) threeApps = True else: frontPageApps = [] except UnboundExecutionError: stats = {'app': 0, 'task': 0, 'taskrun': 0, 'user': 0} if current_user.is_authenticated() and current_user.email_addr == "None": flash( "Please update your e-mail address in your profile page, right now it is empty!" ) return render_template('/home/index.html', stats=stats, frontPageApps=frontPageApps, threeApps=threeApps)
def register_email(): if current_user.is_authenticated(): return redirect("/") form = UserRegistrationForm() # You'd think this wouldn't need to be called here but # a CSRF error will come up when the form is POSTed to # /register. So below there's a show_errors flag in the # template context blow form.validate() # See if a password was passed from the register modal form.password.data = request.form.get('password', '') return render_template('register.html', section_selector="register", page_selector="email", form=form, show_errors=False, phoneForm=VerifyPhoneForm(csrf_enabled=False))
def _login_handler(provider_id, provider_user_id, oauth_response): """Shared method to handle the signin process """ if current_user.is_authenticated(): return redirect("/") display_name = get_display_name(provider_id) try: current_app.logger.debug('Attempting login via %s with provider ' 'user %s' % (display_name, provider_user_id)) meth = connection_service.get_connection_by_provider_user_id connection = meth(provider_id, provider_user_id) user = user_service.get_user_with_id(connection['user_id']) if login_user(user): redirect_url = session.get('post_oauth_login_url', get_cv('post_login_view')) session.pop('post_oauth_login_url', None) current_app.logger.debug('User logged in via %s. Redirecting ' 'to %s' % (display_name, redirect_url)) return redirect(redirect_url) else: current_app.logger.info('Inactive local user attempted login ' 'via %s.' % display_name) flash("Inactive user") except ConnectionNotFoundError: current_app.logger.info('Login attempt via %s failed because ' 'connection was not found.' % display_name) flash('%s account not associated with an existing user' % display_name) # TODO: Maybe redirect to a register page? except Exception, e: current_app.logger.error('Unexpected error signing in via %s: ' '%s' % (display_name, e))
def register_facebook(): if current_user.is_authenticated(): return redirect("/") # Always clear out any verified phone numbers session.pop('verified_phone', None) # Try getting their facebook profile profile = get_facebook_profile(session['facebooktoken']) phoneForm = VerifyPhoneForm(csrf_enabled=False) form = UserRegistrationForm(username=profile['first_name'], email=profile['email'], csrf_enabled=False) form.password.data = request.form.get('password', '') form.validate() return render_template('register.html', form=form, phoneForm=phoneForm, facebook_profile=profile, show_errors=False, section_selector="register", page_selector="facebook")
def export_to(short_name): """Export Tasks and TaskRuns in the given format""" app = app_by_shortname(short_name) title = app_title(app, "Export") def gen_json(table): n = db.session.query(table)\ .filter_by(app_id=app.id).count() sep = ", " yield "[" for i, tr in enumerate( db.session.query(table).filter_by(app_id=app.id).yield_per(1), 1): item = json.dumps(tr.dictize()) if (i == n): sep = "" yield item + sep yield "]" def handle_task(writer, t): writer.writerow(t.info.values()) def handle_task_run(writer, t): if (type(t.info) == dict): writer.writerow(t.info.values()) else: writer.writerow([t.info]) def get_csv(out, writer, table, handle_row): for tr in db.session.query(table)\ .filter_by(app_id=app.id)\ .yield_per(1): handle_row(writer, tr) yield out.getvalue() def respond_json(ty): tables = {"task": model.Task, "task_run": model.TaskRun} try: table = tables[ty] except KeyError: return abort(404) return Response(gen_json(table), mimetype='application/json') def create_ckan_datastores(ckan): tables = {"task": model.Task, "task_run": model.TaskRun} resources = dict(task=None, task_run=None) for k in tables.keys(): # Create the two table resources resource = ckan.resource_create(name=k) resources[k] = resource['result'] ckan.datastore_create(name=k, resource_id=resources[k]['id']) return resources def respond_ckan(ty): # First check if there is a package (dataset) in CKAN tables = {"task": model.Task, "task_run": model.TaskRun} msg_1 = lazy_gettext("Data exported to ") msg = msg_1 + "%s ..." % current_app.config['CKAN_URL'] ckan = Ckan(url=current_app.config['CKAN_URL'], api_key=current_user.ckan_api) app_url = url_for('.details', short_name=app.short_name, _external=True) try: package = ckan.package_exists(name=app.short_name) if package: # Update the package ckan.package_update(app=app, user=app.owner, url=app_url) if len(package['resources']) == 0: resources = create_ckan_datastores(ckan) ckan.datastore_upsert(name=ty, records=gen_json(tables[ty]), resource_id=resources[ty]['id']) flash(msg, 'success') return render_template('/applications/export.html', title=title, app=app) else: ckan.datastore_delete(name=ty) ckan.datastore_create(name=ty) ckan.datastore_upsert(name=ty, records=gen_json(tables[ty])) flash(msg, 'success') return render_template('/applications/export.html', title=title, app=app) else: ckan.package_create(app=app, user=app.owner, url=app_url, tags=current_app.config['BRAND']) resources = create_ckan_datastores(ckan) ckan.datastore_upsert(name=ty, records=gen_json(tables[ty]), resource_id=resources[ty]['id']) flash(msg, 'success') return render_template('/applications/export.html', title=title, app=app) except Exception as inst: print inst if len(inst.args) == 3: type, msg, status_code = inst.args msg = ("Error: %s with status code: %s" % (type, status_code)) else: msg = ("Error: %s" % inst.args[0]) flash(msg, 'danger') return render_template('/applications/export.html', title=title, app=app) def respond_csv(ty): # Export Task(/Runs) to CSV types = { "task": (model.Task, handle_task, (lambda x: True), lazy_gettext("Oops, the application does not have tasks to \ export, if you are the owner add some tasks")), "task_run": (model.TaskRun, handle_task_run, (lambda x: type(x.info) == dict), lazy_gettext("Oops, there are no Task Runs yet to export, invite \ some users to participate")) } try: table, handle_row, test, msg = types[ty] except KeyError: return abort(404) out = StringIO() writer = UnicodeWriter(out) t = db.session.query(table)\ .filter_by(app_id=app.id)\ .first() if t is not None: if test(t): writer.writerow(t.info.keys()) return Response(get_csv(out, writer, table, handle_row), mimetype='text/csv') else: flash(msg, 'info') return render_template('/applications/export.html', title=title, app=app) export_formats = ["json", "csv"] if current_user.is_authenticated(): if current_user.ckan_api: export_formats.append('ckan') ty = request.args.get('type') fmt = request.args.get('format') if not (fmt and ty): if len(request.args) >= 1: abort(404) return render_template('/applications/export.html', title=title, ckan_name=current_app.config.get('CKAN_NAME'), app=app) if fmt not in export_formats: abort(404) return { "json": respond_json, "csv": respond_csv, 'ckan': respond_ckan }[fmt](ty)
def decorated_view(*args, **kwargs): if not current_user.is_authenticated() or not current_user.isAdmin: abort(403) else: return fn(*args, **kwargs)
def restrict_components_to_users(): if not current_user.is_authenticated(): return app.login_manager.unauthorized()
def decorated_view(*args, **kwargs): if has_valid_auth_token() or current_user.is_authenticated(): return fn(*args, **kwargs) else: abort(403)