def add_link(): """Adds a new link for the current user.""" form = LinkForm(request.form, banlist=[strip_protocol(app.config["LINKSERVER_URL"])]) client = get_db_client(app, g) if request.method == "POST": # Validate the form form.long_url.data = ensure_protocol(form.long_url.data) if form.validate(): # TODO Decide whether we want to do something with the response kwargs = form.to_json() try: client.create_short_url( netid=current_user.netid, **kwargs ) return redirect("/") except Exception as e: return render_template("add.html", errors=["{}".format(e)], netid=current_user.netid, admin=current_user.is_admin()) else: # WTForms detects a form validation error return render_template("add.html", errors=form.errors, netid=current_user.netid, admin=current_user.is_admin()) else: # GET request return render_template("add.html", netid=current_user.netid, admin=current_user.is_admin())
def post_deployment_file(username, deployment_id): deployment = db.Deployment.find_one({'_id':deployment_id}) user = db.User.find_one( {'username' : username } ) if not (deployment and user and deployment.user_id == user._id and (current_user.is_admin() or current_user == user)): raise StandardError("Unauthorized") # @TODO better response via ajax? retval = [] for name, f in request.files.iteritems(): if not name.startswith('file-'): continue safe_filename = f.filename # @TODO out_name = os.path.join(deployment.deployment_dir, safe_filename) with open(out_name, 'w') as of: f.save(of) retval.append((safe_filename, datetime.utcnow())) editable = current_user and current_user.is_active() and (current_user.is_admin() or current_user == user) return render_template("_deployment_files.html", files=retval, editable=editable)
def edit_user(username): app.logger.info("GET %s", username) app.logger.info("Request URL: %s", request.url) action_path = request.url user = db.User.find_one( {'username' : username } ) if user is None or (user is not None and not current_user.is_admin() and current_user != user): # No permission app.logger.error("Permission is denied") app.logger.error("User: %s", user) app.logger.error("Admin?: %s", current_user.is_admin()) app.logger.error("Not current user?: %s", current_user != user) flash("Permission denied", 'danger') return redirect(url_for("index")) form = UserForm(obj=user) if form.validate_on_submit(): form.populate_obj(user) user.save() if form.password.data: User.update(username=user.username, password=form.password.data) flash("Account updated", 'success') return redirect(url_for("index")) return render_template('edit_user.html', form=form, user=user, action_path=action_path)
def get(self, userId=None, id=None): """Retrieve a list of API keys""" if id is not None: key = APIKey.query.get(id) if key.user == current_user or current_user.is_admin(): return key else: abort(403) if userId == current_user.id or current_user.is_admin(): marsh = APIKey.query.filter(APIKey.user_id == userId).all() return marsh else: abort(403)
def view(certificate_id): use_ssl = Setting.get_by_name('use_ssl', default=False).value if use_ssl == False: abort(404) cert = Certificate.get_by_id(certificate_id) if cert.type != CLIENT and not current_user.is_admin(): abort(403) ca_cert = Certificate.query.filter_by(type=CA).first() if cert.user != current_user and not current_user.is_admin(): abort(403) return render_template('certificate/view.html', certificate=cert, ca_cert=ca_cert, current_user=current_user, active='certificates', ssl=use_ssl)
def admin_hoteles(): if not current_user.is_admin(): return redirect(url_for('index')) form = CreateHotelForm(request.form) hoteles_p = [] for hotel in Hotel.select(): nombre = hotel.nombre region = hotel.region ciudad = hotel.ciudad direccion = hotel.direccion formd = DeleteHotelForm(request.form) hoteles_p.insert(len(hoteles_p),{'nombre':nombre, 'region':region,'ciudad':ciudad,'direccion':direccion,'form':formd }) if form.validate_on_submit(): try: hotel = Hotel.get(Hotel.nombre == form.nombre.data) if hotel: return render_template('admin_hoteles.html',hoteles=hoteles_p, form=form, error=u'nombre de hotel ya existente en sistema') except: Hotel.create( nombre=form.nombre.data, region=form.region.data, ciudad=form.ciudad.data, direccion=form.direccion.data, numeroAtencion=form.numeroAtencion.data, emailContacto=form.emailContacto.data ) return redirect(url_for('admin_hoteles')) return render_template('admin_hoteles.html',hoteles=hoteles_p,form=form)
def new_deployment(username): user = db.User.find_one( {'username' : username } ) if user is None or (user is not None and not current_user.is_admin() and current_user != user): # No permission flash("Permission denied", 'danger') return redirect(url_for("index")) form = NewDeploymentForm() bad_regex = r'[^a-zA-z0-9_]' form.name.data = re.sub(bad_regex, '', form.name.data) if form.validate_on_submit(): upload_root = os.path.join(user.data_root, 'upload') new_deployment_dir = os.path.join(upload_root, form.name.data) deployment = db.Deployment() form.populate_obj(deployment) deployment.user_id = user._id deployment.deployment_dir = new_deployment_dir deployment.updated = datetime.utcnow() try: deployment.save() flash("Deployment created", 'success') send_wmoid_email(username, deployment) except DuplicateKeyError: flash("Deployment names must be unique across Glider DAC: %s already used" % deployment.name, 'danger') else: error_str = ", ".join(["%s: %s" % (k, ", ".join(v)) for k, v in form.errors.iteritems()]) flash("Deployment could not be created: %s" % error_str, 'danger') return redirect(url_for('list_user_deployments', username=username))
def home(): if current_user.is_admin(): redirect_url = url_for("admin.admin_dashboard") return redirect(redirect_url) else: redirect_url = url_for("department.department_dashboard", department_id=current_user.department_id) return redirect(redirect_url)
def edit_deployment(username, deployment_id): user = db.User.find_one( {'username' : username } ) if user is None or (user is not None and not current_user.is_admin() and current_user != user): # No permission flash("Permission denied", 'danger') return redirect(url_for('list_user_deployments', username=username)) deployment = db.Deployment.find_one({'_id':deployment_id}) form = DeploymentForm(obj=deployment) if form.validate_on_submit(): form.populate_obj(deployment) deployment.updated = datetime.utcnow() try: deployment.estimated_deploy_date = datetime.strptime(form.estimated_deploy_date.data, "%Y-%m-%d") except ValueError: deployment.estimated_deploy_date = None deployment.save() flash("Deployment updated", 'success') return redirect(url_for('show_deployment', username=username, deployment_id=deployment._id)) else: error_str = ", ".join(["%s: %s" % (k, ", ".join(v)) for k, v in form.errors.iteritems()]) flash("Deployment could not be edited: %s" % error_str, 'danger') return render_template('edit_deployment.html', username=username, form=form, deployment=deployment)
def admin(): if not current_user.is_admin(): # No permission flash("Permission denied", 'danger') return redirect(url_for("index")) form = UserForm() if form.is_submitted() and BaseForm.validate(form, extra_validators={'password':[validators.Required()]}): user = db.User() form.populate_obj(user) user.save() User.update(username=user.username, password=form.password.data) # make sure user dirs exist user.ensure_dir('upload') flash("Account for '%s' created" % user.username, 'success') return redirect(url_for("admin")) users = db.User.find() mission_counts_raw = db.User.get_mission_count_by_user() mission_counts = {m['_id']:m['count'] for m in mission_counts_raw} return render_template('admin.html', form=form, users=users, mission_counts=mission_counts)
def delete_comment(id: int): comment = Comment.query.get_or_404(id) post_id = comment.post.id if current_user == comment.user or current_user.is_admin(): db.session.delete(comment) db.session.commit() return redirect(url_for('main.post', id=post_id))
def copy_notification(id): notification = Notification.query.filter_by(id=id).first_or_404() desc = notification.description if notification.user != current_user and not current_user.is_admin(): abort(403) notification.id = None notification.description = desc + ' Clone' make_transient(notification) db.session.add(notification) db.session.commit() old_settings = NotificationSetting.query.filter_by(notification_id=id).all() for s in old_settings: s.id = None s.notification_id = notification.id make_transient(s) db.session.add(s) db.session.commit() current_app.decoder.refresh_notifier(notification.id) flash('Notification cloned.', 'success') return redirect(url_for('notifications.index'))
def entity(id, rev=None): review = Review.query.get_or_404(str(id)) # Not showing review if it isn't published yet and not viewed by author. if review.is_draft and not (current_user.is_authenticated() and current_user == review.user): raise NotFound(gettext("Can't find a review with the specified ID.")) if review.is_hidden: if not current_user.is_admin(): raise Forbidden(gettext("Review has been hidden. " "You need to be an administrator to view it.")) else: flash(gettext("Review has been hidden."), 'warning') spotify_mappings = None if review.entity_type == 'release_group': spotify_mappings = mbspotify.mappings(review.entity_id) revisions = Revision.query.filter_by(review=review).order_by(desc(Revision.timestamp)) count = revisions.count() if not rev: rev = count if rev < count: flash(gettext('You are viewing an old revision, the review has been updated since then.')) elif rev > count: raise NotFound(gettext("The revision you are looking for does not exist.")) revision = revisions.offset(count-rev).first() if not review.is_draft and current_user.is_authenticated(): # if user is logged in, get his vote for this review vote = Vote.query.filter_by(user=current_user, revision=revision).first() else: # otherwise set vote to None, its value will not be used vote = None review.text_html = markdown(revision.text, safe_mode="escape") return render_template('review/entity/%s.html' % review.entity_type, review=review, spotify_mappings=spotify_mappings, vote=vote)
def admin_tipos_habitacion(): if not current_user.is_admin(): return redirect(url_for('index')) form = CreateTipoHabitacionForm(request.form) tipos_habitacion_p = [] for tipoHabitacion in TipoHabitacion.select(): nombre = tipoHabitacion.nombre descripcion = tipoHabitacion.descripcion numeroPersonas = tipoHabitacion.numeroPersonas precio = tipoHabitacion.precio formd = DeleteTipoHabitacionForm(request.form) tipos_habitacion_p.insert(len(tipos_habitacion_p),{'nombre':nombre, 'descripcion':descripcion,'numeroPersonas':numeroPersonas,'precio':precio,'form':formd }) if form.validate_on_submit(): try: tipoHabitacion = TipoHabitacion.get(TipoHabitacion.nombre == form.nombre.data) if tipoHabitacion: return render_template('admin_tipos_habitacion.html',tipos_habitacion=tipos_habitacion_p, form=form, error=u'nombre de tipo habitacion ya existente en sistema') except: TipoHabitacion.create( nombre=form.nombre.data, descripcion=form.descripcion.data, numeroPersonas=form.numeroPersonas.data, precio=form.precio.data ) return redirect(url_for('admin_tipos_habitacion')) return render_template('admin_tipos_habitacion.html',tipos_habitacion=tipos_habitacion_p,form=form)
def validate_username(self, field): if field.data != current_user.username and not current_user.is_admin(): raise ValidationError('You do not have permission to change your username.') existing_user = User.query.filter_by(username_insensitive=field.data).first() if existing_user and existing_user.id != self.id.data: raise ValidationError('Sorry this username is taken... please choose another.')
def report(id): review = Review.query.get_or_404(str(id)) if review.is_hidden and not current_user.is_admin(): raise NotFound(gettext("Review has been hidden.")) if review.user == current_user: flash(gettext("You cannot report your own review."), 'error') return redirect(url_for('.entity', id=id)) if current_user.is_blocked: flash(gettext("You are not allowed to report this review because " "your account has been blocked by a moderator."), 'error') return redirect(url_for('.entity', id=id)) last_revision_id = review.last_revision.id count = SpamReport.query.filter_by(user=current_user, revision_id=last_revision_id).count() if count > 0: flash(gettext("You have already reported this review."), 'error') return redirect(url_for('.entity', id=id)) form = ReviewReportForm() if form.validate_on_submit(): SpamReport.create(last_revision_id, current_user, form.reason.data) flash(gettext("Review has been reported."), 'success') return redirect(url_for('.entity', id=id)) return render_template('review/report.html', review=review, form=form)
def vote_submit(review_id): review_id = str(review_id) if 'yes' in request.form: vote = True elif 'no' in request.form: vote = False review = Review.query.get_or_404(review_id) if review.is_hidden and not current_user.is_admin(): raise NotFound(gettext("Review has been hidden.")) if review.user == current_user: flash(gettext("You cannot rate your own review."), 'error') return redirect(url_for('.entity', id=review_id)) if current_user.is_vote_limit_exceeded is True and current_user.has_voted(review) is False: flash(gettext("You have exceeded your limit of votes per day."), 'error') return redirect(url_for('.entity', id=review_id)) if current_user.is_blocked: flash(gettext("You are not allowed to rate this review because " "your account has been blocked by a moderator."), 'error') return redirect(url_for('.entity', id=review_id)) Vote.create(current_user, review, vote) # overwrites an existing vote, if needed flash(gettext("You have rated this review!"), 'success') return redirect(url_for('.entity', id=review_id))
def edit(id): review = Review.query.get_or_404(str(id)) if review.is_draft and current_user != review.user: raise NotFound(gettext("Can't find a review with the specified ID.")) if review.user != current_user: raise Unauthorized(gettext("Only author can edit this review.")) if review.is_hidden and not current_user.is_admin(): raise NotFound(gettext("Review has been hidden.")) form = ReviewEditForm(default_license_id=review.license_id, default_language=review.language) if not review.is_draft: # Can't change license if review is published. del form.license_choice if form.validate_on_submit(): if review.is_draft: license_choice = form.license_choice.data else: license_choice = None review.update(text=form.text.data, is_draft=(form.state.data == 'draft'), license_id=license_choice, language=form.language.data) flash(gettext("Review has been updated."), 'success') return redirect(url_for('.entity', id=review.id)) else: form.text.data = review.text if review.entity_type == 'release_group': spotify_mappings = mbspotify.mappings(review.entity_id) return render_template('review/modify/edit.html', form=form, review=review, entity_type=review.entity_type, entity=entity, spotify_mappings = spotify_mappings) return render_template('review/modify/edit.html', form=form, review=review, entity_type=review.entity_type)
def edit_category(): if not current_user.is_admin(): flash('Permission denied...', 'danger') return {'status': 403} form = EditCategoryForm(request.form) if form.validate_on_submit(): category = Category.query.get(form.id.data) if not category: flash("This category doesn't exist...", 'danger') return {'status': 400} category.name = form.name.data db.session.commit() flash('Successfully updated ' + category.name + '.', 'success') # return the updated navbar result = profile_view_serializer.dump({ 'navbar': { 'categories': Category.query.order_by(Category.name).all() } }).data return {'status': 200, 'result': result} else: flash(form.errors, 'form-error') return {'status': 400}
def put(self, profile_id): if profile_id != 'me' and not current_user.is_admin(): return abort(401) if profile_id == 'me': profile = g.Profile.objects.filter(user=current_user.get_user()).first() else: profile = g.Profile.objects.with_id(profile_id) parser = reqparse.RequestParser() parser.add_argument('facebook_id', type=unicode, store_missing=False) parser.add_argument('twitter_id', type=unicode, store_missing=False) parser.add_argument('biography', type=unicode, store_missing=False) parser.add_argument('birthday', type=unicode, store_missing=False) args = parser.parse_args() for field in ['facebook_id', 'twitter_id']: if field in args.keys(): setattr(profile, field, args[field]) if 'biography' in args.keys(): profile.biography = bleach.clean(args['biography'], tags=ALLOWED_TAGS, styles=ALLOWED_STYLES, attributes=ALLOWED_ATTRIBUTES) if 'birthday' in args.keys(): profile.birthday = arrow.get(args['birthday']).naive profile.save() return profile
def get(self, profile_id): if profile_id == 'me': return g.Profile.objects.filter(user=current_user.get_user()).first() else: if not current_user.is_admin(): return abort(401) return g.Profile.objects.with_id(profile_id)
def delete_category(): if not current_user.is_admin(): flash('Permission denied...', 'danger') return {'status': 403} form = DeleteCategoryForm(request.form) if form.validate_on_submit(): category = Category.query.get(form.id.data) if category.articles.first(): flash("You can't delete a category containing articles.", 'danger') return {'status': 400} name = category.name db.session.delete(category) db.session.commit() flash('Successfully deleted ' + name, 'success') # return the updated navbar result = profile_view_serializer.dump({ 'navbar': { 'categories': Category.query.order_by(func.lower(Category.name)).all() } }).data return {'status': 200, 'result': result} else: flash(form.errors, 'form-error') return {'status': 400}
def users(): if not current_user.is_admin(): abort(403) users = User.query return render_template('users.html', title='All Users', users=users)
def ballot(ballot_id=0): # If no ballot is provided, try to grab the user's most recent ballot. if not ballot_id and g.user.ballots is not None: ballot = g.user.ballots.order_by(Ballot.id.desc()).first() return redirect(url_for('ballot', ballot_id=ballot.id)) else: ballot = Ballot.query.get(ballot_id) if not ballot: flash('No such ballot', 'warning') return redirect(url_for('index')) poll = Poll.query.get(ballot.poll_id) closes_eastern = poll.closeTime.replace(tzinfo=utc).astimezone(eastern_tz) updated_eastern = ballot.updated.replace(tzinfo=utc).astimezone(eastern_tz) if not poll.has_completed and not current_user.is_admin() and current_user != ballot.voter: flash('Poll has not yet completed. Please wait until ' + timestamp(closes_eastern), 'warning') return redirect(url_for('index')) votes = [] for vote in ballot.votes: votes.append({'rank': vote.rank, 'team': vote.team_id, 'reason': vote.reason}) votes.sort(key=lambda vote: vote['rank']) return render_template('ballot.html', ballot=ballot, votes=votes, teams=Team.query, updated_eastern=updated_eastern)
def pluginCommand(name): api_plugins = octoprint.plugin.plugin_manager().get_filtered_implementations(lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin) if not api_plugins: return make_response("Not found", 404) if len(api_plugins) > 1: return make_response("More than one api provider registered for {name}, can't proceed".format(name=name), 500) api_plugin = api_plugins[0] try: valid_commands = api_plugin.get_api_commands() if valid_commands is None: return make_response("Method not allowed", 405) if api_plugin.is_api_adminonly() and not current_user.is_admin(): return make_response("Forbidden", 403) command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response response = api_plugin.on_api_command(command, data) if response is not None: return response return NO_CONTENT except Exception: logging.getLogger(__name__).exception("Error while excuting SimpleApiPlugin {}".format(name), extra=dict(plugin=name)) return abort(500)
def delete(self, news_id): news = g.News.objects.with_id(news_id) if not current_user.is_admin() and not current_user.has_any_permission('club', news.club.id, ['admin', 'news']): return abort(401) news.delete() return '', 204
def polls(s, w): prov = request.args.get('prov', False) detailed = request.args.get('detailed', False) poll = Poll.query.filter_by(season=s).filter_by(week=w).first() if not poll: flash('No such poll', 'warning') return redirect(url_for('index')) closes_eastern = poll.closeTime.replace(tzinfo=utc).astimezone(eastern_tz) if not poll.has_completed and not current_user.is_admin(): flash('Poll has not yet completed. Please wait until '+ timestamp(closes_eastern), 'warning') return redirect(url_for('index')) (results, official_ballots, provisional_ballots, nonvoters) = generate_results(poll, prov) return render_template('polldetail.html', season=s, week=w, poll=poll, results=results, official_ballots=official_ballots, provisional_ballots=provisional_ballots, users=User.query, teams=Team.query, closes_eastern=closes_eastern, prov=prov, detailed=detailed, nonvoters=nonvoters)
def post(self, news_id): news = g.News.objects.with_id(news_id) if not current_user.is_admin() and not current_user.has_any_permission('club', news.club.id, ['admin', 'news']): return abort(401) parser = reqparse.RequestParser() parser.add_argument('media', type=werkzeug.datastructures.FileStorage, location='files') args = parser.parse_args() uid = str(uuid4()) bucket = s3conn.get_bucket(current_app.config['AWS_S3_BUCKET']) key = Key(bucket) key.key = g.tenant + '/news/' + str(news.id) + '/' + uid key.content_type = args['media'].mimetype key.set_contents_from_file(args['media'].stream) key.make_public() news.update(add_to_set__medias=Media( name=uid, url='https://' + current_app.config['AWS_S3_BUCKET'] + '.s3.amazonaws.com/' + g.tenant + '/news/' + str(news.id) + '/' + uid )) return g.News.objects.with_id(news_id)
def put(self, news_id): news = g.News.objects.with_id(news_id) if not current_user.is_admin() and not current_user.has_any_permission('club', news.club.id, ['admin', 'news']): return abort(401) parser = reqparse.RequestParser() parser.add_argument('name', type=unicode, store_missing=False) parser.add_argument('date', type=unicode, store_missing=False) parser.add_argument('author', type=unicode, store_missing=False) parser.add_argument('headline', type=unicode, store_missing=False) parser.add_argument('content', type=unicode, store_missing=False) parser.add_argument('draft', type=bool, store_missing=False) args = parser.parse_args() for field in ['name', 'club', 'author', 'headline', 'draft']: if field in args.keys(): setattr(news, field, args[field]) if 'content' in args.keys(): news.content = bleach.clean(args['content'], tags=ALLOWED_TAGS, styles=ALLOWED_STYLES, attributes=ALLOWED_ATTRIBUTES) if 'date' in args.keys(): news.date = arrow.get(args['date']).naive news.save() return news
def whatif(): if not current_user.is_admin(): abort(403) users = User.query.filter((User.is_voter == True) | (User.applicationFlag == True)) return render_template('users.html', title='What if Voters', users=users)
def is_accessible(self): return current_user.is_authenticated and current_user.is_admin()
def debug(): if not current_user.is_admin(): abort(404) tweets = db.session.query(models.Tweet).all() tweet_result = {'tweet': []} for tweet in tweets: tweet_result['tweet'].append({ 'id': tweet.id, 'user': tweet.user.username, 'text': json.loads(tweet.detail)['text'], 'api_url': tweet.api_url, 'tweet_id': tweet.tweet_id, 'time': tweet.created_at, 'score': tweet.sentiment.score if tweet.sentiment else None }) mentions = db.session.query(models.TweetMention).all() mention_result = {'mention': []} for mention in mentions: mention_result['mention'].append({ 'id': mention.id, 'user': mention.user.username, 'text': json.loads(mention.detail)['text'], 'api_url': mention.api_url, 'score': mention.sentiment.score if mention.sentiment else None }) users = db.session.query(models.User).all() user_result = {'user': []} for u in users: user_result['user'].append({'name': u.username}) oauths = db.session.query(models.OAuth).all() oauth_result = {'oauth': []} for oauth in oauths: oauth_result['oauth'].append({ 'provider': oauth.provider, 'username': oauth.user.username, 'provider_user_id': oauth.provider_user_id }) fbs = db.session.query(models.FacebookPost).all() fb_result = {'fb': []} for fb in fbs: fb_result['fb'].append({ 'id': fb.id, 'user': fb.user.username, 'text': json.loads(fb.detail), 'api_url': fb.api_url, 'score': fb.sentiment.score if fb.sentiment else None }) moods = db.session.query(models.Mood).all() mood_result = {'mood': []} for mood in moods: mood_result['mood'].append({ 'id': mood.id, 'user': mood.user.username, 'text': mood.detail, 'score': mood.sentiment.score if mood.sentiment else None }) return jsonify(user_result, '=======', oauth_result, '=======', tweet_result, '=======', mention_result, '=======', fb_result, '=======', mood_result, '=======')
def is_accessible(self): if "ADMIN" in current_user.getPermissoes(): self.can_delete = True if "CONTEUDO" in current_user.getPermissoes(): self.can_delete = False return current_user.is_authenticated and current_user.is_admin()
def index(): from psycopg2 import DataError cur_cat = request.args.get("category", "") from .knowl import knowl_status_code, knowl_type_code if request.method == 'POST': data = request.form else: data = request.args qualities = [ quality for quality in knowl_status_code if data.get(quality, "") == "on" ] if not qualities: qualities = ["reviewed", "beta"] types = [typ for typ in knowl_type_code if data.get(typ, "") == "on"] if not types: types = ["normal"] search = request.args.get("search", "") regex = (request.args.get("regex", "") == "on") keywords = search if regex else search.lower() # for the moment the two boxes types and search are two forms, thus as temporary fix we search on all types when one searches by keyword or regex if search: types = list(knowl_type_code) try: # We omit the category so that we can compute the number of results in each category. # Eventually it would be good to do the category filtering client-side all_knowls = knowldb.search(filters=qualities, types=types, keywords=keywords, regex=regex) except DataError as e: knowls = {} if regex and "invalid regular expression" in str(e): flash_error("The string %s is not a valid regular expression", keywords) else: flash_error("Unexpected error %s occurred during knowl search", str(e)) all_knowls = [] categories = Counter() if cur_cat: # Always include the current category categories[cur_cat] = 0 knowls = [] for k in all_knowls: cat = k["id"].split(".")[0] categories[cat] += 1 if cur_cat in ["", cat]: knowls.append(k) def first_char(k): t = k['title'] if len(t) == 0 or t[0] not in string.ascii_letters: return "?" return t[0].upper() def get_table(k): return k['id'].split(".")[1] def knowl_sort_key(knowl): '''sort knowls, special chars at the end''' if cur_cat == "columns": return knowl['id'] title = knowl['title'] if title and title[0] in string.ascii_letters: return (0, title.lower()) else: return (1, title.lower()) knowls = sorted(knowls, key=knowl_sort_key) from itertools import groupby if cur_cat == "columns": knowls = groupby(knowls, get_table) else: knowls = groupby(knowls, first_char) knowl_qualities = ["reviewed", "beta"] #if current_user.is_authenticated: # knowl_qualities.append("in progress") if current_user.is_admin(): knowl_qualities.append("deleted") b = [] if cur_cat: b = [(cur_cat, url_for('.index', category=cur_cat))] return render_template("knowl-index.html", title="Knowledge database", bread=get_bread(b), knowls=knowls, search=search, knowl_qualities=knowl_qualities, qualities=qualities, use_regex=regex, categories=categories, cur_cat=cur_cat, knowl_types=list(knowl_type_code), types=types)
def view_post(sub, pid, slug=None, comments=False, highlight=None): """ View post and comments (WIP) """ sort = request.args.get("sort", default=None, type=str) try: post = misc.getSinglePost(pid) except SubPost.DoesNotExist: return abort(404) if post["sub"].lower() != sub.lower(): abort(404) # We check the slug and correct it if it's wrong if slug != post["slug"]: kwargs = {} if sort is None else {"sort": sort} return redirect( url_for("sub.view_post", sub=sub, pid=pid, slug=post["slug"], **kwargs), 301) sub = Sub.select().where(fn.Lower(Sub.name) == sub.lower()).dicts().get() subInfo = misc.getSubData(sub["sid"]) postmeta = misc.metadata_to_dict( SubPostMetadata.select().where(SubPostMetadata.pid == pid)) sticky_sort = "top" if str(pid) in subInfo["sticky"]: sticky_sort = postmeta.get("sort", sticky_sort) if sort is None: sort = sticky_sort subMods = misc.getSubMods(sub["sid"]) include_history = current_user.is_mod(sub["sid"], 1) or current_user.is_admin() if current_user.is_mod(sub["sid"], 1) or current_user.is_admin(): open_reports = ( SubPostReport.select().where((SubPostReport.pid == pid) & SubPostReport.open).dicts()) else: open_reports = False try: UserSaved.get((UserSaved.uid == current_user.uid) & (UserSaved.pid == pid)) is_saved = True except UserSaved.DoesNotExist: is_saved = False if not comments: comments = SubPostComment.select( SubPostComment.cid, SubPostComment.parentcid).where(SubPostComment.pid == post["pid"]) if sort == "new": comments = comments.order_by(SubPostComment.time.desc()).dicts() elif sort == "top": comments = comments.order_by(SubPostComment.score.desc()).dicts() comments = comments.dicts() if not comments.count(): comments = [] else: comments = misc.get_comment_tree( post["pid"], sub["sid"], comments, uid=current_user.uid, include_history=include_history, postmeta=postmeta, ) if config.site.edit_history and include_history: try: content_history = (SubPostContentHistory.select( SubPostContentHistory.pid, SubPostContentHistory.content, SubPostContentHistory.datetime, ).where(SubPostContentHistory.pid == post["pid"]).order_by( SubPostContentHistory.datetime.desc()).dicts()) except SubPostContentHistory.DoesNotExist: content_history = [] try: title_history = (SubPostTitleHistory.select( SubPostTitleHistory.pid, SubPostTitleHistory.title, SubPostTitleHistory.datetime, ).where(SubPostTitleHistory.pid == post["pid"]).order_by( SubPostTitleHistory.datetime.desc()).dicts()) except SubPostTitleHistory.DoesNotExist: title_history = [] else: content_history = [] title_history = [] post["visibility"] = "" if post["deleted"] == 1: if current_user.uid == post["uid"]: post["visibility"] = "user-self-del" elif current_user.is_admin(): post["visibility"] = "admin-self-del" elif current_user.is_mod(sub["sid"], 1): post["visibility"] = "mod-self-del" else: post["visibility"] = "none" elif post["deleted"] == 2: if (current_user.is_admin() or current_user.is_mod(sub["sid"], 1) or current_user.uid == post["uid"]): post["visibility"] = "mod-del" else: post["visibility"] = "none" if post["userstatus"] == 10 and post["deleted"] == 1: post["visibility"] = "none" postmeta = misc.metadata_to_dict( SubPostMetadata.select().where(SubPostMetadata.pid == pid)) pollData = {"has_voted": False} if post["ptype"] == 3: # poll. grab options and votes. options = SubPostPollOption.select( SubPostPollOption.id, SubPostPollOption.text, fn.Count(SubPostPollVote.id).alias("votecount"), ) options = options.join( SubPostPollVote, JOIN.LEFT_OUTER, on=(SubPostPollVote.vid == SubPostPollOption.id), ) options = options.where(SubPostPollOption.pid == pid).group_by( SubPostPollOption.id) pollData["options"] = options total_votes = SubPostPollVote.select().where( SubPostPollVote.pid == pid).count() pollData["total_votes"] = total_votes if current_user.is_authenticated: # Check if user has already voted on this poll. try: u_vote = SubPostPollVote.get( (SubPostPollVote.pid == pid) & (SubPostPollVote.uid == current_user.uid)) pollData["has_voted"] = True pollData["voted_for"] = u_vote.vid_id except SubPostPollVote.DoesNotExist: pollData["has_voted"] = False # Check if the poll is open pollData["poll_open"] = True if "poll_closed" in postmeta: pollData["poll_open"] = False if "poll_closes_time" in postmeta: pollData["poll_closes"] = datetime.datetime.utcfromtimestamp( int(postmeta["poll_closes_time"])).isoformat() if int(postmeta["poll_closes_time"]) < time.time(): pollData["poll_open"] = False return engine.get_template("sub/post.html").render({ "post": post, "sub": sub, "subInfo": subInfo, "is_saved": is_saved, "pollData": pollData, "postmeta": postmeta, "commentform": PostComment(), "comments": comments, "subMods": subMods, "highlight": highlight, "content_history": content_history, "title_history": title_history, "open_reports": open_reports, "sort": sort, "sticky_sort": sticky_sort, })
def decorated_function(*args, **kwargs): if not current_user.is_admin(): return abort(403) return f(*args, **kwargs)
def is_accessible(self): return current_user.is_admin()
def decorated_view(*args, **kwargs): logger.info("admin access attempt by %s" % current_user.get_id()) if not current_user.is_admin(): return flask.abort(403) # access denied return fn(*args, **kwargs)
def save_form(): ID = request.form['id'] if not ID: raise Exception("no id") if not allowed_id(ID): return redirect(url_for(".index")) FINISH_RENAME = request.form.get('finish_rename', '') UNDO_RENAME = request.form.get('undo_rename', '') if FINISH_RENAME: k = Knowl(ID) k.actually_rename() flash(Markup("Renaming complete; the history of %s has been merged into %s" % (ID, k.source_name))) return redirect(url_for(".show", ID=k.source_name)) elif UNDO_RENAME: k = Knowl(ID) k.undo_rename() flash(Markup("Renaming undone; the history of %s has been merged back into %s" % (k.source_name, ID))) return redirect(url_for(".show", ID=ID)) NEWID = request.form.get('krename', '').strip() k = Knowl(ID, saving=True, renaming=bool(NEWID)) new_title = request.form['title'] new_content = request.form['content'] who = current_user.get_id() if new_title != k.title or new_content != k.content: if not k.content and not k.title and k.exists(allow_deleted=True): # Creating a new knowl with the same id as one that had previously been deleted k.resurrect() flash(Markup("Knowl successfully created. Note that a knowl with this id existed previously but was deleted; its history has been restored.")) k.title = new_title k.content = new_content k.timestamp = datetime.now() k.status = 0 k.save(who=who) if NEWID: if not current_user.is_admin(): flash_error("You do not have permissions to rename knowl") elif not allowed_id(NEWID): pass else: try: if k.sed_safety == 0: time.sleep(0.01) k.actually_rename(NEWID) flash(Markup("Knowl renamed to {0} successfully.".format(NEWID))) else: k.start_rename(NEWID, who) except ValueError as err: flash_error(str(err), "error") else: if k.sed_safety == 1: flash(Markup("Knowl rename process started. You can change code references using".format(NEWID))) flash(Markup("git grep -l '{0}' | xargs sed -i '' -e 's/{0}/{1}/g' (Mac)".format(ID, NEWID))) flash(Markup("git grep -l '{0}' | xargs sed -i 's/{0}/{1}/g' (Linux)".format(ID, NEWID))) elif k.sed_safety == -1: flash(Markup("Knowl rename process started. This knowl appears in the code (see references below), but cannot trivially be replaced with grep/sed".format(NEWID))) ID = NEWID if k.type == -2: return redirect(url_for(".show", ID=k.source)) else: return redirect(url_for(".show", ID=ID))
def users_all(): if current_user.is_admin(): return render_template("users/all.html", users=User.query.all()) else: abort(403)
def before_request(): if not current_user.is_authenticated or not current_user.is_admin(): abort(401)
def index(): from psycopg2 import DataError cur_cat = request.args.get("category", "") filtermode = request.args.get("filtered") from .knowl import knowl_status_code, knowl_type_code if request.method == 'POST': qualities = [quality for quality in knowl_status_code if request.form.get(quality, "") == "on"] types = [typ for typ in knowl_type_code if request.form.get(typ, "") == "on"] elif request.method == 'GET': qualities = request.args.getlist('qualities') types = request.args.getlist('types') if filtermode: filters = [ q for q in qualities if q in knowl_status_code ] types = [ typ for typ in types if typ in knowl_type_code ] # If "in progress" requested, should add author = current_user.get_id() else: filters = [] types = ["normal"] search = request.args.get("search", "") regex = (request.args.get("regex", "") == "on") keywords = search if regex else search.lower() try: knowls = knowldb.search(category=cur_cat, filters=filters, types=types, keywords=keywords, regex=regex) except DataError as e: knowls = {} if regex and "invalid regular expression" in str(e): flash_error("The string %s is not a valid regular expression", keywords) else: flash_error("Unexpected error %s occured during knowl search", str(e)) def first_char(k): t = k['title'] if len(t) == 0 or t[0] not in string.ascii_letters: return "?" return t[0].upper() def knowl_sort_key(knowl): '''sort knowls, special chars at the end''' title = knowl['title'] if title and title[0] in string.ascii_letters: return (0, title.lower()) else: return (1, title.lower()) knowls = sorted(knowls, key=knowl_sort_key) from itertools import groupby knowls = groupby(knowls, first_char) knowl_qualities = ["reviewed", "beta"] #if current_user.is_authenticated: # knowl_qualities.append("in progress") if current_user.is_admin(): knowl_qualities.append("deleted") b = [] if cur_cat: b = [(cur_cat, url_for('.index', category=cur_cat))] return render_template("knowl-index.html", title="Knowledge Database", bread=get_bread(b), knowls=knowls, search=search, searchbox=searchbox(search, bool(search)), knowl_qualities=knowl_qualities, qualities = qualities, searchmode=bool(search), use_regex=regex, categories = knowldb.get_categories(), cur_cat = cur_cat, categorymode = bool(cur_cat), filtermode = filtermode, knowl_types=list(knowl_type_code), types=types)
def decorated_view(*args, **kwargs): if not current_user.is_admin(): return app.login_manager.unauthorized() return func(*args, **kwargs)
def validate_username(self, username): if username.data != current_user.username and not current_user.is_admin(): user = User.query.filter_by(username=username.data).first() if user: raise ValidationError('That username is already taken 該名稱已被使用')
def validate_email(self, email): if email.data != current_user.email and not current_user.is_admin(): user = User.query.filter_by(email=email.data).first() if user: raise ValidationError('That email is already in use 該電子郵件已被使用')
def check_admin_permissions(): if not current_user.is_authenticated: return "No user is logged in!" if current_user.is_authenticated and not current_user.is_admin(): return "User does not have permissions to access/modify user data."
def _is_editable(location): return location.user_id == current_user.id or current_user.is_admin( ) or current_user.is_editor()
def decorated_function(*args, **kwargs): if not current_user.is_admin(): return redirect(url_for('user_not_admin')) return func(*args, **kwargs)
def invitecodes(page, error=None): """ View and configure Invite Codes """ def map_style(code): if code['uses'] >= code['max_uses']: return 'expired' elif code['expires'] is not None and code[ 'expires'] < datetime.datetime.utcnow(): return 'expired' else: return '' if not current_user.is_admin(): abort(404) invite_settings = { meta.key: meta.value for meta in SiteMetadata.select().where( SiteMetadata.key in ('useinvitecode', 'invite_level', 'invite_max')) } invite_codes = InviteCode.select( InviteCode.code, User.name.alias('created_by'), InviteCode.created, InviteCode.expires, InviteCode.uses, InviteCode.max_uses, ).join(User).order_by(InviteCode.uses.desc(), InviteCode.created.desc()).paginate(page, 50).dicts() code_users = UserMetadata.select( User.name.alias('used_by'), UserMetadata.value.alias("code")).where( (UserMetadata.key == 'invitecode') & (UserMetadata.value << set([x['code'] for x in invite_codes]))).join( User).dicts() used_by = {} for user in code_users: if not user['code'] in used_by: used_by[user['code']] = [] used_by[user['code']].append(user['used_by']) for code in invite_codes: code['style'] = map_style(code) code['used_by'] = used_by.get(code['code'], []) invite_form = UseInviteCodeForm() form = CreateInviteCodeForm() if form.validate_on_submit(): invite = InviteCode() invite.user = current_user.uid if form.code.data: invite.code = form.code.data else: invite.code = ''.join( random.choice('abcdefghijklmnopqrstuvwxyz0123456789') for _ in range(32)) if form.expires.data: invite.expires = form.expires.data invite.max_uses = form.uses.data invite.save() return render_template('admin/invitecodes.html', useinvitecodeform=invite_form, invite_settings=invite_settings, invite_codes=invite_codes, page=page, error=misc.get_errors(form, True), form=form)
def main(): if current_user.is_admin(): return render_template('admin/car/main.html', cars=get_cars(), pghead=get_pghead()) else: flash('You are not an admin!', 'danger') return redirect(url_for("user.members"))
def get(self): """List all stats""" args = parser.parse_args(strict=True) limit = args.get("limit", 0) offset = args.get("offset", 0) type = args.get("type") group_by_anr = args.get("group_by_anr") anrs = args.get("anrs") get_last = args.get("get_last") date_from = args.get("date_from") date_to = args.get("date_to") if not get_last: if date_from is None: date_from = (date.today() + relativedelta(months=-3)).strftime("%Y-%m-%d") if date_to is None: date_to = date.today().strftime("%Y-%m-%d") result = { "data": [], "metadata": { "count": 0, "offset": offset, "limit": limit }, } # type: Dict[str, Any] query = Stats.query if not current_user.is_admin(): query = query.filter(Stats.client_id == current_user.id) query = query.filter(Stats.type == type) if anrs: query = query.filter(Stats.anr.in_(anrs)) if get_last: # TODO: Handle the case if the request is from an admin user (from BO). # Get all the records grouped by anr with max date. results = [] max_date_and_anrs = (query.with_entities( Stats.anr, db.func.max(Stats.date)).group_by(Stats.anr).all()) for max_date_and_anr in max_date_and_anrs: results.append( query.filter( Stats.anr == max_date_and_anr[0], Stats.date == max_date_and_anr[1], ).first()._asdict()) result["data"] = results result["metadata"] = { "count": len(results), "offset": 0, "limit": 0 } return result, 200 query = query.filter(Stats.date >= date_from, Stats.date <= date_to) if limit or offset: results = query.limit(limit).offset(offset).all() result["metadata"]["count"] = len(results) else: results = query.all() result["metadata"]["count"] = len(results) result["data"] = results return result, 200
def decorated_view(*args, **kwags): if not current_user.is_admin(): return abort(403) return func(*args, **kwags)
def chats_all(): if current_user.is_admin(): return render_template("chats/all.html", chats=Chat.all()) abort(403)
def chats_delete(chat_id): if not current_user.is_admin(): abort(403) Chat.delete(chat_id) return redirect(url_for('chats_all'))
def index(self): if current_user.is_authenticated and current_user.is_admin(): self._template_args["usuario"] = current_user return super(AppIndexView, self).index() return redirect(url_for("views.login"))
def tester(*args, **kwargs): message = "Réservé aux administrateurs" return current_user.is_admin(), message, url_for("event.index")