def line_up_proposal(proposal_id, slug=None): proposal = Proposal.query.get_or_404(proposal_id) if proposal.state not in ('accepted', 'finished'): abort(404) if not current_user.is_anonymous(): is_fave = proposal in current_user.favourites else: is_fave = False if (request.method == "POST") and not current_user.is_anonymous(): if is_fave: current_user.favourites.remove(proposal) msg = 'Removed "%s" from favourites' % proposal.title else: current_user.favourites.append(proposal) msg = 'Added "%s" to favourites' % proposal.title db.session.commit() flash(msg) return redirect(url_for('.line_up_proposal', proposal_id=proposal.id, slug=proposal.slug)) if slug != proposal.slug: return redirect(url_for('.line_up_proposal', proposal_id=proposal.id, slug=proposal.slug)) venue_name = None if proposal.scheduled_venue: venue_name = Venue.query.filter_by(id=proposal.scheduled_venue).one().name return render_template('schedule/line-up-proposal.html', proposal=proposal, is_fave=is_fave, venue_name=venue_name)
def article_add(): url = request.form.get('url', None) if url is None: return abort(500, "URL of article not supplied") if current_user.is_anonymous(): user_name = "anonymous" else: user_name = current_user['user_name'] article_doc = get_source(url, 'user/' + user_name, 'moderated') log('article_add', url_for('.article', doc_id=str(article_doc['_id'])), {'url': url,}) url_parsed = urlparse(url) if url_parsed.netloc in domain_whitelist: article_doc['state'] = 'approved' db_articles.save(article_doc) if current_user.is_anonymous(): return render_template('article_add_thanks.html', article=article_doc) else: return redirect(url_for(".article", doc_id=str(article_doc['_id'])))
def set_user_cookie_id(): """ Sets the user id in the global object if nothing is there before each request This function works together with set_user_cookie in the after requests """ #new fresh user if not request.cookies.get(config.COOKIE_ADSABS2_NAME): if current_user.is_anonymous(): g.user_cookie_id = unicode(uuid.uuid4()) else: g.user_cookie_id = current_user.get_id() #the user has already visited the web site else: if current_user.is_anonymous(): #if the cookie is a valid UUID it's ok curr_cookie = request.cookies.get(config.COOKIE_ADSABS2_NAME) try: uuid.UUID(curr_cookie) g.user_cookie_id = curr_cookie #otherwise the app generates a new one except ValueError: g.user_cookie_id = unicode(uuid.uuid4()) else: g.user_cookie_id = current_user.get_id()
def create_account(): if not current_user.is_anonymous(): return redirect(url_for('index')) new_account = session.pop('new_account', None) if new_account is None: return redirect(url_for('index')) if not current_user.is_anonymous(): return redirect(url_for('index')) social_id = new_account.get('social_id') if social_id is None: return redirect(url_for('index')) form = BaseRegisterForm() if form.validate_on_submit(): user = current_app.bouncer.user_class( email = form.email.data, username = form.username.data, social_id = social_id ) if user.email == new_account.get('email'): user.confirmed = True user.save() if not user.confirmed: token = user.make_confirm_token() send_email('confirm', user, None, token = token) flash(_cfg('flash.register_success', 'A confirmation email has been sent to you.'), 'info') login_user(user, True) return redirect(url_for('index')) session['new_account'] = new_account if request.method == 'GET': form.email.data = session['new_account'].get('email') or '' form.username.data = session['new_account'].get('username') or '' return render_template('bouncer/register_social.html', form = form)
def new_task(app_id): """Return a new task for an application.""" # Check if the request has an arg: try: app = db.session.query(model.App).get(app_id) if app is None: raise NotFound if request.args.get('offset'): offset = int(request.args.get('offset')) else: offset = 0 # Identify the current user fb_user_id = request.args.get('facebook_user_id') if (fb_user_id == None): user_id = None if current_user.is_anonymous() else current_user.id else: fb_api = UserFbAPI() fb_user = fb_api.get_user_by_fb_id(int(fb_user_id)) user_id = fb_user.id user_ip = request.remote_addr if current_user.is_anonymous() and fb_user_id == None else None task = sched.new_task(app_id, user_id, user_ip, offset) # If there is a task for the user, return it if task: r = make_response(json.dumps(task.dictize())) r.mimetype = "application/json" return r else: return Response(json.dumps({}), mimetype="application/json") except Exception as e: return error.format_exception(e, target='app', action='GET')
def _retrieve_new_task(project_id): project = project_repo.get(project_id) if project is None: raise NotFound if not project.allow_anonymous_contributors and current_user.is_anonymous(): info = dict( error="This project does not allow anonymous contributors") error = model.task.Task(info=info) return error if request.args.get('offset'): offset = int(request.args.get('offset')) else: offset = 0 user_id = None if current_user.is_anonymous() else current_user.id user_ip = request.remote_addr if current_user.is_anonymous() else None if request.headers.get('remote_mobile_addr') is not None : user_ip = request.headers.get('remote_mobile_addr') if current_user.is_anonymous() else None else: if request.headers.getlist("X-Forwarded-For"): user_ip = request.headers.getlist("X-Forwarded-For")[0] if ',' in user_ip: ips = user_ip.split(",") for ip in ips: user_ip = ip print "_retrieve_new_task %s." % user_id print "_retrieve_new_task %s." % user_ip print "project.info.get('sched') %s." % project.info.get('sched') task = sched.new_task(project_id, project.info.get('sched'), user_id, user_ip, offset) return task
def get(self, get_provider=None, provider=None): if get_provider is not None: # GET OAUTH PROVIDER if not current_user.is_anonymous(): return redirect(url_for('home')) oauth = OAuthSignIn.get_provider(get_provider) return oauth.authorize() elif provider is not None: # OAUTH PROVIDER CALLBACK if not current_user.is_anonymous(): return redirect(url_for('home')) oauth = OAuthSignIn.get_provider(provider) nickname, email = oauth.callback() if email is None: flash('Authentication failed.') return redirect("/photos/recent/") currentuser = User.query.filter_by(email=email.lower()).first() if not currentuser: currentuser = User(nickname=nickname, email=email, photo="profile.jpg") db.session.add(currentuser) db.session.commit() login_user(currentuser) return redirect(request.args.get('next') or '/photos/latest') else: # LOGIN PAGE if g.user is not None and g.user.is_authenticated(): return redirect(url_for('photos')) return LoginPage(category="login").render()
def get(self, get_provider=None, provider=None): if get_provider is not None: # GET OAUTH PROVIDER if not current_user.is_anonymous(): return redirect(url_for('posts', page_mark='home', page=1)) oauth = OAuthSignIn.get_provider(get_provider) return oauth.authorize() elif provider is not None: # OAUTH PROVIDER CALLBACK if not current_user.is_anonymous(): return redirect(url_for('posts', page_mark='home', page=1)) oauth = OAuthSignIn.get_provider(provider) nickname, email = oauth.callback() if email is None: flash('Authentication failed.') return redirect(url_for('posts', page_mark='home', page=1)) currentuser = User.query.filter_by(email=email).first() if not currentuser: currentuser = User(nickname=nickname, email=email) db.session.add(currentuser) db.session.add(currentuser.follow(currentuser)) db.session.commit() remember_me = False if 'remember_me' in session: remember_me = session['remember_me'] session.pop('remember_me', None) login_user(currentuser, remember=remember_me) # return redirect(request.args.get('next') or '/piemail') return redirect(request.args.get('next') or url_for('posts', page_mark='home')) else: # LOGIN PAGE if g.user is not None and g.user.is_authenticated(): return redirect(url_for('members')) context = {'assets': ViewData(page_mark="login").assets} return render_template("base.html", **context)
def _retrieve_new_task(project_id): project = project_repo.get(project_id) if project is None: raise NotFound if not project.allow_anonymous_contributors and current_user.is_anonymous(): info = dict( error="This project does not allow anonymous contributors") error = model.task.Task(info=info) return error if request.args.get('external_uid'): resp = jwt_authorize_project(project, request.headers.get('Authorization')) if resp != True: return resp if request.args.get('offset'): offset = int(request.args.get('offset')) else: offset = 0 user_id = None if current_user.is_anonymous() else current_user.id user_ip = request.remote_addr if current_user.is_anonymous() else None external_uid = request.args.get('external_uid') task = sched.new_task(project_id, project.info.get('sched'), user_id, user_ip, external_uid, offset) return task
def new_task(app_id): # Check if the request has an arg: try: app = db.session.query(model.App).get(app_id) if app is None: raise NotFound if request.args.get('offset'): offset = int(request.args.get('offset')) else: offset = 0 user_id = None if current_user.is_anonymous() else current_user.id user_ip = request.remote_addr if current_user.is_anonymous() else None task = sched.new_task(app_id, user_id, user_ip, offset) # If there is a task for the user, return it if task: s = URLSafeSerializer(current_app.config.get('SECRET_KEY')) r = make_response(json.dumps(task.dictize())) r.mimetype = "application/json" cookie_id = 'task_run_for_task_id_%s' % task.id r.set_cookie(cookie_id, s.dumps(task.dictize())) return r else: return Response(json.dumps({}), mimetype="application/json") except Exception as e: return error.format_exception(e, target='app', action='GET')
def _update_object(self, taskrun): """Update task_run object with user id or ip.""" # validate the task and project for that taskrun are ok task = task_repo.get_task(taskrun.task_id) if task is None: # pragma: no cover raise Forbidden('Invalid task_id') if (task.project_id != taskrun.project_id): raise Forbidden('Invalid project_id') if _check_task_requested_by_user(taskrun, sentinel.master) is False: raise Forbidden('You must request a task first!') # Add the user info so it cannot post again the same taskrun if current_user.is_anonymous(): taskrun.user_ip = request.remote_addr else: taskrun.user_id = current_user.id if request.headers.get('remote_mobile_addr') is not None : taskrun.user_ip = request.headers.get('remote_mobile_addr') if current_user.is_anonymous() else None else: if request.headers.getlist("X-Forwarded-For"): user_ip = request.headers.getlist("X-Forwarded-For")[0] taskrun.user_ip = user_ip print "user_ip %s." % user_ip if ',' in user_ip: ips = user_ip.split(",") for ip in ips: taskrun.user_ip = ip print "taskrun.user_ip %s." % taskrun.user_ip
def edit(path="/"): if path != "/": path = "/" + path record = models.Pages.pull_by_url(path) if record is None: if current_user.is_anonymous(): abort(404) else: return redirect("/" + path) elif current_user.is_anonymous() and not (rec.data.get("editable", False) and rec.data.get("accessible", False)): abort(401) else: if app.config.get("COLLABORATIVE", False): try: test = requests.get(app.config["COLLABORATIVE"]) if test.status_code == 200: padsavailable = True else: padsavailable = False except: padsavailable = False # TODO: add a check - if index has more recent content than pad content, show a warning to sync the pad to index return render_template("pagemanager/edit.html", padsavailable=padsavailable, record=record)
def ctx_proc_userdata(): userdata = {} userdata["userid"] = "anon" if current_user.is_anonymous() else current_user._uid 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() userdata["get_username"] = get_username # this is a function return userdata
def ctx_proc_userdata(): userdata = {} userdata['userid'] = 'anon' if current_user.is_anonymous() else current_user._uid 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() userdata['get_username'] = get_username return userdata
def edit_user(userid=None): """ Action that edits an existing user or creates a new one """ # True if user is new is_new = False is_admin = False if current_user.is_anonymous(): is_admin = False elif current_user.is_super_admin: is_admin = True userid = try_int(userid) if userid != None and current_user.is_anonymous(): abort(403) elif userid != None and not is_admin and not (current_user.id == userid): abort(403) if userid == None: is_new = True form = EditUserForm(request.form) if not userid: form.password.validators.append(validators.Required(message=_('Password is required'))) if request.method == 'POST' and form.validate(): if userid: # Update existing user = User.query.get(userid) user.username = form.username.data user.is_super_admin = form.is_super_admin.data if is_admin else False user.is_disabled = form.is_disabled.data user.shinken_contact = form.shinken_contact.data if is_admin else user.shinken_contact if form.password.data: user.set_password(form.password.data) db.session.commit() else: # Create new if User.query.filter_by(username= form.username.data).first(): flash(_('Username already taken!'),'error') return redirect(url_for('edit_user')) user = User(form.username.data, form.password.data, form.is_super_admin.data if is_admin else False) user.is_disabled = form.is_disabled.data user.shinken_contact = form.shinken_contact.data if is_admin else 'None' db.session.add(user) db.session.commit() if current_user.is_anonymous(): return redirect(url_for('login')) return redirect(url_for("list_users")) else: if userid: # Fill the form with user info user = User.query.filter( User.id == userid).first() form.username.data = user.username form.is_disabled.data = user.is_disabled form.is_super_admin.data = user.is_super_admin form.shinken_contact.data = user.shinken_contact return render_template('user/edit_user.html', form=form, isnew=is_new, isadmin=is_admin)
def poll_vote(slug): poll = Poll.query.filter_by(slug=slug).first_or_404() poll.check_expiry() if poll.require_login and current_user.is_anonymous(): flash(gettext("You need to login to vote on this poll."), "error") return redirect(url_for("login", next=url_for("poll_vote", slug=poll.slug))) if poll.one_vote_per_user and not current_user.is_anonymous() and poll.get_user_votes(current_user): flash(gettext("You can only vote once on this poll. Please edit your choices by clicking the edit button on the right."), "error") return redirect(poll.get_url()) groups = poll.get_choice_groups() if not groups: flash(gettext("The poll author has not yet created any choices. You cannot vote on the poll yet."), "warning") return redirect(poll.get_url()) form = CreateVoteForm() if request.method == "POST": for subform in form.vote_choices: subform.value.choices = [(v.id, v.title) for v in poll.get_choice_values()] if form.validate_on_submit(): vote = Vote() if current_user.is_anonymous(): vote.name = form.name.data else: vote.user = current_user vote.anonymous = poll.anonymous_allowed and form.anonymous.data if vote.anonymous and not vote.user: vote.name = "anonymous" poll.votes.append(vote) for subform in form.vote_choices: choice = Choice.query.filter_by(id=subform.choice_id.data).first() value = ChoiceValue.query.filter_by(id=subform.value.data).first() if not choice or choice.poll != poll: abort(404) if value and value.poll != poll: abort(404) vote_choice = VoteChoice() vote_choice.value = value vote_choice.comment = subform.comment.data vote_choice.vote = vote vote_choice.choice = choice db.session.add(vote_choice) flash(gettext("You have voted."), "success") db.session.commit() return redirect(poll.get_url()) if not request.method == "POST": poll.fill_vote_form(form) return render_template("vote.html", poll=poll, form=form)
def poll_vote_edit(slug, vote_id): poll = Poll.query.filter_by(slug=slug).first_or_404() poll.check_expiry() vote = Vote.query.filter_by(id=vote_id).first_or_404() if vote.poll != poll: abort(404) if vote.user and current_user.is_anonymous(): flash(gettext("This vote was created by a logged in user. If that was you, please log in to edit the vote."), "error") return redirect(url_for("login", next=url_for("poll_vote_edit", slug=poll.slug, vote_id=vote_id))) if vote.user and not current_user.is_anonymous() and vote.user != current_user: flash(gettext("This vote was created by someone else. You cannot edit their choices."), "error") return redirect(poll.get_url()) form = CreateVoteForm(obj=vote) if poll.require_login and current_user.is_anonymous(): flash(gettext("You need to login to edit votes on this poll.")) return redirect(url_for("login", next=url_for("poll_vote_edit", slug=poll.slug, vote_id=vote_id))) if request.method == "POST": for subform in form.vote_choices: subform.value.choices = [(v.id, v.title) for v in poll.get_choice_values()] if form.validate_on_submit(): if not vote.user: vote.name = form.name.data vote.anonymous = poll.anonymous_allowed and form.anonymous.data if vote.anonymous and not vote.user: vote.name = "anonymous" for subform in form.vote_choices: choice = Choice.query.filter_by(id=subform.choice_id.data).first() value = ChoiceValue.query.filter_by(id=subform.value.data).first() if not choice or choice.poll != poll: abort(404) if value and value.poll != poll: abort(404) vote_choice = poll.get_vote_choice(vote, choice) if not vote_choice: vote_choice = VoteChoice() vote_choice.vote = vote vote_choice.choice = choice vote_choice.comment = subform.comment.data vote_choice.value = value db.session.commit() flash(gettext("The vote has been edited."), "success") return redirect(poll.get_url()) if not request.method == "POST": poll.fill_vote_form(form) for subform in form.vote_choices: vote_choice = VoteChoice.query.filter_by(vote_id = vote.id, choice_id = subform.choice_id.data).first() subform.comment.data = vote_choice.comment if vote_choice else "" return render_template("vote.html", poll=poll, form=form, vote=vote)
def requests(): try: # Return first 100, ? limit = 100 departments_json = open(os.path.join(app.root_path, "static/json/list_of_departments.json")) list_of_departments = json.load(departments_json) departments = sorted(list_of_departments, key=unicode.lower) my_requests = False requester_name = "" dept_selected = "All departments" open_requests = True if request.method == "GET": filters = request.args.copy() if not filters: if not current_user.is_anonymous(): my_requests = True filters["owner"] = current_user.id filters["status"] = "open" else: if "department" in filters and filters["department"].lower() == "all": del filters["department"] if not ("status" in filters and filters["status"].lower() == "open"): open_requests = False if "department" in filters: dept_selected = filters["department"] # if dept_selected != "All departments": # filters['department'] = request.args['department_filter'] if "owner" in filters and not current_user.is_anonymous(): my_requests = True if "requester" in filters and current_user.is_anonymous(): del filters["requester"] record_requests = get_request_table_data(get_requests_by_filters(filters)) user_id = get_user_id() if record_requests: template = "all_requests.html" if user_id: template = "all_requests_city.html" else: template = "all_requests_noresults.html" total_requests_count = get_count("Request") return render_template( template, record_requests=record_requests, user_id=user_id, title="All Requests", open_requests=open_requests, departments=departments, dept_selected=dept_selected, my_requests=my_requests, total_requests_count=total_requests_count, requester_name=requester_name, ) except Exception, message: if "Too long" in message: message = "Loading requests is taking a while. Try exploring with more restricted search options." print message return render_template("error.html", message=message, user_id=get_user_id())
def query_on_description(description): offset = request.args.get('offset', 0) size = request.args.get('size', 10) order_by = request.args.get('order_by', "upload_time") reverse = request.args.get('reverse', 0) > 0 res = VideoListService.query_on_description(description, offset, size, order_by, reverse, show_banned = (not current_user.is_anonymous()) and current_user.is_admin(), show_disabled = (not current_user.is_anonymous()) and current_user.is_admin()) res = [v.to_rich_dict() for v in res] return json.dumps(res, ensure_ascii = False)
def index(error=None): """ Gplus login page. """ if not current_user.is_anonymous() and "@stxnext.pl" in current_user.username: return redirect("order") elif not current_user.is_anonymous() or error: msg = "Sadly you are not a hero, but you can try and join us." return render_template("index.html", msg=msg) return render_template("index.html")
def _retrieve_new_task(project_id): project = project_repo.get(project_id) if project is None: raise NotFound if not project.allow_anonymous_contributors and current_user.is_anonymous(): info = dict( error="This project does not allow anonymous contributors") error = [model.task.Task(info=info)] return error if request.args.get('external_uid'): resp = jwt_authorize_project(project, request.headers.get('Authorization')) if resp != True: return resp if request.args.get('limit'): limit = int(request.args.get('limit')) else: limit = 1 if limit > 100: limit = 100 if request.args.get('offset'): offset = int(request.args.get('offset')) else: offset = 0 if request.args.get('orderby'): orderby = request.args.get('orderby') else: orderby = 'id' if request.args.get('desc'): desc = fuzzyboolean(request.args.get('desc')) else: desc = False user_id = None if current_user.is_anonymous() else current_user.id user_ip = (anonymizer.ip(request.remote_addr or '127.0.0.1') if current_user.is_anonymous() else None) external_uid = request.args.get('external_uid') task = sched.new_task(project_id, project.info.get('sched'), user_id, user_ip, external_uid, offset, limit, orderby=orderby, desc=desc) return task
def bbs_topic(id): options = {"id": id} page = request.args.get('page', 0, type=int) topic = Topic.query.get(id) if not topic: return render_template("topic_not_found.html") count, num_pages, replies = get_page_query(Reply.query.replies_at_topic(topic.id), page, page_size=DEFAULT_PAGE_REPLIES) def pager_url(p, options): return generate_url(".bbs_topic", page=p, **options) if current_user.is_anonymous(): form = None else: form = ReplyForm(request.form) if request.method == "POST": if current_user.is_anonymous(): return redirect(url_for("auth.login", next=request.path) or "/") if form.validate(): reply = Reply(section=topic.section, node=topic.node, user=current_user, topic=topic, content=form.data["content"], created=datetime.now(), floor=topic.reply_count+1) topic.last_reply_by = current_user.username topic.last_reply_at = datetime.now() topic.reply_count += 1 current_user.profile.replies += 1 node = topic.node node.reply_count += 1 section = topic.section section.reply_count += 1 db.session.add_all([reply, topic, current_user.profile, node, section]) db.session.commit() return redirect(pager_url((reply.floor-1)/DEFAULT_PAGE_REPLIES, options)) return render_template("topic.html", topic=topic, options=options, count=count, pager_url=pager_url, num_pages=num_pages, page=page, replies=replies, form=form) topic.hits += 1 db.session.commit() markdowner = Markdown() topic.content = markdowner.convert(topic.content) for r in replies: r.content = markdowner.convert(r.content) return render_template("topic.html", topic=topic, options=options, count=count, pager_url=pager_url, num_pages=num_pages, page=page, replies=replies, form=form )
def start_topic (board_str): """ Creates a new topic. Is called by the javascript event callback for #docreate :param board_id: board in which the new topic should be started :rtype: json """ board_id = int(board_str.split("-")[0]) check_ban(board_id) board = Board.query.get(board_id) if not board: return "boardnotfound", 404 if not current_user.may_post_in(board): return "forbidden", 403 title = request.json["title"] text = request.json["text"] topic = Topic(board_id, title) db.session.add(topic) db.session.commit() event_dispatcher = EventDispatcher() event = Event("topic_created", topic) event_dispatcher.dispatch(event) event = Event("topic_id_created", topic.id) event_dispatcher.dispatch(event) if not current_user.is_anonymous(): wrapper = TopicWrapper(topic) wrapper.follow() post = Post(current_user.id, text, topic.id, request.remote_addr) db.session.add(post) db.session.commit() event = Event("post_created", post) event_dispatcher.dispatch(event) event = Event("post_id_created", post.id) event_dispatcher.dispatch(event) if not current_user.is_anonymous(): post = PostWrapper(post) post.read() event = Event("post_read", post) event_dispatcher.dispatch(event) cache = TopicCache() cache.refresh(board_id) return jsonify(topicId = topic.id)
def task_presenter(short_name, task_id): app = app_by_shortname(short_name) task = Task.query.filter_by(id=task_id).first_or_404() if current_user.is_anonymous(): if not app.allow_anonymous_contributors: msg = ("Oops! You have to sign in to participate in " "<strong>%s</strong>" "application" % app.name) flash(gettext(msg), 'warning') return redirect(url_for('account.signin', next=url_for('.presenter', short_name=app.short_name))) else: msg_1 = gettext( "Ooops! You are an anonymous user and will not " "get any credit" " for your contributions.") next_url = url_for( 'app.task_presenter', short_name=short_name, task_id=task_id) url = url_for( 'account.signin', next=next_url) flash(msg_1 + "<a href=\"" + url + "\">Sign in now!</a>", "warning") title = app_title(app, "Contribute") template_args = {"app": app, "title": title} def respond(tmpl): return render_template(tmpl, **template_args) if not (task.app_id == app.id): return respond('/applications/task/wrong.html') #return render_template('/applications/presenter.html', app = app) # Check if the user has submitted a task before tr_search = db.session.query(model.TaskRun)\ .filter(model.TaskRun.task_id == task_id)\ .filter(model.TaskRun.app_id == app.id) if current_user.is_anonymous(): remote_addr = request.remote_addr or "127.0.0.1" tr = tr_search.filter(model.TaskRun.user_ip == remote_addr) else: tr = tr_search.filter(model.TaskRun.user_id == current_user.id) tr_first = tr.first() if tr_first is None: return respond('/applications/presenter.html') else: return respond('/applications/task/done.html')
def _retrieve_new_task(app_id): app = db.session.query(model.app.App).get(app_id) if app is None: raise NotFound if request.args.get('offset'): offset = int(request.args.get('offset')) else: offset = 0 user_id = None if current_user.is_anonymous() else current_user.id user_ip = request.remote_addr if current_user.is_anonymous() else None task = sched.new_task(app_id, user_id, user_ip, offset) return task
def logout_view(): if DEBUG: print current_user.name , current_user.is_anonymous() if current_user.is_anonymous() == False: if DEBUG: print "Prepare to Logout" logout_user() msg = {'echotext':u'成功登出' } return render_template('logout.html', msg=msg) else: flash(u"您还未登录") return redirect(url_for('index'))
def order(id, form=None): order = Order.query.filter(Order.id == id).first() if order is None: abort(404) if current_user.is_anonymous() and not order.public: flash('Please login to see this order.', 'info') abort(401) if form is None: form = AnonOrderItemForm() if current_user.is_anonymous() else OrderItemForm() form.populate(order.location) if order.stoptime and order.stoptime < datetime.now(): form = None total_price = sum([o.product.price for o in order.items]) return render_template('order.html', order=order, form=form, total_price=total_price)
def pagemanager(path=''): url = '/' + path.lstrip('/').rstrip('/').replace('../',"") if url == '/': url = '/index' if url.endswith('.json'): url = url.replace('.json','') rec = models.Pages.pull_by_url(url) if rec is not None and rec.data.get('editable',False): if current_user.is_anonymous() and not rec.data.get('accessible',True): abort(401) else: return redirect(url_for('.edit',path=url)) elif ( ( request.method == 'DELETE' or ( request.method == 'POST' and request.form['submit'] == 'Delete' ) ) and not current_user.is_anonymous() ): if rec is None: abort(404) else: _sync_delete(rec) return "" elif request.method == 'POST' and not current_user.is_anonymous(): if rec is None: rec = models.Pages() rec.save_from_form(request) if app.config.get('CONTENT_FOLDER',False): _sync_fs_from_es(rec) return redirect(rec.data.get('url','/')) elif rec is None: if current_user.is_anonymous(): abort(404) else: return redirect(url_for('.settings', path=url)) elif request.method == 'GET': if current_user.is_anonymous() and not rec.data.get('accessible',True): abort(401) elif util.request_wants_json(): resp = make_response( rec.json ) resp.mimetype = "application/json" return resp else: try: content = render_template( 'pagemanager/content' + url, record=rec ) except: content = rec.data.get('content',"") return _render_page(rec,content) else: abort(401)
def query(path='Record'): pathparts = path.strip('/').split('/') subpath = pathparts[0] if subpath.lower() in app.config.get('NO_QUERY_VIA_API',[]) and ( current_user.is_anonymous() or not current_user.view_admin ): abort(401) if subpath.lower() in ["student", "everything"] and ( current_user.is_anonymous() or not current_user.view_admin ): abort(401) klass = getattr(models, subpath[0].capitalize() + subpath[1:] ) if len(pathparts) > 1 and pathparts[1] == '_mapping': resp = make_response( json.dumps(klass().query(endpoint='_mapping')) ) elif len(pathparts) == 2 and pathparts[1] not in ['_mapping','_search']: if request.method == 'POST': abort(401) else: rec = klass().pull(pathparts[1]) if rec: if ( not app.config.get('ANONYMOUS_SEARCH_FILTER',False) ) or ( app.config.get('ANONYMOUS_SEARCH_FILTER',False) and rec.get('visible',False) and rec.get('accessible',False) ): resp = make_response( rec.json ) else: abort(401) else: abort(404) else: if request.method == "POST": if request.json: qs = request.json else: qs = dict(request.form).keys()[-1] elif 'q' in request.values: qs = {'query': {'query_string': { 'query': request.values['q'] }}} elif 'source' in request.values: qs = json.loads(urllib2.unquote(request.values['source'])) else: qs = '' for item in request.values: if item not in ['q','source','callback','_'] and isinstance(qs,dict): qs[item] = request.values[item] if 'sort' not in qs and app.config.get('SEARCH_SORT',False): qs['sort'] = {app.config['SEARCH_SORT'].rstrip(app.config['FACET_FIELD']) + app.config['FACET_FIELD'] : {"order":app.config.get('SEARCH_SORT_ORDER','asc')}} if app.config.get('ANONYMOUS_SEARCH_FILTER',False) and current_user.is_anonymous(): terms = {'visible':True,'accessible':True} else: terms = '' resp = make_response( json.dumps(klass().query(q=qs, terms=terms)) ) resp.mimetype = "application/json" return resp
def user_progress(project_id=None, short_name=None): """API endpoint for user progress. Return a JSON object with two fields regarding the tasks for the user: { 'done': 10, 'total: 100 } This will mean that the user has done a 10% of the available tasks for him """ if project_id or short_name: if short_name: project = project_repo.get_by_shortname(short_name) elif project_id: project = project_repo.get(project_id) if project: # For now, keep this version, but wait until redis cache is used here for task_runs too query_attrs = dict(project_id=project.id) if current_user.is_anonymous(): query_attrs['user_ip'] = request.remote_addr or '127.0.0.1' else: query_attrs['user_id'] = current_user.id taskrun_count = task_repo.count_task_runs_with(**query_attrs) tmp = dict(done=taskrun_count, total=n_tasks(project.id)) return Response(json.dumps(tmp), mimetype="application/json") else: return abort(404) else: # pragma: no cover return abort(404)
def addReport(userReportedID, issue): # If user is logged in or not if current_user.is_anonymous(): user = None else: user = current_user.id # Add report to database report = Report(user, userReportedID, issue) db.session.add(report) db.session.commit() # Send email to admins reportEmail(user, userReportedID, issue)
def _update_object(self, taskrun): """Update task_run object with user id or ip.""" # validate the task and app for that taskrun are ok task = Task.query.get(taskrun.task_id) if task is None: # pragma: no cover raise Forbidden('Invalid task_id') if (task.app_id != taskrun.app_id): raise Forbidden('Invalid app_id') # Add the user info so it cannot post again the same taskrun if current_user.is_anonymous(): taskrun.user_ip = request.remote_addr else: taskrun.user_id = current_user.id
def get_request_table_data(requests): public = False if current_user.is_anonymous(): public = True request_table_data = [] if not requests: return request_table_data for req in requests: request_table_data.append( RequestTablePresenter(request=req, public=public)) if not request_table_data: return request_table_data request_table_data.sort(key=lambda x: x.request.date_created, reverse=True) return request_table_data
def password_reset(token): if not current_user.is_anonymous(): return redirect(url_for('index')) form = PasswordResetForm() if form.validate_on_submit(): user = Contact.query.filter_by(mail=form.email.data).first_or_404() if user is None: return redirect(url_for('index')) if user.reset_password(token, form.password.data): flash('Your password has been updated.') return redirect(url_for('login')) else: return redirect(url_for('index')) return render_template('auth/reset_password.html', form=form)
def profile(name): """ Get user profile. Returns a Jinja2 template with the user information. """ user = user_repo.get_by_name(name=name) if user is None: raise abort(404) if current_user.is_anonymous() or (user.id != current_user.id): return _show_public_profile(user) if current_user.is_authenticated() and user.id == current_user.id: return _show_own_profile(user)
def password_reset(token): if not current_user.is_anonymous(): return redirect(url_for('main.index')) form = form_class.PasswordResetForm() if form.validate_on_submit(): user = models.User.query.filter_by(email=form.email.data).first() if user is None: return redirect(url_for('main.index')) if user.reset_password(token, form.password.data): flash('Your password has been updated.', 'success') return redirect(url_for('user.login')) else: return redirect(url_for('main.index')) return render_template('auth/reset_password.html', form=form)
def password_reset(token): if not current_user.is_anonymous(): return redirect(url_for('main.index')) form = PasswordResetForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is None: return redirect(url_for('main.index')) if user.reset_password(token, form.password.data): flash('您的密码已经更新.') return redirect(url_for('auth.login')) else: return redirect(url_for('main.index')) return render_template('auth/reset_password.html', form=form)
def update_a_resource(resource): if request.method == 'POST': update_resource(resource, request) if current_user.is_anonymous() == False: return redirect( url_for('show_request_for_x', audience='city', request_id=request.form['request_id'])) else: return redirect( url_for('show_request', request_id=request.form['request_id'])) return render_template( 'error.html', message="You can only update requests from a request page!")
def signin(): """ Signin method for PyBossa users. Returns a Jinja2 template with the result of signing process. """ if is_amnesty_sso_enable(): return redirect(url_for('amnesty.login')) form = LoginForm(request.form) if request.method == 'POST' and form.validate(): password = form.password.data email = form.email.data user = user_repo.get_by(email_addr=email) if user and user.check_password(password): msg_1 = gettext("Welcome back") + " " + user.fullname flash(msg_1, 'success') return _sign_in_user(user) elif user: msg, method = get_user_signup_method(user) if method == 'local': msg = gettext("Ooops, Incorrect email/password") flash(msg, 'error') else: flash(msg, 'info') else: msg = gettext("Ooops, we didn't find you in the system, \ did you sign up?") flash(msg, 'info') if request.method == 'POST' and not form.validate(): flash(gettext('Please correct the errors'), 'error') auth = {'twitter': False, 'facebook': False, 'google': False} if current_user.is_anonymous(): # If Twitter is enabled in config, show the Twitter Sign in button if ('twitter' in current_app.blueprints): # pragma: no cover auth['twitter'] = True if ('facebook' in current_app.blueprints): # pragma: no cover auth['facebook'] = True if ('google' in current_app.blueprints): # pragma: no cover auth['google'] = True return render_template('account/signin.html', title="Sign in", form=form, auth=auth, next=request.args.get('next')) else: # User already signed in, so redirect to home page return redirect(url_for('home.home'))
def track(request_id=None): if request.method == 'POST': if not request_id: request_id = request.form['request_id'] if not current_user.is_anonymous(): audience = 'city' else: audience = 'public' return redirect( url_for('show_request_for_x', audience=audience, request_id=request_id)) else: return render_template("track.html")
def preview(path='/'): if current_user.is_anonymous(): abort(401) else: if path != '/': path = '/' + path rec = models.Pages.pull_by_url(path) if rec is None: abort(404) else: # get current etherpad content a = app.config['COLLABORATIVE'].rstrip('/') + '/p/' a += rec.id + '/export/txt' c = requests.get(a) return _render_page(rec,c.text)
def get_alias(self, formatted=True): if current_user.is_anonymous() is True: return None replay_alias = current_user.replay_aliases_dict.get(self.id) if replay_alias is not None: if formatted: return "\u201C{}\u201D".decode('unicode-escape').format( replay_alias.alias) # Wrap in curly quotes else: return replay_alias.alias return None
def main(): if current_user.is_anonymous(): return redirect(url_for('users.login', next=url_for('.main'))) if current_user.has_permission('admin'): return redirect(url_for('.proposals')) if current_user.has_permission('cfp_anonymiser'): return redirect(url_for('.anonymisation')) if current_user.has_permission('cfp_reviewer'): return redirect(url_for('.review_list')) abort(404)
def new_task(app_id): """Return a new task for an application.""" # Check if the request has an arg: try: app = db.session.query(model.app.App).get(app_id) if app is None: raise NotFound if request.args.get('offset'): offset = int(request.args.get('offset')) else: offset = 0 user_id = None if current_user.is_anonymous() else current_user.id user_ip = request.remote_addr if current_user.is_anonymous() else None task = sched.new_task(app_id, user_id, user_ip, offset) # If there is a task for the user, return it if task: r = make_response(json.dumps(task.dictize())) r.mimetype = "application/json" return r else: return Response(json.dumps({}), mimetype="application/json") except Exception as e: return error.format_exception(e, target='app', action='GET')
def oauth_callback(provider): if not current_user.is_anonymous(): return redirect(url_for('index')) oauth = OAuthSignIn.get_provider(provider) username, email = oauth.callback() if email is None: # Valid email address for user identification flash('Authentication failed !!') return redirect(url_for('index')) if email != '*****@*****.**' or email != '*****@*****.**': flash('You are not authorized to login to the application !!') return redirect(url_for('index')) login_user(user, remember=True) return redirect(url_for('index'))
def get_current_user_id(): userId = None fb_user_id = request.args.get('facebook_user_id') if (fb_user_id != None): fb_api = UserFbAPI() fb_user = fb_api.get_user_by_fb_id(int(fb_user_id)) userId = fb_user.id elif not current_user.is_anonymous(): userId = current_user.id else: userId = request.remote_addr return Response(json.dumps({"current_user_id": str(userId)}), mimetype="application/json")
def posts_for_current_user(): if not (current_user.is_anonymous()) and current_user.is_authenticated(): if current_user.is_admin: # He can see everything return Post.query else: # They can see public posts and posts in their categories return Post.query.join( Post.categories).filter((Category.public == True) | Category.allowed_users.any( id=current_user.id)) else: # They can only see public posts return Post.query.join(Post.categories).filter(Category.public == True)
def page_write(name): cname = to_canonical(name) if not cname: return dict(error=True, message="Invalid name") if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous( ): return dict(error=True, message="Anonymous posting not allowed"), 403 if request.method == 'POST': # Create if cname in current_app.config.get('WIKI_LOCKED_PAGES'): return dict(error=True, message="Page is locked"), 403 sha = g.current_wiki.write_page(cname, request.form['content'], message=request.form['message'], create=True, username=current_user.username, email=current_user.email) elif request.method == 'PUT': edit_cname = to_canonical(request.form['name']) if edit_cname in current_app.config.get('WIKI_LOCKED_PAGES'): return dict(error=True, message="Page is locked"), 403 if edit_cname != cname.lower(): g.current_wiki.rename_page(cname, edit_cname) sha = g.current_wiki.write_page(edit_cname, request.form['content'], message=request.form['message'], username=current_user.username, email=current_user.email) return dict(sha=sha) else: # DELETE if cname in current_app.config.get('WIKI_LOCKED_PAGES'): return dict(error=True, message="Page is locked"), 403 sha = g.current_wiki.delete_page(name, username=current_user.username, email=current_user.email) return dict(sha=sha)
def landing(search=None, page=0): """ Listings page """ # If there is no search, get the first on off the list if current_user.is_anonymous(): searches = [] else: searches = Search.related(current_user.pk) if not search: if len(searches) > 0: for i in xrange(len(searches)): if searches[i].make: display = searches[i] break else: return redirect(url_for('landing')) else: return redirect(url_for('landing')) else: display = Search.objects.get(pk=search).select_related() try: make = Car.objects.get(make=display.make) except Car.DoesNotExist: pass models = [model.model for model in make.models] models.insert(0, 'Any') model = make.get_model(display.model) trims = ['Any'] if model: for trim in model.trims: trims.append(trim) # Show all the finds for a search finds = display.get_finds(page, 100) context = dict(display=display, searches=searches, finds=finds, page=page, pages=len(display.finds) / 100, makes=MAKES, models=models, trims=trims) return render_template('listings.html', **context)
def signup(): if not current_user.is_anonymous(): return abort(403) form = Signup_Form(username=request.args.get("username", None), email=request.args.get("email", None), next=request.args.get("next", None)) if form.validate_on_submit(): # add user (not activated) request_user_account(form.username.data, form.password.data, form.email.data) flash( "Thanks for signing up! An Activation mail has been sent to you (%s) please come back..." % (form.email.data)) return redirect(url_for('base.index')) return render_template('accounts/signup.html', form=form)
def login(): form = forms.UsuarioLoginForm() #import pdb; pdb.set_trace() if form.validate_on_submit(): usuario = Usuario.query.filter_by(matricula=form.matricula.data, senha=hashlib.md5(form.senha.data.encode('utf-8')).hexdigest(), ativo=True).first() if usuario: login_user(usuario) else: flash('Matrícula ou senha inválida!', 'login') if not current_user.is_anonymous() and current_user.is_authenticated(): return redirect(url_for('home.index')) return render_template('home/login.html', form=form)
def login(): if not current_user.is_anonymous(): return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and user.password == form.password.data: login_user(user, remember=form.remember_me) flash('Successfully logged in.', 'success') else: flash('Incorrect user or password.', 'danger') return redirect(request.args.get('next') or url_for('index')) return redirect(url_for('index', login_form=form))
def getSubjectPercentage(subjectID): if current_user.is_anonymous(): return None subjectPercentage = 0.0 topics = getTopics(subjectID) # If the subject has no topics return nothing if not topics: return 0 for topic in topics: subjectPercentage += getTopicPercentage(topic['id']) return int(subjectPercentage / len(topics))
def line_up_proposal(proposal_id): proposal = Proposal.query.get_or_404(proposal_id) form = FavouriteProposalForm() if not current_user.is_anonymous(): is_fave = proposal in current_user.favourites else: is_fave = False # Use the form for CSRF token but explicitly check for post requests as # an empty form is always valid if (request.method == "POST") and not current_user.is_anonymous(): if is_fave: current_user.favourites.remove(proposal) msg = 'Removed "%s" from favourites' % proposal.title else: current_user.favourites.append(proposal) msg = 'Added "%s" to favourites' % proposal.title db.session.commit() flash(msg) return redirect(url_for('.line_up_proposal', proposal_id=proposal.id)) return render_template('schedule/line-up-proposal.html', form=form, proposal=proposal, is_fave=is_fave)
def oauth_authorized(): """Authorise a Discourse login.""" sso = request.args.get('sso') sig = request.args.get('sig') if current_user.is_anonymous(): next_url = url_for('discourse.oauth_authorized', sso=sso, sig=sig) return redirect(url_for('account.signin', next=next_url)) try: url = discourse_sso.get_sso_login_url(sso, sig) except (ValueError, AttributeError) as e: # pragma: no cover flash('Access Denied: {0}'.format(str(e)), 'error') return redirect(url_for('home.home')) return redirect(url)
def search(): if current_user.is_anonymous(): return redirect(url_for('views.index')) keywords = request.args.get('query') if not keywords: return render_template('search.html', animals={}, keywords=keywords) query = keywords.split(' ') animals = Animal.query.filter( Animal.name.ilike("%" + func.lower(query.pop()) + "%")) while query: animals = animals.union( Animal.query.filter( Animal.name.ilike("%" + func.lower(query.pop()) + "%"))) print(query) return render_template('search.html', animals=animals, keywords=keywords)
def oauth_callback(provider): if not current_user.is_anonymous(): return redirect(url_for('index')) oauth = OAuthSignIn.get_provider(provider) social_id, username, email = oauth.callback() if social_id is None: flash('Authentication failed.') return redirect(url_for('index')) user = User.query.filter_by(social_id=social_id).first() if not user: user = User(social_id=social_id, nickname=username, email=email) db.session.add(user) db.session.commit() login_user(user, True) return redirect(url_for('index'))
def changePasswordForUser(username): if userManager is None: return jsonify(SUCCESS) if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()): if "application/json" in request.headers["Content-Type"]: data = request.json if "password" in data.keys() and data["password"]: try: userManager.changeUserPassword(username, data["password"]) except users.UnknownUser: return app.make_response(("Unknown user: %s" % username, 404, [])) return jsonify(SUCCESS) else: return app.make_response(("Forbidden", 403, []))
def __init__(self, key_prefix, limit, per, send_x_headers): self.reset = (int(time.time()) // per) * per + per self.key = key_prefix + str(self.reset) self.limit = limit self.per = per self.send_x_headers = send_x_headers if not current_user.is_anonymous() and current_user.admin: self.limit *= current_app.config.get("ADMIN_RATE_MULTIPLIER", 1) p = sentinel.master.pipeline() p.incr(self.key) p.expireat(self.key, self.reset + self.expiration_window) self.current = min(p.execute()[0], limit)
def password_reset_request(): if not current_user.is_anonymous(): return redirect(url_for('main.index')) form = PasswordResetRequestForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: token = user.generate_reset_token() send_email(user.email, u'重置你的密码', 'auth/email/reset_password', user=user, token=token, next=request.args.get('next')) flash(u'一个密码重置邮件将会发送到你的邮箱。') return redirect(url_for('auth.login')) return render_template('auth/reset_password.html', form=form)